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/serviceTasksMappers";
import * as Parameters from "../models/parameters";
import { DataMigrationServiceClientContext } from "../dataMigrationServiceClientContext";
/** Class representing a ServiceTasks. */
export class ServiceTasks {
private readonly client: DataMigrationServiceClientContext;
/**
* Create a ServiceTasks.
* @param {DataMigrationServiceClientContext} client Reference to the service client.
*/
constructor(client: DataMigrationServiceClientContext) {
this.client = client;
}
/**
* The services resource is the top-level resource that represents the Database Migration Service.
* This method returns a list of service level tasks owned by a service resource. Some tasks may
* have a status of Unknown, which indicates that an error occurred while querying the status of
* that task.
* @summary Get service level tasks for a service
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param [options] The optional parameters
* @returns Promise<Models.ServiceTasksListResponse>
*/
list(groupName: string, serviceName: string, options?: Models.ServiceTasksListOptionalParams): Promise<Models.ServiceTasksListResponse>;
/**
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param callback The callback
*/
list(groupName: string, serviceName: string, callback: msRest.ServiceCallback<Models.TaskList>): void;
/**
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param options The optional parameters
* @param callback The callback
*/
list(groupName: string, serviceName: string, options: Models.ServiceTasksListOptionalParams, callback: msRest.ServiceCallback<Models.TaskList>): void;
list(groupName: string, serviceName: string, options?: Models.ServiceTasksListOptionalParams | msRest.ServiceCallback<Models.TaskList>, callback?: msRest.ServiceCallback<Models.TaskList>): Promise<Models.ServiceTasksListResponse> {
return this.client.sendOperationRequest(
{
groupName,
serviceName,
options
},
listOperationSpec,
callback) as Promise<Models.ServiceTasksListResponse>;
}
/**
* The service tasks resource is a nested, proxy-only resource representing work performed by a DMS
* instance. The PUT method creates a new service task or updates an existing one, although since
* service tasks have no mutable custom properties, there is little reason to update an existing
* one.
* @summary Create or update service task
* @param parameters Information about the task
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param taskName Name of the Task
* @param [options] The optional parameters
* @returns Promise<Models.ServiceTasksCreateOrUpdateResponse>
*/
createOrUpdate(parameters: Models.ProjectTask, groupName: string, serviceName: string, taskName: string, options?: msRest.RequestOptionsBase): Promise<Models.ServiceTasksCreateOrUpdateResponse>;
/**
* @param parameters Information about the task
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param taskName Name of the Task
* @param callback The callback
*/
createOrUpdate(parameters: Models.ProjectTask, groupName: string, serviceName: string, taskName: string, callback: msRest.ServiceCallback<Models.ProjectTask>): void;
/**
* @param parameters Information about the task
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param taskName Name of the Task
* @param options The optional parameters
* @param callback The callback
*/
createOrUpdate(parameters: Models.ProjectTask, groupName: string, serviceName: string, taskName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProjectTask>): void;
createOrUpdate(parameters: Models.ProjectTask, groupName: string, serviceName: string, taskName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProjectTask>, callback?: msRest.ServiceCallback<Models.ProjectTask>): Promise<Models.ServiceTasksCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{
parameters,
groupName,
serviceName,
taskName,
options
},
createOrUpdateOperationSpec,
callback) as Promise<Models.ServiceTasksCreateOrUpdateResponse>;
}
/**
* The service tasks resource is a nested, proxy-only resource representing work performed by a DMS
* instance. The GET method retrieves information about a service task.
* @summary Get service task information
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param taskName Name of the Task
* @param [options] The optional parameters
* @returns Promise<Models.ServiceTasksGetResponse>
*/
get(groupName: string, serviceName: string, taskName: string, options?: Models.ServiceTasksGetOptionalParams): Promise<Models.ServiceTasksGetResponse>;
/**
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param taskName Name of the Task
* @param callback The callback
*/
get(groupName: string, serviceName: string, taskName: string, callback: msRest.ServiceCallback<Models.ProjectTask>): void;
/**
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param taskName Name of the Task
* @param options The optional parameters
* @param callback The callback
*/
get(groupName: string, serviceName: string, taskName: string, options: Models.ServiceTasksGetOptionalParams, callback: msRest.ServiceCallback<Models.ProjectTask>): void;
get(groupName: string, serviceName: string, taskName: string, options?: Models.ServiceTasksGetOptionalParams | msRest.ServiceCallback<Models.ProjectTask>, callback?: msRest.ServiceCallback<Models.ProjectTask>): Promise<Models.ServiceTasksGetResponse> {
return this.client.sendOperationRequest(
{
groupName,
serviceName,
taskName,
options
},
getOperationSpec,
callback) as Promise<Models.ServiceTasksGetResponse>;
}
/**
* The service tasks resource is a nested, proxy-only resource representing work performed by a DMS
* instance. The DELETE method deletes a service task, canceling it first if it's running.
* @summary Delete service task
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param taskName Name of the Task
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(groupName: string, serviceName: string, taskName: string, options?: Models.ServiceTasksDeleteMethodOptionalParams): Promise<msRest.RestResponse>;
/**
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param taskName Name of the Task
* @param callback The callback
*/
deleteMethod(groupName: string, serviceName: string, taskName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param taskName Name of the Task
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(groupName: string, serviceName: string, taskName: string, options: Models.ServiceTasksDeleteMethodOptionalParams, callback: msRest.ServiceCallback<void>): void;
deleteMethod(groupName: string, serviceName: string, taskName: string, options?: Models.ServiceTasksDeleteMethodOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
groupName,
serviceName,
taskName,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* The service tasks resource is a nested, proxy-only resource representing work performed by a DMS
* instance. The PATCH method updates an existing service task, but since service tasks have no
* mutable custom properties, there is little reason to do so.
* @summary Create or update service task
* @param parameters Information about the task
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param taskName Name of the Task
* @param [options] The optional parameters
* @returns Promise<Models.ServiceTasksUpdateResponse>
*/
update(parameters: Models.ProjectTask, groupName: string, serviceName: string, taskName: string, options?: msRest.RequestOptionsBase): Promise<Models.ServiceTasksUpdateResponse>;
/**
* @param parameters Information about the task
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param taskName Name of the Task
* @param callback The callback
*/
update(parameters: Models.ProjectTask, groupName: string, serviceName: string, taskName: string, callback: msRest.ServiceCallback<Models.ProjectTask>): void;
/**
* @param parameters Information about the task
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param taskName Name of the Task
* @param options The optional parameters
* @param callback The callback
*/
update(parameters: Models.ProjectTask, groupName: string, serviceName: string, taskName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProjectTask>): void;
update(parameters: Models.ProjectTask, groupName: string, serviceName: string, taskName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProjectTask>, callback?: msRest.ServiceCallback<Models.ProjectTask>): Promise<Models.ServiceTasksUpdateResponse> {
return this.client.sendOperationRequest(
{
parameters,
groupName,
serviceName,
taskName,
options
},
updateOperationSpec,
callback) as Promise<Models.ServiceTasksUpdateResponse>;
}
/**
* The service tasks resource is a nested, proxy-only resource representing work performed by a DMS
* instance. This method cancels a service task if it's currently queued or running.
* @summary Cancel a service task
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param taskName Name of the Task
* @param [options] The optional parameters
* @returns Promise<Models.ServiceTasksCancelResponse>
*/
cancel(groupName: string, serviceName: string, taskName: string, options?: msRest.RequestOptionsBase): Promise<Models.ServiceTasksCancelResponse>;
/**
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param taskName Name of the Task
* @param callback The callback
*/
cancel(groupName: string, serviceName: string, taskName: string, callback: msRest.ServiceCallback<Models.ProjectTask>): void;
/**
* @param groupName Name of the resource group
* @param serviceName Name of the service
* @param taskName Name of the Task
* @param options The optional parameters
* @param callback The callback
*/
cancel(groupName: string, serviceName: string, taskName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProjectTask>): void;
cancel(groupName: string, serviceName: string, taskName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProjectTask>, callback?: msRest.ServiceCallback<Models.ProjectTask>): Promise<Models.ServiceTasksCancelResponse> {
return this.client.sendOperationRequest(
{
groupName,
serviceName,
taskName,
options
},
cancelOperationSpec,
callback) as Promise<Models.ServiceTasksCancelResponse>;
}
/**
* The services resource is the top-level resource that represents the Database Migration Service.
* This method returns a list of service level tasks owned by a service resource. Some tasks may
* have a status of Unknown, which indicates that an error occurred while querying the status of
* that task.
* @summary Get service level tasks for a service
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.ServiceTasksListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ServiceTasksListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.TaskList>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TaskList>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TaskList>, callback?: msRest.ServiceCallback<Models.TaskList>): Promise<Models.ServiceTasksListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.ServiceTasksListNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/serviceTasks",
urlParameters: [
Parameters.subscriptionId,
Parameters.groupName,
Parameters.serviceName
],
queryParameters: [
Parameters.apiVersion,
Parameters.taskType
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.TaskList
},
default: {
bodyMapper: Mappers.ApiError
}
},
serializer
};
const createOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/serviceTasks/{taskName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.groupName,
Parameters.serviceName,
Parameters.taskName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.ProjectTask,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.ProjectTask
},
201: {
bodyMapper: Mappers.ProjectTask
},
default: {
bodyMapper: Mappers.ApiError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/serviceTasks/{taskName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.groupName,
Parameters.serviceName,
Parameters.taskName
],
queryParameters: [
Parameters.expand,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ProjectTask
},
default: {
bodyMapper: Mappers.ApiError
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/serviceTasks/{taskName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.groupName,
Parameters.serviceName,
Parameters.taskName
],
queryParameters: [
Parameters.deleteRunningTasks,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ApiError
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/serviceTasks/{taskName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.groupName,
Parameters.serviceName,
Parameters.taskName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.ProjectTask,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.ProjectTask
},
default: {
bodyMapper: Mappers.ApiError
}
},
serializer
};
const cancelOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/serviceTasks/{taskName}/cancel",
urlParameters: [
Parameters.subscriptionId,
Parameters.groupName,
Parameters.serviceName,
Parameters.taskName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ProjectTask
},
default: {
bodyMapper: Mappers.ApiError
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.TaskList
},
default: {
bodyMapper: Mappers.ApiError
}
},
serializer
}; | the_stack |
import { Resolver, schemaComposer, ObjectTypeComposer } from 'graphql-compose';
import { GraphQLList, GraphQLNonNull } from 'graphql-compose/lib/graphql';
import { mongoose } from '../../__mocks__/mongooseCommon';
import { UserModel, IUser } from '../../__mocks__/userModel';
import { convertModelToGraphQL } from '../../fieldsConverter';
import { createMany } from '../createMany';
import { ExtendedResolveParams } from '..';
import { testFieldConfig } from '../../utils/testHelpers';
beforeAll(() => UserModel.base.createConnection());
afterAll(() => UserModel.base.disconnect());
describe('createMany() ->', () => {
let UserTC: ObjectTypeComposer;
beforeEach(() => {
schemaComposer.clear();
UserTC = convertModelToGraphQL(UserModel, 'User', schemaComposer);
UserTC.setRecordIdFn((source) => (source ? `${source._id}` : ''));
});
beforeEach(async () => {
await UserModel.deleteMany({});
});
it('should return Resolver object', () => {
const resolver = createMany(UserModel, UserTC);
expect(resolver).toBeInstanceOf(Resolver);
});
describe('Resolver.args', () => {
it('should have required `records` arg', () => {
const resolver = createMany(UserModel, UserTC);
const argConfig: any = resolver.getArgConfig('records');
expect(argConfig.type).toBeInstanceOf(GraphQLNonNull);
expect(argConfig.type.toString()).toBe('[CreateManyUserInput!]!');
});
it('should have `records` arg as Plural', () => {
const resolver = createMany(UserModel, UserTC);
const argConfig: any = resolver.getArgConfig('records');
expect(argConfig.type.ofType).toBeInstanceOf(GraphQLList);
expect(argConfig.type.ofType.toString()).toBe('[CreateManyUserInput!]');
});
it('should have `records` arg internal item as required', () => {
const resolver = createMany(UserModel, UserTC);
const argConfig: any = resolver.getArgConfig('records');
expect(argConfig.type).toBeInstanceOf(GraphQLNonNull);
expect(argConfig.type.ofType.ofType.toString()).toBe('CreateManyUserInput!');
});
});
describe('Resolver.resolve():Promise', () => {
it('should be promise', () => {
const result = createMany(UserModel, UserTC).resolve({});
expect(result).toBeInstanceOf(Promise);
result.catch(() => 'catch error if appear, hide it from mocha');
});
it('should rejected with Error if args.records is empty', async () => {
const result = createMany(UserModel, UserTC).resolve({
// @ts-expect-error
args: {},
});
await expect(result).rejects.toThrow(
'User.createMany resolver requires args.records to be an Array and must contain at least one record'
);
});
it('should rejected with Error if args.records is not array', async () => {
const result = createMany(UserModel, UserTC).resolve({
args: {
// @ts-expect-error
records: {},
},
});
await expect(result).rejects.toThrow(
'ser.createMany resolver requires args.records to be an Array and must contain at least one record'
);
});
it('should rejected with Error if args.records is empty array', async () => {
const result = createMany(UserModel, UserTC).resolve({
args: { records: [] },
});
await expect(result).rejects.toThrow(
'User.createMany resolver requires args.records to be an Array and must contain at least one record'
);
});
it('should rejected with Error if args.records is array with empty items', async () => {
const result = createMany(UserModel, UserTC).resolve({
args: { records: [{ name: 'fails' }, {}] },
});
await expect(result).rejects.toThrow(
'User.createMany resolver requires args.records to contain non-empty records, with at least one value'
);
});
it('should return payload.recordIds', async () => {
const result = await testFieldConfig({
field: createMany(UserModel, UserTC),
args: { records: [{ name: 'newName', contacts: { email: 'mail' } }] },
selection: `{
recordIds
}`,
});
expect(result.recordIds).toBeTruthy();
});
it('should create documents with args.records and match createCount', async () => {
const result = await createMany(UserModel, UserTC).resolve({
args: {
records: [
{ name: 'newName0', contacts: { email: 'mail' } },
{ name: 'newName1', contacts: { email: 'mail' } },
],
},
projection: { error: true },
});
expect(result.createdCount).toBe(2);
expect(result.records[0].name).toBe('newName0');
expect(result.records[1].name).toBe('newName1');
});
it('should return resolver runtime error in payload.error', async () => {
const resolver = createMany(UserModel, UserTC);
await expect(resolver.resolve({ projection: { error: true } })).resolves.toEqual({
error: expect.objectContaining({
message: expect.stringContaining('requires args.records to be an Array'),
}),
});
// should throw error if error not requested in graphql query
await expect(resolver.resolve({})).rejects.toThrowError(
'requires args.records to be an Array'
);
});
it('should save documents to database', async () => {
const checkedName = 'nameForMongoDB';
const res = await testFieldConfig({
field: createMany(UserModel, UserTC),
args: {
records: [
{ name: checkedName, contacts: { email: 'mail' } },
{ name: checkedName, contacts: { email: 'mail' } },
],
},
selection: `{
records {
_id
}
recordIds
}`,
});
const docs = await UserModel.collection
.find({ _id: { $in: res.recordIds.map((o: string) => new mongoose.Types.ObjectId(o)) } })
.toArray();
expect(docs.length).toBe(2);
expect(docs[0].n).toBe(checkedName);
expect(docs[1].n).toBe(checkedName);
});
it('should return payload.records', async () => {
const result = await testFieldConfig({
field: createMany(UserModel, UserTC),
args: { records: [{ name: 'newName', contacts: { email: 'mail' } }] },
selection: `{
records {
_id
}
recordIds
}`,
});
expect(result.records[0]._id).toBe(result.recordIds[0]);
});
it('should return mongoose documents', async () => {
const result = await createMany(UserModel, UserTC).resolve({
args: { records: [{ name: 'NewUser', contacts: { email: 'mail' } }] },
projection: { error: true },
});
expect(result.records[0]).toBeInstanceOf(UserModel);
});
it('should call `beforeRecordMutate` method with each created `record` and `resolveParams` as args', async () => {
const result = await createMany(UserModel, UserTC).resolve({
args: {
records: [
{ name: 'NewUser0', contacts: { email: 'mail' } },
{ name: 'NewUser1', contacts: { email: 'mail' } },
],
},
projection: { error: true },
context: { ip: '1.1.1.1' },
beforeRecordMutate: (record: any, rp: ExtendedResolveParams) => {
record.name = 'OverriddenName';
record.someDynamic = rp.context.ip;
return record;
},
});
expect(result.records[0]).toBeInstanceOf(UserModel);
expect(result.records[1]).toBeInstanceOf(UserModel);
expect(result.records[0].name).toBe('OverriddenName');
expect(result.records[1].name).toBe('OverriddenName');
expect(result.records[0].someDynamic).toBe('1.1.1.1');
expect(result.records[1].someDynamic).toBe('1.1.1.1');
});
it('should execute hooks on save', async () => {
schemaComposer.clear();
const ClonedUserSchema = UserModel.schema.clone();
ClonedUserSchema.pre<IUser>('save', function (next) {
this.name = 'ChangedAgain';
this.age = 18;
return next();
});
const ClonedUserModel = mongoose.model('UserClone', ClonedUserSchema);
const ClonedUserTC = convertModelToGraphQL(ClonedUserModel, 'UserClone', schemaComposer);
ClonedUserTC.setRecordIdFn((source: any) => (source ? `${source._id}` : ''));
const result = await createMany(ClonedUserModel, ClonedUserTC).resolve({
args: {
records: [
{ name: 'NewUser0', contacts: { email: 'mail' } },
{ name: 'NewUser1', contacts: { email: 'mail' } },
],
},
projection: { error: true },
context: { ip: '1.1.1.1' },
beforeRecordMutate: (record: any, rp: ExtendedResolveParams) => {
record.name = 'OverriddenName';
record.someDynamic = rp.context.ip;
return record;
},
});
expect(result.records[0]).toBeInstanceOf(ClonedUserModel);
expect(result.records[1]).toBeInstanceOf(ClonedUserModel);
expect(result.records[0].age).toBe(18);
expect(result.records[1].age).toBe(18);
expect(result.records[0].name).toBe('ChangedAgain');
expect(result.records[1].name).toBe('ChangedAgain');
expect(result.records[0].someDynamic).toBe('1.1.1.1');
expect(result.records[1].someDynamic).toBe('1.1.1.1');
});
});
describe('Resolver.getType()', () => {
it('should have correct output type name', () => {
const resolver: any = createMany(UserModel, UserTC);
expect(resolver.getTypeName()).toBe(`CreateMany${UserTC.getTypeName()}Payload`);
expect(resolver.getArgITC('records').getFieldTypeName('name')).toBe('String!');
expect(resolver.getArgITC('records').getFieldTypeName('age')).toBe('Float');
});
it('should have recordIds field, NonNull List', () => {
const resolver = createMany(UserModel, UserTC);
expect(resolver.getOTC().getFieldTypeName('recordIds')).toEqual('[MongoID!]!');
});
it('should have records field, NonNull List', () => {
const resolver = createMany(UserModel, UserTC);
expect(resolver.getOTC().getFieldTypeName('records')).toEqual('[User!]');
});
it('should have user.contacts.mail required field', () => {
const resolver = createMany(UserModel, UserTC);
expect(resolver.getArgITC('records').getFieldITC('contacts').getFieldTypeName('email')).toBe(
'String!'
);
});
it('should have createdCount field, Int', () => {
expect(createMany(UserModel, UserTC).getOTC().getFieldTypeName('createdCount')).toEqual(
'Int!'
);
});
it('should reuse existed outputType', () => {
const outputTypeName = `CreateMany${UserTC.getTypeName()}Payload`;
const existedType = schemaComposer.createObjectTC(outputTypeName);
schemaComposer.set(outputTypeName, existedType);
const outputType = createMany(UserModel, UserTC).getType();
expect(outputType).toBe(existedType.getType());
});
});
}); | the_stack |
import { extname } from 'path'
export function mime(filePath: string): string {
switch (extname(filePath)) {
case '.123':
return 'application/vnd.lotus-1-2-3'
case '.3dml':
return 'text/vnd.in3d.3dml'
case '.3ds':
return 'image/x-3ds'
case '.3g2':
return 'video/3gpp2'
case '.3gp':
return 'video/3gpp'
case '.7z':
return 'application/x-7z-compressed'
case '.aab':
return 'application/x-authorware-bin'
case '.aac':
return 'audio/x-aac'
case '.aam':
return 'application/x-authorware-map'
case '.aas':
return 'application/x-authorware-seg'
case '.abw':
return 'application/x-abiword'
case '.ac':
return 'application/pkix-attr-cert'
case '.acc':
return 'application/vnd.americandynamics.acc'
case '.ace':
return 'application/x-ace-compressed'
case '.acu':
return 'application/vnd.acucobol'
case '.acutc':
return 'application/vnd.acucorp'
case '.adp':
return 'audio/adpcm'
case '.aep':
return 'application/vnd.audiograph'
case '.afm':
return 'application/x-font-type1'
case '.afp':
return 'application/vnd.ibm.modcap'
case '.ahead':
return 'application/vnd.ahead.space'
case '.ai':
return 'application/postscript'
case '.aif':
return 'audio/x-aiff'
case '.aifc':
return 'audio/x-aiff'
case '.aiff':
return 'audio/x-aiff'
case '.air':
return 'application/vnd.adobe.air-application-installer-package+zip'
case '.ait':
return 'application/vnd.dvb.ait'
case '.ami':
return 'application/vnd.amiga.ami'
case '.apk':
return 'application/vnd.android.package-archive'
case '.appcache':
return 'text/cache-manifest'
case '.application':
return 'application/x-ms-application'
case '.apr':
return 'application/vnd.lotus-approach'
case '.arc':
return 'application/x-freearc'
case '.asax':
return 'text/csharp'
case '.asc':
return 'application/pgp-signature'
case '.asf':
return 'video/x-ms-asf'
case '.asm':
return 'text/x-asm'
case '.aso':
return 'application/vnd.accpac.simply.aso'
case '.asx':
return 'video/x-ms-asf'
case '.atc':
return 'application/vnd.acucorp'
case '.atom':
return 'application/atom+xml'
case '.atomcat':
return 'application/atomcat+xml'
case '.atomsvc':
return 'application/atomsvc+xml'
case '.atx':
return 'application/vnd.antix.game-component'
case '.au':
return 'audio/basic'
case '.avi':
return 'video/x-msvideo'
case '.aw':
return 'application/applixware'
case '.azf':
return 'application/vnd.airzip.filesecure.azf'
case '.azs':
return 'application/vnd.airzip.filesecure.azs'
case '.azw':
return 'application/vnd.amazon.ebook'
case '.bat':
return 'application/x-msdownload'
case '.bcpio':
return 'application/x-bcpio'
case '.bdf':
return 'application/x-font-bdf'
case '.bdm':
return 'application/vnd.syncml.dm+wbxml'
case '.bed':
return 'application/vnd.realvnc.bed'
case '.bh2':
return 'application/vnd.fujitsu.oasysprs'
case '.bin':
return 'application/octet-stream'
case '.blb':
return 'application/x-blorb'
case '.blorb':
return 'application/x-blorb'
case '.bmi':
return 'application/vnd.bmi'
case '.bmp':
return 'image/bmp'
case '.book':
return 'application/vnd.framemaker'
case '.box':
return 'application/vnd.previewsystems.box'
case '.boz':
return 'application/x-bzip2'
case '.bpk':
return 'application/octet-stream'
case '.btif':
return 'image/prs.btif'
case '.bz':
return 'application/x-bzip'
case '.bz2':
return 'application/x-bzip2'
case '.c':
return 'text/x-c'
case '.c11amc':
return 'application/vnd.cluetrust.cartomobile-config'
case '.c11amz':
return 'application/vnd.cluetrust.cartomobile-config-pkg'
case '.c4d':
return 'application/vnd.clonk.c4group'
case '.c4f':
return 'application/vnd.clonk.c4group'
case '.c4g':
return 'application/vnd.clonk.c4group'
case '.c4p':
return 'application/vnd.clonk.c4group'
case '.c4u':
return 'application/vnd.clonk.c4group'
case '.cab':
return 'application/vnd.ms-cab-compressed'
case '.caf':
return 'audio/x-caf'
case '.cap':
return 'application/vnd.tcpdump.pcap'
case '.car':
return 'application/vnd.curl.car'
case '.cat':
return 'application/vnd.ms-pki.seccat'
case '.cb7':
return 'application/x-cbr'
case '.cba':
return 'application/x-cbr'
case '.cbr':
return 'application/x-cbr'
case '.cbt':
return 'application/x-cbr'
case '.cbz':
return 'application/x-cbr'
case '.cc':
return 'text/x-c'
case '.cct':
return 'application/x-director'
case '.ccxml':
return 'application/ccxml+xml'
case '.cdbcmsg':
return 'application/vnd.contact.cmsg'
case '.cdf':
return 'application/x-netcdf'
case '.cdkey':
return 'application/vnd.mediastation.cdkey'
case '.cdmia':
return 'application/cdmi-capability'
case '.cdmic':
return 'application/cdmi-container'
case '.cdmid':
return 'application/cdmi-domain'
case '.cdmio':
return 'application/cdmi-object'
case '.cdmiq':
return 'application/cdmi-queue'
case '.cdx':
return 'chemical/x-cdx'
case '.cdxml':
return 'application/vnd.chemdraw+xml'
case '.cdy':
return 'application/vnd.cinderella'
case '.cer':
return 'application/pkix-cert'
case '.cfs':
return 'application/x-cfs-compressed'
case '.cgm':
return 'image/cgm'
case '.chat':
return 'application/x-chat'
case '.chm':
return 'application/vnd.ms-htmlhelp'
case '.chrt':
return 'application/vnd.kde.kchart'
case '.cif':
return 'chemical/x-cif'
case '.cii':
return 'application/vnd.anser-web-certificate-issue-initiation'
case '.cil':
return 'application/vnd.ms-artgalry'
case '.cla':
return 'application/vnd.claymore'
case '.class':
return 'application/java-vm'
case '.clkk':
return 'application/vnd.crick.clicker.keyboard'
case '.clkp':
return 'application/vnd.crick.clicker.palette'
case '.clkt':
return 'application/vnd.crick.clicker.template'
case '.clkw':
return 'application/vnd.crick.clicker.wordbank'
case '.clkx':
return 'application/vnd.crick.clicker'
case '.clp':
return 'application/x-msclip'
case '.cmc':
return 'application/vnd.cosmocaller'
case '.cmdf':
return 'chemical/x-cmdf'
case '.cml':
return 'chemical/x-cml'
case '.cmp':
return 'application/vnd.yellowriver-custom-menu'
case '.cmx':
return 'image/x-cmx'
case '.cod':
return 'application/vnd.rim.cod'
case '.config':
return 'text/xml'
case '.com':
return 'application/x-msdownload'
case '.conf':
return 'text/plain'
case '.cpio':
return 'application/x-cpio'
case '.cpp':
return 'text/x-c'
case '.cpt':
return 'application/mac-compactpro'
case '.crd':
return 'application/x-mscardfile'
case '.crl':
return 'application/pkix-crl'
case '.crt':
return 'application/x-x509-ca-cert'
case '.cryptonote':
return 'application/vnd.rig.cryptonote'
case '.csh':
return 'application/x-csh'
case '.csml':
return 'chemical/x-csml'
case '.csp':
return 'application/vnd.commonspace'
case '.cs':
return 'text/csharp'
case '.css':
return 'text/css'
case '.cst':
return 'application/x-director'
case '.csv':
return 'text/csv'
case '.cu':
return 'application/cu-seeme'
case '.curl':
return 'text/vnd.curl'
case '.cww':
return 'application/prs.cww'
case '.cxt':
return 'application/x-director'
case '.cxx':
return 'text/x-c'
case '.dae':
return 'model/vnd.collada+xml'
case '.daf':
return 'application/vnd.mobius.daf'
case '.dart':
return 'application/vnd.dart'
case '.dataless':
return 'application/vnd.fdsn.seed'
case '.davmount':
return 'application/davmount+xml'
case '.dbk':
return 'application/docbook+xml'
case '.dcr':
return 'application/x-director'
case '.dcurl':
return 'text/vnd.curl.dcurl'
case '.dd2':
return 'application/vnd.oma.dd2+xml'
case '.ddd':
return 'application/vnd.fujixerox.ddd'
case '.deb':
return 'application/x-debian-package'
case '.def':
return 'text/plain'
case '.deploy':
return 'application/octet-stream'
case '.der':
return 'application/x-x509-ca-cert'
case '.dfac':
return 'application/vnd.dreamfactory'
case '.dgc':
return 'application/x-dgc-compressed'
case '.dic':
return 'text/x-c'
case '.dir':
return 'application/x-director'
case '.dis':
return 'application/vnd.mobius.dis'
case '.dist':
return 'application/octet-stream'
case '.distz':
return 'application/octet-stream'
case '.djv':
return 'image/vnd.djvu'
case '.djvu':
return 'image/vnd.djvu'
case '.dll':
return 'application/x-msdownload'
case '.dmg':
return 'application/x-apple-diskimage'
case '.dmp':
return 'application/vnd.tcpdump.pcap'
case '.dms':
return 'application/octet-stream'
case '.dna':
return 'application/vnd.dna'
case '.doc':
return 'application/msword'
case '.docm':
return 'application/vnd.ms-word.document.macroenabled.12'
case '.docx':
return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
case '.dot':
return 'application/msword'
case '.dotm':
return 'application/vnd.ms-word.template.macroenabled.12'
case '.dotx':
return 'application/vnd.openxmlformats-officedocument.wordprocessingml.template'
case '.dp':
return 'application/vnd.osgi.dp'
case '.dpg':
return 'application/vnd.dpgraph'
case '.dra':
return 'audio/vnd.dra'
case '.dsc':
return 'text/prs.lines.tag'
case '.dssc':
return 'application/dssc+der'
case '.dtb':
return 'application/x-dtbook+xml'
case '.dtd':
return 'application/xml-dtd'
case '.dts':
return 'audio/vnd.dts'
case '.dtshd':
return 'audio/vnd.dts.hd'
case '.dump':
return 'application/octet-stream'
case '.dvb':
return 'video/vnd.dvb.file'
case '.dvi':
return 'application/x-dvi'
case '.dwf':
return 'model/vnd.dwf'
case '.dwg':
return 'image/vnd.dwg'
case '.dxf':
return 'image/vnd.dxf'
case '.dxp':
return 'application/vnd.spotfire.dxp'
case '.dxr':
return 'application/x-director'
case '.ecelp4800':
return 'audio/vnd.nuera.ecelp4800'
case '.ecelp7470':
return 'audio/vnd.nuera.ecelp7470'
case '.ecelp9600':
return 'audio/vnd.nuera.ecelp9600'
case '.ecma':
return 'application/ecmascript'
case '.edm':
return 'application/vnd.novadigm.edm'
case '.edx':
return 'application/vnd.novadigm.edx'
case '.efif':
return 'application/vnd.picsel'
case '.ei6':
return 'application/vnd.pg.osasli'
case '.elc':
return 'application/octet-stream'
case '.emf':
return 'application/x-msmetafile'
case '.eml':
return 'message/rfc822'
case '.emma':
return 'application/emma+xml'
case '.emz':
return 'application/x-msmetafile'
case '.eol':
return 'audio/vnd.digital-winds'
case '.eot':
return 'application/vnd.ms-fontobject'
case '.eps':
return 'application/postscript'
case '.epub':
return 'application/epub+zip'
case '.es3':
return 'application/vnd.eszigno3+xml'
case '.esa':
return 'application/vnd.osgi.subsystem'
case '.esf':
return 'application/vnd.epson.esf'
case '.et3':
return 'application/vnd.eszigno3+xml'
case '.etx':
return 'text/x-setext'
case '.eva':
return 'application/x-eva'
case '.evy':
return 'application/x-envoy'
case '.exe':
return 'application/x-msdownload'
case '.exi':
return 'application/exi'
case '.ext':
return 'application/vnd.novadigm.ext'
case '.ez':
return 'application/andrew-inset'
case '.ez2':
return 'application/vnd.ezpix-album'
case '.ez3':
return 'application/vnd.ezpix-package'
case '.f':
return 'text/x-fortran'
case '.f4v':
return 'video/x-f4v'
case '.f77':
return 'text/x-fortran'
case '.f90':
return 'text/x-fortran'
case '.fbs':
return 'image/vnd.fastbidsheet'
case '.fcdt':
return 'application/vnd.adobe.formscentral.fcdt'
case '.fcs':
return 'application/vnd.isac.fcs'
case '.fdf':
return 'application/vnd.fdf'
case '.fe_launch':
return 'application/vnd.denovo.fcselayout-link'
case '.fg5':
return 'application/vnd.fujitsu.oasysgp'
case '.fgd':
return 'application/x-director'
case '.fh':
return 'image/x-freehand'
case '.fh4':
return 'image/x-freehand'
case '.fh5':
return 'image/x-freehand'
case '.fh7':
return 'image/x-freehand'
case '.fhc':
return 'image/x-freehand'
case '.fig':
return 'application/x-xfig'
case '.flac':
return 'audio/x-flac'
case '.fli':
return 'video/x-fli'
case '.flo':
return 'application/vnd.micrografx.flo'
case '.flv':
return 'video/x-flv'
case '.flw':
return 'application/vnd.kde.kivio'
case '.flx':
return 'text/vnd.fmi.flexstor'
case '.fly':
return 'text/vnd.fly'
case '.fm':
return 'application/vnd.framemaker'
case '.fnc':
return 'application/vnd.frogans.fnc'
case '.for':
return 'text/x-fortran'
case '.fpx':
return 'image/vnd.fpx'
case '.frame':
return 'application/vnd.framemaker'
case '.fsc':
return 'application/vnd.fsc.weblaunch'
case '.fst':
return 'image/vnd.fst'
case '.ftc':
return 'application/vnd.fluxtime.clip'
case '.fti':
return 'application/vnd.anser-web-funds-transfer-initiation'
case '.fvt':
return 'video/vnd.fvt'
case '.fxp':
return 'application/vnd.adobe.fxp'
case '.fxpl':
return 'application/vnd.adobe.fxp'
case '.fzs':
return 'application/vnd.fuzzysheet'
case '.g2w':
return 'application/vnd.geoplan'
case '.g3':
return 'image/g3fax'
case '.g3w':
return 'application/vnd.geospace'
case '.gac':
return 'application/vnd.groove-account'
case '.gam':
return 'application/x-tads'
case '.gbr':
return 'application/rpki-ghostbusters'
case '.gca':
return 'application/x-gca-compressed'
case '.gdl':
return 'model/vnd.gdl'
case '.geo':
return 'application/vnd.dynageo'
case '.gex':
return 'application/vnd.geometry-explorer'
case '.ggb':
return 'application/vnd.geogebra.file'
case '.ggt':
return 'application/vnd.geogebra.tool'
case '.ghf':
return 'application/vnd.groove-help'
case '.gif':
return 'image/gif'
case '.gim':
return 'application/vnd.groove-identity-message'
case '.glb':
return 'model/gltf-binary'
case '.gltf':
return 'model/gltf+json'
case '.gml':
return 'application/gml+xml'
case '.gmx':
return 'application/vnd.gmx'
case '.gnumeric':
return 'application/x-gnumeric'
case '.gph':
return 'application/vnd.flographit'
case '.gpx':
return 'application/gpx+xml'
case '.gqf':
return 'application/vnd.grafeq'
case '.gqs':
return 'application/vnd.grafeq'
case '.gram':
return 'application/srgs'
case '.gramps':
return 'application/x-gramps-xml'
case '.gre':
return 'application/vnd.geometry-explorer'
case '.grv':
return 'application/vnd.groove-injector'
case '.grxml':
return 'application/srgs+xml'
case '.gsf':
return 'application/x-font-ghostscript'
case '.gtar':
return 'application/x-gtar'
case '.gtm':
return 'application/vnd.groove-tool-message'
case '.gtw':
return 'model/vnd.gtw'
case '.gv':
return 'text/vnd.graphviz'
case '.gxf':
return 'application/gxf'
case '.gxt':
return 'application/vnd.geonext'
case '.h':
return 'text/x-c'
case '.h261':
return 'video/h261'
case '.h263':
return 'video/h263'
case '.h264':
return 'video/h264'
case '.hal':
return 'application/vnd.hal+xml'
case '.hbci':
return 'application/vnd.hbci'
case '.hdf':
return 'application/x-hdf'
case '.hh':
return 'text/x-c'
case '.hlp':
return 'application/winhlp'
case '.hpgl':
return 'application/vnd.hp-hpgl'
case '.hpid':
return 'application/vnd.hp-hpid'
case '.hps':
return 'application/vnd.hp-hps'
case '.hqx':
return 'application/mac-binhex40'
case '.htke':
return 'application/vnd.kenameaapp'
case '.htm':
return 'text/html'
case '.html':
return 'text/html'
case '.cshtml':
return 'text/html'
case '.hvd':
return 'application/vnd.yamaha.hv-dic'
case '.hvp':
return 'application/vnd.yamaha.hv-voice'
case '.hvs':
return 'application/vnd.yamaha.hv-script'
case '.i2g':
return 'application/vnd.intergeo'
case '.icc':
return 'application/vnd.iccprofile'
case '.ice':
return 'x-conference/x-cooltalk'
case '.icm':
return 'application/vnd.iccprofile'
case '.ico':
return 'image/x-icon'
case '.ics':
return 'text/calendar'
case '.ief':
return 'image/ief'
case '.ifb':
return 'text/calendar'
case '.ifm':
return 'application/vnd.shana.informed.formdata'
case '.iges':
return 'model/iges'
case '.igl':
return 'application/vnd.igloader'
case '.igm':
return 'application/vnd.insors.igm'
case '.igs':
return 'model/iges'
case '.igx':
return 'application/vnd.micrografx.igx'
case '.iif':
return 'application/vnd.shana.informed.interchange'
case '.imp':
return 'application/vnd.accpac.simply.imp'
case '.ims':
return 'application/vnd.ms-ims'
case '.in':
return 'text/plain'
case '.ink':
return 'application/inkml+xml'
case '.inkml':
return 'application/inkml+xml'
case '.install':
return 'application/x-install-instructions'
case '.iota':
return 'application/vnd.astraea-software.iota'
case '.ipfix':
return 'application/ipfix'
case '.ipk':
return 'application/vnd.shana.informed.package'
case '.irm':
return 'application/vnd.ibm.rights-management'
case '.irp':
return 'application/vnd.irepository.package+xml'
case '.iso':
return 'application/x-iso9660-image'
case '.itp':
return 'application/vnd.shana.informed.formtemplate'
case '.ivp':
return 'application/vnd.immervision-ivp'
case '.ivu':
return 'application/vnd.immervision-ivu'
case '.jad':
return 'text/vnd.sun.j2me.app-descriptor'
case '.jam':
return 'application/vnd.jam'
case '.jar':
return 'application/java-archive'
case '.java':
return 'text/x-java-source'
case '.jisp':
return 'application/vnd.jisp'
case '.jlt':
return 'application/vnd.hp-jlyt'
case '.jnlp':
return 'application/x-java-jnlp-file'
case '.joda':
return 'application/vnd.joost.joda-archive'
case '.jpe':
return 'image/jpeg'
case '.jpeg':
return 'image/jpeg'
case '.jpg':
return 'image/jpeg'
case '.jpgm':
return 'video/jpm'
case '.jpgv':
return 'video/jpeg'
case '.jpm':
return 'video/jpm'
case '.js':
return 'application/javascript'
case '.json':
return 'application/json'
case '.jsonml':
return 'application/jsonml+json'
case '.kar':
return 'audio/midi'
case '.karbon':
return 'application/vnd.kde.karbon'
case '.kfo':
return 'application/vnd.kde.kformula'
case '.kia':
return 'application/vnd.kidspiration'
case '.kml':
return 'application/vnd.google-earth.kml+xml'
case '.kmz':
return 'application/vnd.google-earth.kmz'
case '.kne':
return 'application/vnd.kinar'
case '.knp':
return 'application/vnd.kinar'
case '.kon':
return 'application/vnd.kde.kontour'
case '.kpr':
return 'application/vnd.kde.kpresenter'
case '.kpt':
return 'application/vnd.kde.kpresenter'
case '.kpxx':
return 'application/vnd.ds-keypoint'
case '.ksp':
return 'application/vnd.kde.kspread'
case '.ktr':
return 'application/vnd.kahootz'
case '.ktx':
return 'image/ktx'
case '.ktz':
return 'application/vnd.kahootz'
case '.kwd':
return 'application/vnd.kde.kword'
case '.kwt':
return 'application/vnd.kde.kword'
case '.lasxml':
return 'application/vnd.las.las+xml'
case '.latex':
return 'application/x-latex'
case '.lbd':
return 'application/vnd.llamagraphics.life-balance.desktop'
case '.lbe':
return 'application/vnd.llamagraphics.life-balance.exchange+xml'
case '.les':
return 'application/vnd.hhe.lesson-player'
case '.lha':
return 'application/x-lzh-compressed'
case '.link66':
return 'application/vnd.route66.link66+xml'
case '.list':
return 'text/plain'
case '.list3820':
return 'application/vnd.ibm.modcap'
case '.listafp':
return 'application/vnd.ibm.modcap'
case '.lnk':
return 'application/x-ms-shortcut'
case '.log':
return 'text/plain'
case '.lostxml':
return 'application/lost+xml'
case '.lrf':
return 'application/octet-stream'
case '.lrm':
return 'application/vnd.ms-lrm'
case '.ltf':
return 'application/vnd.frogans.ltf'
case '.lvp':
return 'audio/vnd.lucent.voice'
case '.lwp':
return 'application/vnd.lotus-wordpro'
case '.lzh':
return 'application/x-lzh-compressed'
case '.m13':
return 'application/x-msmediaview'
case '.m14':
return 'application/x-msmediaview'
case '.m1v':
return 'video/mpeg'
case '.m21':
return 'application/mp21'
case '.m2a':
return 'audio/mpeg'
case '.m2v':
return 'video/mpeg'
case '.m3a':
return 'audio/mpeg'
case '.m3u':
return 'audio/x-mpegurl'
case '.m3u8':
return 'application/vnd.apple.mpegurl'
case '.m4u':
return 'video/vnd.mpegurl'
case '.m4v':
return 'video/x-m4v'
case '.ma':
return 'application/mathematica'
case '.mads':
return 'application/mads+xml'
case '.mag':
return 'application/vnd.ecowin.chart'
case '.maker':
return 'application/vnd.framemaker'
case '.man':
return 'text/troff'
case '.mar':
return 'application/octet-stream'
case '.mathml':
return 'application/mathml+xml'
case '.mb':
return 'application/mathematica'
case '.mbk':
return 'application/vnd.mobius.mbk'
case '.mbox':
return 'application/mbox'
case '.mc1':
return 'application/vnd.medcalcdata'
case '.mcd':
return 'application/vnd.mcd'
case '.mcurl':
return 'text/vnd.curl.mcurl'
case '.mdb':
return 'application/x-msaccess'
case '.mdi':
return 'image/vnd.ms-modi'
case '.me':
return 'text/troff'
case '.mesh':
return 'model/mesh'
case '.meta4':
return 'application/metalink4+xml'
case '.metalink':
return 'application/metalink+xml'
case '.mets':
return 'application/mets+xml'
case '.mfm':
return 'application/vnd.mfmp'
case '.mft':
return 'application/rpki-manifest'
case '.mgp':
return 'application/vnd.osgeo.mapguide.package'
case '.mgz':
return 'application/vnd.proteus.magazine'
case '.mid':
return 'audio/midi'
case '.midi':
return 'audio/midi'
case '.mie':
return 'application/x-mie'
case '.mif':
return 'application/vnd.mif'
case '.mime':
return 'message/rfc822'
case '.mj2':
return 'video/mj2'
case '.mjp2':
return 'video/mj2'
case '.mk3d':
return 'video/x-matroska'
case '.mka':
return 'audio/x-matroska'
case '.mks':
return 'video/x-matroska'
case '.mkv':
return 'video/x-matroska'
case '.mlp':
return 'application/vnd.dolby.mlp'
case '.mmd':
return 'application/vnd.chipnuts.karaoke-mmd'
case '.mmf':
return 'application/vnd.smaf'
case '.mmr':
return 'image/vnd.fujixerox.edmics-mmr'
case '.mng':
return 'video/x-mng'
case '.mny':
return 'application/x-msmoney'
case '.mobi':
return 'application/x-mobipocket-ebook'
case '.mods':
return 'application/mods+xml'
case '.mov':
return 'video/quicktime'
case '.movie':
return 'video/x-sgi-movie'
case '.mp2':
return 'audio/mpeg'
case '.mp21':
return 'application/mp21'
case '.mp2a':
return 'audio/mpeg'
case '.mp3':
return 'audio/mpeg'
case '.mp4':
return 'video/mp4'
case '.mp4a':
return 'audio/mp4'
case '.mp4s':
return 'application/mp4'
case '.mp4v':
return 'video/mp4'
case '.mpc':
return 'application/vnd.mophun.certificate'
case '.mpe':
return 'video/mpeg'
case '.mpeg':
return 'video/mpeg'
case '.mpg':
return 'video/mpeg'
case '.mpg4':
return 'video/mp4'
case '.mpga':
return 'audio/mpeg'
case '.mpkg':
return 'application/vnd.apple.installer+xml'
case '.mpm':
return 'application/vnd.blueice.multipass'
case '.mpn':
return 'application/vnd.mophun.application'
case '.mpp':
return 'application/vnd.ms-project'
case '.mpt':
return 'application/vnd.ms-project'
case '.mpy':
return 'application/vnd.ibm.minipay'
case '.mqy':
return 'application/vnd.mobius.mqy'
case '.mrc':
return 'application/marc'
case '.mrcx':
return 'application/marcxml+xml'
case '.ms':
return 'text/troff'
case '.mscml':
return 'application/mediaservercontrol+xml'
case '.mseed':
return 'application/vnd.fdsn.mseed'
case '.mseq':
return 'application/vnd.mseq'
case '.msf':
return 'application/vnd.epson.msf'
case '.msh':
return 'model/mesh'
case '.msi':
return 'application/x-msdownload'
case '.msl':
return 'application/vnd.mobius.msl'
case '.msty':
return 'application/vnd.muvee.style'
case '.mts':
return 'model/vnd.mts'
case '.mus':
return 'application/vnd.musician'
case '.musicxml':
return 'application/vnd.recordare.musicxml+xml'
case '.mvb':
return 'application/x-msmediaview'
case '.mwf':
return 'application/vnd.mfer'
case '.mxf':
return 'application/mxf'
case '.mxl':
return 'application/vnd.recordare.musicxml'
case '.mxml':
return 'application/xv+xml'
case '.mxs':
return 'application/vnd.triscape.mxs'
case '.mxu':
return 'video/vnd.mpegurl'
case '.n3':
return 'text/n3'
case '.nb':
return 'application/mathematica'
case '.nbp':
return 'application/vnd.wolfram.player'
case '.nc':
return 'application/x-netcdf'
case '.ncx':
return 'application/x-dtbncx+xml'
case '.nfo':
return 'text/x-nfo'
case '.n-gage':
return 'application/vnd.nokia.n-gage.symbian.install'
case '.ngdat':
return 'application/vnd.nokia.n-gage.data'
case '.nitf':
return 'application/vnd.nitf'
case '.nlu':
return 'application/vnd.neurolanguage.nlu'
case '.nml':
return 'application/vnd.enliven'
case '.nnd':
return 'application/vnd.noblenet-directory'
case '.nns':
return 'application/vnd.noblenet-sealer'
case '.nnw':
return 'application/vnd.noblenet-web'
case '.npx':
return 'image/vnd.net-fpx'
case '.nsc':
return 'application/x-conference'
case '.nsf':
return 'application/vnd.lotus-notes'
case '.ntf':
return 'application/vnd.nitf'
case '.nzb':
return 'application/x-nzb'
case '.oa2':
return 'application/vnd.fujitsu.oasys2'
case '.oa3':
return 'application/vnd.fujitsu.oasys3'
case '.oas':
return 'application/vnd.fujitsu.oasys'
case '.obd':
return 'application/x-msbinder'
case '.obj':
return 'application/x-tgif'
case '.oda':
return 'application/oda'
case '.odb':
return 'application/vnd.oasis.opendocument.database'
case '.odc':
return 'application/vnd.oasis.opendocument.chart'
case '.odf':
return 'application/vnd.oasis.opendocument.formula'
case '.odft':
return 'application/vnd.oasis.opendocument.formula-template'
case '.odg':
return 'application/vnd.oasis.opendocument.graphics'
case '.odi':
return 'application/vnd.oasis.opendocument.image'
case '.odm':
return 'application/vnd.oasis.opendocument.text-master'
case '.odp':
return 'application/vnd.oasis.opendocument.presentation'
case '.ods':
return 'application/vnd.oasis.opendocument.spreadsheet'
case '.odt':
return 'application/vnd.oasis.opendocument.text'
case '.oga':
return 'audio/ogg'
case '.ogg':
return 'audio/ogg'
case '.ogv':
return 'video/ogg'
case '.ogx':
return 'application/ogg'
case '.omdoc':
return 'application/omdoc+xml'
case '.onepkg':
return 'application/onenote'
case '.onetmp':
return 'application/onenote'
case '.onetoc':
return 'application/onenote'
case '.onetoc2':
return 'application/onenote'
case '.opf':
return 'application/oebps-package+xml'
case '.opml':
return 'text/x-opml'
case '.oprc':
return 'application/vnd.palm'
case '.org':
return 'application/vnd.lotus-organizer'
case '.osf':
return 'application/vnd.yamaha.openscoreformat'
case '.osfpvg':
return 'application/vnd.yamaha.openscoreformat.osfpvg+xml'
case '.otc':
return 'application/vnd.oasis.opendocument.chart-template'
case '.otf':
return 'application/x-font-otf'
case '.otg':
return 'application/vnd.oasis.opendocument.graphics-template'
case '.oth':
return 'application/vnd.oasis.opendocument.text-web'
case '.oti':
return 'application/vnd.oasis.opendocument.image-template'
case '.otp':
return 'application/vnd.oasis.opendocument.presentation-template'
case '.ots':
return 'application/vnd.oasis.opendocument.spreadsheet-template'
case '.ott':
return 'application/vnd.oasis.opendocument.text-template'
case '.oxps':
return 'application/oxps'
case '.oxt':
return 'application/vnd.openofficeorg.extension'
case '.p':
return 'text/x-pascal'
case '.p10':
return 'application/pkcs10'
case '.p12':
return 'application/x-pkcs12'
case '.p7b':
return 'application/x-pkcs7-certificates'
case '.p7c':
return 'application/pkcs7-mime'
case '.p7m':
return 'application/pkcs7-mime'
case '.p7r':
return 'application/x-pkcs7-certreqresp'
case '.p7s':
return 'application/pkcs7-signature'
case '.p8':
return 'application/pkcs8'
case '.pas':
return 'text/x-pascal'
case '.paw':
return 'application/vnd.pawaafile'
case '.pbd':
return 'application/vnd.powerbuilder6'
case '.pbm':
return 'image/x-portable-bitmap'
case '.pcap':
return 'application/vnd.tcpdump.pcap'
case '.pcf':
return 'application/x-font-pcf'
case '.pcl':
return 'application/vnd.hp-pcl'
case '.pclxl':
return 'application/vnd.hp-pclxl'
case '.pct':
return 'image/x-pict'
case '.pcurl':
return 'application/vnd.curl.pcurl'
case '.pcx':
return 'image/x-pcx'
case '.pdb':
return 'application/vnd.palm'
case '.pdf':
return 'application/pdf'
case '.pfa':
return 'application/x-font-type1'
case '.pfb':
return 'application/x-font-type1'
case '.pfm':
return 'application/x-font-type1'
case '.pfr':
return 'application/font-tdpfr'
case '.pfx':
return 'application/x-pkcs12'
case '.pgm':
return 'image/x-portable-graymap'
case '.pgn':
return 'application/x-chess-pgn'
case '.pgp':
return 'application/pgp-encrypted'
case '.pic':
return 'image/x-pict'
case '.pkg':
return 'application/octet-stream'
case '.pki':
return 'application/pkixcmp'
case '.pkipath':
return 'application/pkix-pkipath'
case '.plb':
return 'application/vnd.3gpp.pic-bw-large'
case '.plc':
return 'application/vnd.mobius.plc'
case '.plf':
return 'application/vnd.pocketlearn'
case '.pls':
return 'application/pls+xml'
case '.pml':
return 'application/vnd.ctc-posml'
case '.png':
return 'image/png'
case '.pnm':
return 'image/x-portable-anymap'
case '.portpkg':
return 'application/vnd.macports.portpkg'
case '.pot':
return 'application/vnd.ms-powerpoint'
case '.potm':
return 'application/vnd.ms-powerpoint.template.macroenabled.12'
case '.potx':
return 'application/vnd.openxmlformats-officedocument.presentationml.template'
case '.ppam':
return 'application/vnd.ms-powerpoint.addin.macroenabled.12'
case '.ppd':
return 'application/vnd.cups-ppd'
case '.ppm':
return 'image/x-portable-pixmap'
case '.pps':
return 'application/vnd.ms-powerpoint'
case '.ppsm':
return 'application/vnd.ms-powerpoint.slideshow.macroenabled.12'
case '.ppsx':
return 'application/vnd.openxmlformats-officedocument.presentationml.slideshow'
case '.ppt':
return 'application/vnd.ms-powerpoint'
case '.pptm':
return 'application/vnd.ms-powerpoint.presentation.macroenabled.12'
case '.pptx':
return 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
case '.pqa':
return 'application/vnd.palm'
case '.prc':
return 'application/x-mobipocket-ebook'
case '.pre':
return 'application/vnd.lotus-freelance'
case '.prf':
return 'application/pics-rules'
case '.ps':
return 'application/postscript'
case '.psb':
return 'application/vnd.3gpp.pic-bw-small'
case '.psd':
return 'image/vnd.adobe.photoshop'
case '.psf':
return 'application/x-font-linux-psf'
case '.pskcxml':
return 'application/pskc+xml'
case '.ptid':
return 'application/vnd.pvi.ptid1'
case '.pub':
return 'application/x-mspublisher'
case '.pvb':
return 'application/vnd.3gpp.pic-bw-var'
case '.pwn':
return 'application/vnd.3m.post-it-notes'
case '.pya':
return 'audio/vnd.ms-playready.media.pya'
case '.pyv':
return 'video/vnd.ms-playready.media.pyv'
case '.qam':
return 'application/vnd.epson.quickanime'
case '.qbo':
return 'application/vnd.intu.qbo'
case '.qfx':
return 'application/vnd.intu.qfx'
case '.qps':
return 'application/vnd.publishare-delta-tree'
case '.qt':
return 'video/quicktime'
case '.qwd':
return 'application/vnd.quark.quarkxpress'
case '.qwt':
return 'application/vnd.quark.quarkxpress'
case '.qxb':
return 'application/vnd.quark.quarkxpress'
case '.qxd':
return 'application/vnd.quark.quarkxpress'
case '.qxl':
return 'application/vnd.quark.quarkxpress'
case '.qxt':
return 'application/vnd.quark.quarkxpress'
case '.ra':
return 'audio/x-pn-realaudio'
case '.ram':
return 'audio/x-pn-realaudio'
case '.rar':
return 'application/x-rar-compressed'
case '.ras':
return 'image/x-cmu-raster'
case '.rcprofile':
return 'application/vnd.ipunplugged.rcprofile'
case '.rdf':
return 'application/rdf+xml'
case '.rdz':
return 'application/vnd.data-vision.rdz'
case '.rep':
return 'application/vnd.businessobjects'
case '.res':
return 'application/x-dtbresource+xml'
case '.rgb':
return 'image/x-rgb'
case '.rif':
return 'application/reginfo+xml'
case '.rip':
return 'audio/vnd.rip'
case '.ris':
return 'application/x-research-info-systems'
case '.rl':
return 'application/resource-lists+xml'
case '.rlc':
return 'image/vnd.fujixerox.edmics-rlc'
case '.rld':
return 'application/resource-lists-diff+xml'
case '.rm':
return 'application/vnd.rn-realmedia'
case '.rmi':
return 'audio/midi'
case '.rmp':
return 'audio/x-pn-realaudio-plugin'
case '.rms':
return 'application/vnd.jcp.javame.midlet-rms'
case '.rmvb':
return 'application/vnd.rn-realmedia-vbr'
case '.rnc':
return 'application/relax-ng-compact-syntax'
case '.roa':
return 'application/rpki-roa'
case '.roff':
return 'text/troff'
case '.rp9':
return 'application/vnd.cloanto.rp9'
case '.rpss':
return 'application/vnd.nokia.radio-presets'
case '.rpst':
return 'application/vnd.nokia.radio-preset'
case '.rq':
return 'application/sparql-query'
case '.rs':
return 'application/rls-services+xml'
case '.rsd':
return 'application/rsd+xml'
case '.rss':
return 'application/rss+xml'
case '.rtf':
return 'application/rtf'
case '.rtx':
return 'text/richtext'
case '.s':
return 'text/x-asm'
case '.s3m':
return 'audio/s3m'
case '.saf':
return 'application/vnd.yamaha.smaf-audio'
case '.sbml':
return 'application/sbml+xml'
case '.sc':
return 'application/vnd.ibm.secure-container'
case '.scd':
return 'application/x-msschedule'
case '.scm':
return 'application/vnd.lotus-screencam'
case '.scq':
return 'application/scvp-cv-request'
case '.scs':
return 'application/scvp-cv-response'
case '.scurl':
return 'text/vnd.curl.scurl'
case '.sda':
return 'application/vnd.stardivision.draw'
case '.sdc':
return 'application/vnd.stardivision.calc'
case '.sdd':
return 'application/vnd.stardivision.impress'
case '.sdkd':
return 'application/vnd.solent.sdkm+xml'
case '.sdkm':
return 'application/vnd.solent.sdkm+xml'
case '.sdp':
return 'application/sdp'
case '.sdw':
return 'application/vnd.stardivision.writer'
case '.see':
return 'application/vnd.seemail'
case '.seed':
return 'application/vnd.fdsn.seed'
case '.sema':
return 'application/vnd.sema'
case '.semd':
return 'application/vnd.semd'
case '.semf':
return 'application/vnd.semf'
case '.ser':
return 'application/java-serialized-object'
case '.setpay':
return 'application/set-payment-initiation'
case '.setreg':
return 'application/set-registration-initiation'
case '.sfd-hdstx':
return 'application/vnd.hydrostatix.sof-data'
case '.sfs':
return 'application/vnd.spotfire.sfs'
case '.sfv':
return 'text/x-sfv'
case '.sgi':
return 'image/sgi'
case '.sgl':
return 'application/vnd.stardivision.writer-global'
case '.sgm':
return 'text/sgml'
case '.sgml':
return 'text/sgml'
case '.sh':
return 'application/x-sh'
case '.shar':
return 'application/x-shar'
case '.shf':
return 'application/shf+xml'
case '.sid':
return 'image/x-mrsid-image'
case '.sig':
return 'application/pgp-signature'
case '.sil':
return 'audio/silk'
case '.silo':
return 'model/mesh'
case '.sis':
return 'application/vnd.symbian.install'
case '.sisx':
return 'application/vnd.symbian.install'
case '.sit':
return 'application/x-stuffit'
case '.sitx':
return 'application/x-stuffitx'
case '.skd':
return 'application/vnd.koan'
case '.skm':
return 'application/vnd.koan'
case '.skp':
return 'application/vnd.koan'
case '.skt':
return 'application/vnd.koan'
case '.sldm':
return 'application/vnd.ms-powerpoint.slide.macroenabled.12'
case '.sldx':
return 'application/vnd.openxmlformats-officedocument.presentationml.slide'
case '.slt':
return 'application/vnd.epson.salt'
case '.sm':
return 'application/vnd.stepmania.stepchart'
case '.smf':
return 'application/vnd.stardivision.math'
case '.smi':
return 'application/smil+xml'
case '.smil':
return 'application/smil+xml'
case '.smv':
return 'video/x-smv'
case '.smzip':
return 'application/vnd.stepmania.package'
case '.snd':
return 'audio/basic'
case '.snf':
return 'application/x-font-snf'
case '.so':
return 'application/octet-stream'
case '.spc':
return 'application/x-pkcs7-certificates'
case '.spf':
return 'application/vnd.yamaha.smaf-phrase'
case '.spl':
return 'application/x-futuresplash'
case '.spot':
return 'text/vnd.in3d.spot'
case '.spp':
return 'application/scvp-vp-response'
case '.spq':
return 'application/scvp-vp-request'
case '.spx':
return 'audio/ogg'
case '.sql':
return 'application/x-sql'
case '.src':
return 'application/x-wais-source'
case '.srt':
return 'application/x-subrip'
case '.sru':
return 'application/sru+xml'
case '.srx':
return 'application/sparql-results+xml'
case '.ssdl':
return 'application/ssdl+xml'
case '.sse':
return 'application/vnd.kodak-descriptor'
case '.ssf':
return 'application/vnd.epson.ssf'
case '.ssml':
return 'application/ssml+xml'
case '.st':
return 'application/vnd.sailingtracker.track'
case '.stc':
return 'application/vnd.sun.xml.calc.template'
case '.std':
return 'application/vnd.sun.xml.draw.template'
case '.stf':
return 'application/vnd.wt.stf'
case '.sti':
return 'application/vnd.sun.xml.impress.template'
case '.stk':
return 'application/hyperstudio'
case '.stl':
return 'application/vnd.ms-pki.stl'
case '.str':
return 'application/vnd.pg.format'
case '.stw':
return 'application/vnd.sun.xml.writer.template'
case '.sub':
return 'text/vnd.dvb.subtitle'
case '.sus':
return 'application/vnd.sus-calendar'
case '.susp':
return 'application/vnd.sus-calendar'
case '.sv4cpio':
return 'application/x-sv4cpio'
case '.sv4crc':
return 'application/x-sv4crc'
case '.svc':
return 'application/vnd.dvb.service'
case '.svd':
return 'application/vnd.svd'
case '.svg':
return 'image/svg+xml'
case '.svgz':
return 'image/svg+xml'
case '.swa':
return 'application/x-director'
case '.swf':
return 'application/x-shockwave-flash'
case '.swi':
return 'application/vnd.aristanetworks.swi'
case '.sxc':
return 'application/vnd.sun.xml.calc'
case '.sxd':
return 'application/vnd.sun.xml.draw'
case '.sxg':
return 'application/vnd.sun.xml.writer.global'
case '.sxi':
return 'application/vnd.sun.xml.impress'
case '.sxm':
return 'application/vnd.sun.xml.math'
case '.sxw':
return 'application/vnd.sun.xml.writer'
case '.t':
return 'text/troff'
case '.t3':
return 'application/x-t3vm-image'
case '.taglet':
return 'application/vnd.mynfc'
case '.tao':
return 'application/vnd.tao.intent-module-archive'
case '.tar':
return 'application/x-tar'
case '.tcap':
return 'application/vnd.3gpp2.tcap'
case '.tcl':
return 'application/x-tcl'
case '.teacher':
return 'application/vnd.smart.teacher'
case '.tei':
return 'application/tei+xml'
case '.teicorpus':
return 'application/tei+xml'
case '.tex':
return 'application/x-tex'
case '.texi':
return 'application/x-texinfo'
case '.texinfo':
return 'application/x-texinfo'
case '.text':
return 'text/plain'
case '.tfi':
return 'application/thraud+xml'
case '.tfm':
return 'application/x-tex-tfm'
case '.tga':
return 'image/x-tga'
case '.thmx':
return 'application/vnd.ms-officetheme'
case '.tif':
return 'image/tiff'
case '.tiff':
return 'image/tiff'
case '.tmo':
return 'application/vnd.tmobile-livetv'
case '.torrent':
return 'application/x-bittorrent'
case '.tpl':
return 'application/vnd.groove-tool-template'
case '.tpt':
return 'application/vnd.trid.tpt'
case '.tr':
return 'text/troff'
case '.tra':
return 'application/vnd.trueapp'
case '.trm':
return 'application/x-msterminal'
case '.ts':
return 'application/typescript'
case '.tsd':
return 'application/timestamped-data'
case '.tsv':
return 'text/tab-separated-values'
case '.ttc':
return 'application/x-font-ttf'
case '.ttf':
return 'application/x-font-ttf'
case '.ttl':
return 'text/turtle'
case '.twd':
return 'application/vnd.simtech-mindmapper'
case '.twds':
return 'application/vnd.simtech-mindmapper'
case '.txd':
return 'application/vnd.genomatix.tuxedo'
case '.txf':
return 'application/vnd.mobius.txf'
case '.txt':
return 'text/plain'
case '.u32':
return 'application/x-authorware-bin'
case '.udeb':
return 'application/x-debian-package'
case '.ufd':
return 'application/vnd.ufdl'
case '.ufdl':
return 'application/vnd.ufdl'
case '.ulx':
return 'application/x-glulx'
case '.umj':
return 'application/vnd.umajin'
case '.unityweb':
return 'application/vnd.unity'
case '.uoml':
return 'application/vnd.uoml+xml'
case '.uri':
return 'text/uri-list'
case '.uris':
return 'text/uri-list'
case '.urls':
return 'text/uri-list'
case '.ustar':
return 'application/x-ustar'
case '.utz':
return 'application/vnd.uiq.theme'
case '.uu':
return 'text/x-uuencode'
case '.uva':
return 'audio/vnd.dece.audio'
case '.uvd':
return 'application/vnd.dece.data'
case '.uvf':
return 'application/vnd.dece.data'
case '.uvg':
return 'image/vnd.dece.graphic'
case '.uvh':
return 'video/vnd.dece.hd'
case '.uvi':
return 'image/vnd.dece.graphic'
case '.uvm':
return 'video/vnd.dece.mobile'
case '.uvp':
return 'video/vnd.dece.pd'
case '.uvs':
return 'video/vnd.dece.sd'
case '.uvt':
return 'application/vnd.dece.ttml+xml'
case '.uvu':
return 'video/vnd.uvvu.mp4'
case '.uvv':
return 'video/vnd.dece.video'
case '.uvva':
return 'audio/vnd.dece.audio'
case '.uvvd':
return 'application/vnd.dece.data'
case '.uvvf':
return 'application/vnd.dece.data'
case '.uvvg':
return 'image/vnd.dece.graphic'
case '.uvvh':
return 'video/vnd.dece.hd'
case '.uvvi':
return 'image/vnd.dece.graphic'
case '.uvvm':
return 'video/vnd.dece.mobile'
case '.uvvp':
return 'video/vnd.dece.pd'
case '.uvvs':
return 'video/vnd.dece.sd'
case '.uvvt':
return 'application/vnd.dece.ttml+xml'
case '.uvvu':
return 'video/vnd.uvvu.mp4'
case '.uvvv':
return 'video/vnd.dece.video'
case '.uvvx':
return 'application/vnd.dece.unspecified'
case '.uvvz':
return 'application/vnd.dece.zip'
case '.uvx':
return 'application/vnd.dece.unspecified'
case '.uvz':
return 'application/vnd.dece.zip'
case '.vcard':
return 'text/vcard'
case '.vcd':
return 'application/x-cdlink'
case '.vcf':
return 'text/x-vcard'
case '.vcg':
return 'application/vnd.groove-vcard'
case '.vcs':
return 'text/x-vcalendar'
case '.vcx':
return 'application/vnd.vcx'
case '.vis':
return 'application/vnd.visionary'
case '.viv':
return 'video/vnd.vivo'
case '.vob':
return 'video/x-ms-vob'
case '.vor':
return 'application/vnd.stardivision.writer'
case '.vox':
return 'application/x-authorware-bin'
case '.vrml':
return 'model/vrml'
case '.vsd':
return 'application/vnd.visio'
case '.vsf':
return 'application/vnd.vsf'
case '.vss':
return 'application/vnd.visio'
case '.vst':
return 'application/vnd.visio'
case '.vsw':
return 'application/vnd.visio'
case '.vtu':
return 'model/vnd.vtu'
case '.vxml':
return 'application/voicexml+xml'
case '.w3d':
return 'application/x-director'
case '.wad':
return 'application/x-doom'
case '.wasm':
return 'application/wasm'
case '.wav':
return 'audio/x-wav'
case '.wax':
return 'audio/x-ms-wax'
case '.wbmp':
return 'image/vnd.wap.wbmp'
case '.wbs':
return 'application/vnd.criticaltools.wbs+xml'
case '.wbxml':
return 'application/vnd.wap.wbxml'
case '.wcm':
return 'application/vnd.ms-works'
case '.wdb':
return 'application/vnd.ms-works'
case '.wdp':
return 'image/vnd.ms-photo'
case '.weba':
return 'audio/webm'
case '.webm':
return 'video/webm'
case '.webp':
return 'image/webp'
case '.wg':
return 'application/vnd.pmi.widget'
case '.wgt':
return 'application/widget'
case '.wks':
return 'application/vnd.ms-works'
case '.wm':
return 'video/x-ms-wm'
case '.wma':
return 'audio/x-ms-wma'
case '.wmd':
return 'application/x-ms-wmd'
case '.wmf':
return 'application/x-msmetafile'
case '.wml':
return 'text/vnd.wap.wml'
case '.wmlc':
return 'application/vnd.wap.wmlc'
case '.wmls':
return 'text/vnd.wap.wmlscript'
case '.wmlsc':
return 'application/vnd.wap.wmlscriptc'
case '.wmv':
return 'video/x-ms-wmv'
case '.wmx':
return 'video/x-ms-wmx'
case '.wmz':
return 'application/x-msmetafile'
case '.woff':
return 'application/x-font-woff'
case '.wpd':
return 'application/vnd.wordperfect'
case '.wpl':
return 'application/vnd.ms-wpl'
case '.wps':
return 'application/vnd.ms-works'
case '.wqd':
return 'application/vnd.wqd'
case '.wri':
return 'application/x-mswrite'
case '.wrl':
return 'model/vrml'
case '.wsdl':
return 'application/wsdl+xml'
case '.wspolicy':
return 'application/wspolicy+xml'
case '.wtb':
return 'application/vnd.webturbo'
case '.wvx':
return 'video/x-ms-wvx'
case '.x32':
return 'application/x-authorware-bin'
case '.x3d':
return 'model/x3d+xml'
case '.x3db':
return 'model/x3d+binary'
case '.x3dbz':
return 'model/x3d+binary'
case '.x3dv':
return 'model/x3d+vrml'
case '.x3dvz':
return 'model/x3d+vrml'
case '.x3dz':
return 'model/x3d+xml'
case '.xaml':
return 'application/xaml+xml'
case '.xap':
return 'application/x-silverlight-app'
case '.xar':
return 'application/vnd.xara'
case '.xbap':
return 'application/x-ms-xbap'
case '.xbd':
return 'application/vnd.fujixerox.docuworks.binder'
case '.xbm':
return 'image/x-xbitmap'
case '.xdf':
return 'application/xcap-diff+xml'
case '.xdm':
return 'application/vnd.syncml.dm+xml'
case '.xdp':
return 'application/vnd.adobe.xdp+xml'
case '.xdssc':
return 'application/dssc+xml'
case '.xdw':
return 'application/vnd.fujixerox.docuworks'
case '.xenc':
return 'application/xenc+xml'
case '.xer':
return 'application/patch-ops-error+xml'
case '.xfdf':
return 'application/vnd.adobe.xfdf'
case '.xfdl':
return 'application/vnd.xfdl'
case '.xht':
return 'application/xhtml+xml'
case '.xhtml':
return 'application/xhtml+xml'
case '.xhvml':
return 'application/xv+xml'
case '.xif':
return 'image/vnd.xiff'
case '.xla':
return 'application/vnd.ms-excel'
case '.xlam':
return 'application/vnd.ms-excel.addin.macroenabled.12'
case '.xlc':
return 'application/vnd.ms-excel'
case '.xlf':
return 'application/x-xliff+xml'
case '.xlm':
return 'application/vnd.ms-excel'
case '.xls':
return 'application/vnd.ms-excel'
case '.xlsb':
return 'application/vnd.ms-excel.sheet.binary.macroenabled.12'
case '.xlsm':
return 'application/vnd.ms-excel.sheet.macroenabled.12'
case '.xlsx':
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
case '.xlt':
return 'application/vnd.ms-excel'
case '.xltm':
return 'application/vnd.ms-excel.template.macroenabled.12'
case '.xltx':
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.template'
case '.xlw':
return 'application/vnd.ms-excel'
case '.xm':
return 'audio/xm'
case '.xml':
return 'application/xml'
case '.xo':
return 'application/vnd.olpc-sugar'
case '.xop':
return 'application/xop+xml'
case '.xpi':
return 'application/x-xpinstall'
case '.xpl':
return 'application/xproc+xml'
case '.xpm':
return 'image/x-xpixmap'
case '.xpr':
return 'application/vnd.is-xpr'
case '.xps':
return 'application/vnd.ms-xpsdocument'
case '.xpw':
return 'application/vnd.intercon.formnet'
case '.xpx':
return 'application/vnd.intercon.formnet'
case '.xsl':
return 'application/xml'
case '.xslt':
return 'application/xslt+xml'
case '.xsm':
return 'application/vnd.syncml+xml'
case '.xspf':
return 'application/xspf+xml'
case '.xul':
return 'application/vnd.mozilla.xul+xml'
case '.xvm':
return 'application/xv+xml'
case '.xvml':
return 'application/xv+xml'
case '.xwd':
return 'image/x-xwindowdump'
case '.xyz':
return 'chemical/x-xyz'
case '.xz':
return 'application/x-xz'
case '.yang':
return 'application/yang'
case '.yin':
return 'application/yin+xml'
case '.z1':
return 'application/x-zmachine'
case '.z2':
return 'application/x-zmachine'
case '.z3':
return 'application/x-zmachine'
case '.z4':
return 'application/x-zmachine'
case '.z5':
return 'application/x-zmachine'
case '.z6':
return 'application/x-zmachine'
case '.z7':
return 'application/x-zmachine'
case '.z8':
return 'application/x-zmachine'
case '.zaz':
return 'application/vnd.zzazz.deck+xml'
case '.zip':
return 'application/zip'
case '.zir':
return 'application/vnd.zul'
case '.zirz':
return 'application/vnd.zul'
case '.zmm':
return 'application/vnd.handheld-entertainment+xml'
default:
return 'application/octet-stream'
}
} | the_stack |
import { HttpResponse } from "@azure-rest/core-client";
import {
ApplicationDataListResponseOutput,
ErrorResponseOutput,
ApplicationDataOutput,
AttachmentListResponseOutput,
AttachmentOutput,
BoundaryListResponseOutput,
CascadeDeleteJobOutput,
BoundaryOutput,
BoundaryOverlapResponseOutput,
CropListResponseOutput,
CropOutput,
CropVarietyListResponseOutput,
CropVarietyOutput,
FarmerListResponseOutput,
FarmerOutput,
FarmOperationDataIngestionJobOutput,
FarmListResponseOutput,
FarmOutput,
FieldListResponseOutput,
FieldOutput,
HarvestDataListResponseOutput,
HarvestDataOutput,
ImageProcessingRasterizeJobOutput,
OAuthProviderListResponseOutput,
OAuthProviderOutput,
OAuthTokenListResponseOutput,
PlantingDataListResponseOutput,
PlantingDataOutput,
SceneListResponseOutput,
SatelliteDataIngestionJobOutput,
SeasonalFieldListResponseOutput,
SeasonalFieldOutput,
SeasonListResponseOutput,
SeasonOutput,
TillageDataListResponseOutput,
TillageDataOutput,
WeatherDataListResponseOutput,
WeatherDataIngestionJobOutput,
WeatherDataDeleteJobOutput
} from "./outputModels";
/** Returns a paginated list of application data resources under a particular farm. */
export interface ApplicationDataListByFarmerId200Response extends HttpResponse {
status: "200";
body: ApplicationDataListResponseOutput;
}
/** Returns a paginated list of application data resources under a particular farm. */
export interface ApplicationDataListByFarmerIddefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of application data resources across all farmers. */
export interface ApplicationDataList200Response extends HttpResponse {
status: "200";
body: ApplicationDataListResponseOutput;
}
/** Returns a paginated list of application data resources across all farmers. */
export interface ApplicationDataListdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Get a specified application data resource under a particular farmer. */
export interface ApplicationDataGet200Response extends HttpResponse {
status: "200";
body: ApplicationDataOutput;
}
/** Get a specified application data resource under a particular farmer. */
export interface ApplicationDataGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Creates or updates an application data resource under a particular farmer. */
export interface ApplicationDataCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: ApplicationDataOutput;
}
/** Creates or updates an application data resource under a particular farmer. */
export interface ApplicationDataCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: ApplicationDataOutput;
}
/** Creates or updates an application data resource under a particular farmer. */
export interface ApplicationDataCreateOrUpdatedefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Deletes a specified application data resource under a particular farmer. */
export interface ApplicationDataDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes a specified application data resource under a particular farmer. */
export interface ApplicationDataDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of attachment resources under a particular farmer. */
export interface AttachmentsListByFarmerId200Response extends HttpResponse {
status: "200";
body: AttachmentListResponseOutput;
}
/** Returns a paginated list of attachment resources under a particular farmer. */
export interface AttachmentsListByFarmerIddefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Gets a specified attachment resource under a particular farmer. */
export interface AttachmentsGet200Response extends HttpResponse {
status: "200";
body: AttachmentOutput;
}
/** Gets a specified attachment resource under a particular farmer. */
export interface AttachmentsGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Creates or updates an attachment resource under a particular farmer. */
export interface AttachmentsCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: AttachmentOutput;
}
/** Creates or updates an attachment resource under a particular farmer. */
export interface AttachmentsCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: AttachmentOutput;
}
/** Creates or updates an attachment resource under a particular farmer. */
export interface AttachmentsCreateOrUpdatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Deletes a specified attachment resource under a particular farmer. */
export interface AttachmentsDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes a specified attachment resource under a particular farmer. */
export interface AttachmentsDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Downloads and returns attachment as response for the given input filePath. */
export interface AttachmentsDownload200Response extends HttpResponse {
status: "200";
/** Value may contain any sequence of octets */
body: Uint8Array;
}
/** Downloads and returns attachment as response for the given input filePath. */
export interface AttachmentsDownloaddefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of boundary resources under a particular farmer. */
export interface BoundariesListByFarmerId200Response extends HttpResponse {
status: "200";
body: BoundaryListResponseOutput;
}
/** Returns a paginated list of boundary resources under a particular farmer. */
export interface BoundariesListByFarmerIddefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Search for boundaries by fields and intersecting geometry. */
export interface BoundariesSearchByFarmerId200Response extends HttpResponse {
status: "200";
body: BoundaryListResponseOutput;
}
/** Search for boundaries by fields and intersecting geometry. */
export interface BoundariesSearchByFarmerIddefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of boundary resources across all farmers. */
export interface BoundariesList200Response extends HttpResponse {
status: "200";
body: BoundaryListResponseOutput;
}
/** Returns a paginated list of boundary resources across all farmers. */
export interface BoundariesListdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Search for boundaries across all farmers by fields and intersecting geometry. */
export interface BoundariesSearch200Response extends HttpResponse {
status: "200";
body: BoundaryListResponseOutput;
}
/** Search for boundaries across all farmers by fields and intersecting geometry. */
export interface BoundariesSearchdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Get cascade delete job for specified boundary. */
export interface BoundariesGetCascadeDeleteJobDetails200Response
extends HttpResponse {
status: "200";
body: CascadeDeleteJobOutput;
}
/** Get cascade delete job for specified boundary. */
export interface BoundariesGetCascadeDeleteJobDetailsdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Create a cascade delete job for specified boundary. */
export interface BoundariesCreateCascadeDeleteJob202Response
extends HttpResponse {
status: "202";
body: CascadeDeleteJobOutput;
}
/** Create a cascade delete job for specified boundary. */
export interface BoundariesCreateCascadeDeleteJobdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Gets a specified boundary resource under a particular farmer. */
export interface BoundariesGet200Response extends HttpResponse {
status: "200";
body: BoundaryOutput;
}
/** Gets a specified boundary resource under a particular farmer. */
export interface BoundariesGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Creates or updates a boundary resource. */
export interface BoundariesCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: BoundaryOutput;
}
/** Creates or updates a boundary resource. */
export interface BoundariesCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: BoundaryOutput;
}
/** Creates or updates a boundary resource. */
export interface BoundariesCreateOrUpdatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Deletes a specified boundary resource under a particular farmer. */
export interface BoundariesDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes a specified boundary resource under a particular farmer. */
export interface BoundariesDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns overlapping acreage between two boundary Ids. */
export interface BoundariesGetOverlap200Response extends HttpResponse {
status: "200";
body: BoundaryOverlapResponseOutput;
}
/** Returns overlapping acreage between two boundary Ids. */
export interface BoundariesGetOverlapdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of crop resources. */
export interface CropsList200Response extends HttpResponse {
status: "200";
body: CropListResponseOutput;
}
/** Returns a paginated list of crop resources. */
export interface CropsListdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Gets a specified crop resource. */
export interface CropsGet200Response extends HttpResponse {
status: "200";
body: CropOutput;
}
/** Gets a specified crop resource. */
export interface CropsGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Creates or updates a crop resource. */
export interface CropsCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: CropOutput;
}
/** Creates or updates a crop resource. */
export interface CropsCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: CropOutput;
}
/** Creates or updates a crop resource. */
export interface CropsCreateOrUpdatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Deletes Crop for given crop id. */
export interface CropsDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes Crop for given crop id. */
export interface CropsDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of crop variety resources under a particular crop. */
export interface CropVarietiesListByCropId200Response extends HttpResponse {
status: "200";
body: CropVarietyListResponseOutput;
}
/** Returns a paginated list of crop variety resources under a particular crop. */
export interface CropVarietiesListByCropIddefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of crop variety resources across all crops. */
export interface CropVarietiesList200Response extends HttpResponse {
status: "200";
body: CropVarietyListResponseOutput;
}
/** Returns a paginated list of crop variety resources across all crops. */
export interface CropVarietiesListdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Gets a specified crop variety resource under a particular crop. */
export interface CropVarietiesGet200Response extends HttpResponse {
status: "200";
body: CropVarietyOutput;
}
/** Gets a specified crop variety resource under a particular crop. */
export interface CropVarietiesGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Creates or updates a crop variety resource. */
export interface CropVarietiesCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: CropVarietyOutput;
}
/** Creates or updates a crop variety resource. */
export interface CropVarietiesCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: CropVarietyOutput;
}
/** Creates or updates a crop variety resource. */
export interface CropVarietiesCreateOrUpdatedefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Deletes a specified crop variety resource under a particular crop. */
export interface CropVarietiesDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes a specified crop variety resource under a particular crop. */
export interface CropVarietiesDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of farmer resources. */
export interface FarmersList200Response extends HttpResponse {
status: "200";
body: FarmerListResponseOutput;
}
/** Returns a paginated list of farmer resources. */
export interface FarmersListdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Gets a specified farmer resource. */
export interface FarmersGet200Response extends HttpResponse {
status: "200";
body: FarmerOutput;
}
/** Gets a specified farmer resource. */
export interface FarmersGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Creates or updates a farmer resource. */
export interface FarmersCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: FarmerOutput;
}
/** Creates or updates a farmer resource. */
export interface FarmersCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: FarmerOutput;
}
/** Creates or updates a farmer resource. */
export interface FarmersCreateOrUpdatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Deletes a specified farmer resource. */
export interface FarmersDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes a specified farmer resource. */
export interface FarmersDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Get a cascade delete job for specified farmer. */
export interface FarmersGetCascadeDeleteJobDetails200Response
extends HttpResponse {
status: "200";
body: CascadeDeleteJobOutput;
}
/** Get a cascade delete job for specified farmer. */
export interface FarmersGetCascadeDeleteJobDetailsdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Create a cascade delete job for specified farmer. */
export interface FarmersCreateCascadeDeleteJob202Response extends HttpResponse {
status: "202";
body: CascadeDeleteJobOutput;
}
/** Create a cascade delete job for specified farmer. */
export interface FarmersCreateCascadeDeleteJobdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Create a farm operation data ingestion job. */
export interface FarmOperationsCreateDataIngestionJob202Response
extends HttpResponse {
status: "202";
body: FarmOperationDataIngestionJobOutput;
}
/** Create a farm operation data ingestion job. */
export interface FarmOperationsCreateDataIngestionJobdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Get a farm operation data ingestion job. */
export interface FarmOperationsGetDataIngestionJobDetails200Response
extends HttpResponse {
status: "200";
body: FarmOperationDataIngestionJobOutput;
}
/** Get a farm operation data ingestion job. */
export interface FarmOperationsGetDataIngestionJobDetailsdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of farm resources under a particular farmer. */
export interface FarmsListByFarmerId200Response extends HttpResponse {
status: "200";
body: FarmListResponseOutput;
}
/** Returns a paginated list of farm resources under a particular farmer. */
export interface FarmsListByFarmerIddefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of farm resources across all farmers. */
export interface FarmsList200Response extends HttpResponse {
status: "200";
body: FarmListResponseOutput;
}
/** Returns a paginated list of farm resources across all farmers. */
export interface FarmsListdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Gets a specified farm resource under a particular farmer. */
export interface FarmsGet200Response extends HttpResponse {
status: "200";
body: FarmOutput;
}
/** Gets a specified farm resource under a particular farmer. */
export interface FarmsGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Creates or updates a farm resource under a particular farmer. */
export interface FarmsCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: FarmOutput;
}
/** Creates or updates a farm resource under a particular farmer. */
export interface FarmsCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: FarmOutput;
}
/** Creates or updates a farm resource under a particular farmer. */
export interface FarmsCreateOrUpdatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Deletes a specified farm resource under a particular farmer. */
export interface FarmsDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes a specified farm resource under a particular farmer. */
export interface FarmsDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Get a cascade delete job for specified farm. */
export interface FarmsGetCascadeDeleteJobDetails200Response
extends HttpResponse {
status: "200";
body: CascadeDeleteJobOutput;
}
/** Get a cascade delete job for specified farm. */
export interface FarmsGetCascadeDeleteJobDetailsdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Create a cascade delete job for specified farm. */
export interface FarmsCreateCascadeDeleteJob202Response extends HttpResponse {
status: "202";
body: CascadeDeleteJobOutput;
}
/** Create a cascade delete job for specified farm. */
export interface FarmsCreateCascadeDeleteJobdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of field resources under a particular farmer. */
export interface FieldsListByFarmerId200Response extends HttpResponse {
status: "200";
body: FieldListResponseOutput;
}
/** Returns a paginated list of field resources under a particular farmer. */
export interface FieldsListByFarmerIddefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of field resources across all farmers. */
export interface FieldsList200Response extends HttpResponse {
status: "200";
body: FieldListResponseOutput;
}
/** Returns a paginated list of field resources across all farmers. */
export interface FieldsListdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Gets a specified field resource under a particular farmer. */
export interface FieldsGet200Response extends HttpResponse {
status: "200";
body: FieldOutput;
}
/** Gets a specified field resource under a particular farmer. */
export interface FieldsGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Creates or Updates a field resource under a particular farmer. */
export interface FieldsCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: FieldOutput;
}
/** Creates or Updates a field resource under a particular farmer. */
export interface FieldsCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: FieldOutput;
}
/** Creates or Updates a field resource under a particular farmer. */
export interface FieldsCreateOrUpdatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Deletes a specified field resource under a particular farmer. */
export interface FieldsDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes a specified field resource under a particular farmer. */
export interface FieldsDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Get a cascade delete job for specified field. */
export interface FieldsGetCascadeDeleteJobDetails200Response
extends HttpResponse {
status: "200";
body: CascadeDeleteJobOutput;
}
/** Get a cascade delete job for specified field. */
export interface FieldsGetCascadeDeleteJobDetailsdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Create a cascade delete job for specified field. */
export interface FieldsCreateCascadeDeleteJob202Response extends HttpResponse {
status: "202";
body: CascadeDeleteJobOutput;
}
/** Create a cascade delete job for specified field. */
export interface FieldsCreateCascadeDeleteJobdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of harvest data resources under a particular farm. */
export interface HarvestDataListByFarmerId200Response extends HttpResponse {
status: "200";
body: HarvestDataListResponseOutput;
}
/** Returns a paginated list of harvest data resources under a particular farm. */
export interface HarvestDataListByFarmerIddefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of harvest data resources across all farmers. */
export interface HarvestDataList200Response extends HttpResponse {
status: "200";
body: HarvestDataListResponseOutput;
}
/** Returns a paginated list of harvest data resources across all farmers. */
export interface HarvestDataListdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Get a specified harvest data resource under a particular farmer. */
export interface HarvestDataGet200Response extends HttpResponse {
status: "200";
body: HarvestDataOutput;
}
/** Get a specified harvest data resource under a particular farmer. */
export interface HarvestDataGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Creates or updates harvest data resource under a particular farmer. */
export interface HarvestDataCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: HarvestDataOutput;
}
/** Creates or updates harvest data resource under a particular farmer. */
export interface HarvestDataCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: HarvestDataOutput;
}
/** Creates or updates harvest data resource under a particular farmer. */
export interface HarvestDataCreateOrUpdatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Deletes a specified harvest data resource under a particular farmer. */
export interface HarvestDataDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes a specified harvest data resource under a particular farmer. */
export interface HarvestDataDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Create a ImageProcessing Rasterize job. */
export interface ImageProcessingCreateRasterizeJob202Response
extends HttpResponse {
status: "202";
body: ImageProcessingRasterizeJobOutput;
}
/** Create a ImageProcessing Rasterize job. */
export interface ImageProcessingCreateRasterizeJobdefaultResponse
extends HttpResponse {
status: "500";
body: Record<string, unknown>;
}
/** Get ImageProcessing Rasterize job's details. */
export interface ImageProcessingGetRasterizeJob200Response
extends HttpResponse {
status: "200";
body: ImageProcessingRasterizeJobOutput;
}
/** Returns a paginated list of oauthProvider resources. */
export interface OAuthProvidersList200Response extends HttpResponse {
status: "200";
body: OAuthProviderListResponseOutput;
}
/** Returns a paginated list of oauthProvider resources. */
export interface OAuthProvidersListdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Get a specified oauthProvider resource. */
export interface OAuthProvidersGet200Response extends HttpResponse {
status: "200";
body: OAuthProviderOutput;
}
/** Get a specified oauthProvider resource. */
export interface OAuthProvidersGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Creates or updates an oauthProvider resource. */
export interface OAuthProvidersCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: OAuthProviderOutput;
}
/** Creates or updates an oauthProvider resource. */
export interface OAuthProvidersCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: OAuthProviderOutput;
}
/** Creates or updates an oauthProvider resource. */
export interface OAuthProvidersCreateOrUpdatedefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Deletes an specified oauthProvider resource. */
export interface OAuthProvidersDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes an specified oauthProvider resource. */
export interface OAuthProvidersDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a list of OAuthToken documents. */
export interface OAuthTokensList200Response extends HttpResponse {
status: "200";
body: OAuthTokenListResponseOutput;
}
/** Returns a list of OAuthToken documents. */
export interface OAuthTokensListdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns Connection link needed in the OAuth flow. */
export interface OAuthTokensGetOAuthConnectionLink200Response
extends HttpResponse {
status: "200";
body: string;
}
/** Returns Connection link needed in the OAuth flow. */
export interface OAuthTokensGetOAuthConnectionLinkdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Get cascade delete job details for OAuth tokens for specified job ID. */
export interface OAuthTokensGetCascadeDeleteJobDetails200Response
extends HttpResponse {
status: "200";
body: CascadeDeleteJobOutput;
}
/** Get cascade delete job details for OAuth tokens for specified job ID. */
export interface OAuthTokensGetCascadeDeleteJobDetailsdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Create a cascade delete job for OAuth tokens. */
export interface OAuthTokensCreateCascadeDeleteJob202Response
extends HttpResponse {
status: "202";
body: CascadeDeleteJobOutput;
}
/** Create a cascade delete job for OAuth tokens. */
export interface OAuthTokensCreateCascadeDeleteJobdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of planting data resources under a particular farm. */
export interface PlantingDataListByFarmerId200Response extends HttpResponse {
status: "200";
body: PlantingDataListResponseOutput;
}
/** Returns a paginated list of planting data resources under a particular farm. */
export interface PlantingDataListByFarmerIddefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of planting data resources across all farmers. */
export interface PlantingDataList200Response extends HttpResponse {
status: "200";
body: PlantingDataListResponseOutput;
}
/** Returns a paginated list of planting data resources across all farmers. */
export interface PlantingDataListdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Get a specified planting data resource under a particular farmer. */
export interface PlantingDataGet200Response extends HttpResponse {
status: "200";
body: PlantingDataOutput;
}
/** Get a specified planting data resource under a particular farmer. */
export interface PlantingDataGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Creates or updates an planting data resource under a particular farmer. */
export interface PlantingDataCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: PlantingDataOutput;
}
/** Creates or updates an planting data resource under a particular farmer. */
export interface PlantingDataCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: PlantingDataOutput;
}
/** Creates or updates an planting data resource under a particular farmer. */
export interface PlantingDataCreateOrUpdatedefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Deletes a specified planting data resource under a particular farmer. */
export interface PlantingDataDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes a specified planting data resource under a particular farmer. */
export interface PlantingDataDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of scene resources. */
export interface ScenesList200Response extends HttpResponse {
status: "200";
body: SceneListResponseOutput;
}
/** Returns a paginated list of scene resources. */
export interface ScenesListdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Create a satellite data ingestion job. */
export interface ScenesCreateSatelliteDataIngestionJob202Response
extends HttpResponse {
status: "202";
body: SatelliteDataIngestionJobOutput;
}
/** Create a satellite data ingestion job. */
export interface ScenesCreateSatelliteDataIngestionJobdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Get a satellite data ingestion job. */
export interface ScenesGetSatelliteDataIngestionJobDetails200Response
extends HttpResponse {
status: "200";
body: SatelliteDataIngestionJobOutput;
}
/** Get a satellite data ingestion job. */
export interface ScenesGetSatelliteDataIngestionJobDetailsdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Downloads and returns file stream as response for the given input filePath. */
export interface ScenesDownload200Response extends HttpResponse {
status: "200";
/** Value may contain any sequence of octets */
body: Uint8Array;
}
/** Downloads and returns file stream as response for the given input filePath. */
export interface ScenesDownloaddefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of seasonal field resources under a particular farmer. */
export interface SeasonalFieldsListByFarmerId200Response extends HttpResponse {
status: "200";
body: SeasonalFieldListResponseOutput;
}
/** Returns a paginated list of seasonal field resources under a particular farmer. */
export interface SeasonalFieldsListByFarmerIddefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of seasonal field resources across all farmers. */
export interface SeasonalFieldsList200Response extends HttpResponse {
status: "200";
body: SeasonalFieldListResponseOutput;
}
/** Returns a paginated list of seasonal field resources across all farmers. */
export interface SeasonalFieldsListdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Gets a specified seasonal field resource under a particular farmer. */
export interface SeasonalFieldsGet200Response extends HttpResponse {
status: "200";
body: SeasonalFieldOutput;
}
/** Gets a specified seasonal field resource under a particular farmer. */
export interface SeasonalFieldsGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Creates or Updates a seasonal field resource under a particular farmer. */
export interface SeasonalFieldsCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: SeasonalFieldOutput;
}
/** Creates or Updates a seasonal field resource under a particular farmer. */
export interface SeasonalFieldsCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: SeasonalFieldOutput;
}
/** Creates or Updates a seasonal field resource under a particular farmer. */
export interface SeasonalFieldsCreateOrUpdatedefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Deletes a specified seasonal-field resource under a particular farmer. */
export interface SeasonalFieldsDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes a specified seasonal-field resource under a particular farmer. */
export interface SeasonalFieldsDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Get cascade delete job for specified seasonal field. */
export interface SeasonalFieldsGetCascadeDeleteJobDetails200Response
extends HttpResponse {
status: "200";
body: CascadeDeleteJobOutput;
}
/** Get cascade delete job for specified seasonal field. */
export interface SeasonalFieldsGetCascadeDeleteJobDetailsdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Create a cascade delete job for specified seasonal field. */
export interface SeasonalFieldsCreateCascadeDeleteJob202Response
extends HttpResponse {
status: "202";
body: CascadeDeleteJobOutput;
}
/** Create a cascade delete job for specified seasonal field. */
export interface SeasonalFieldsCreateCascadeDeleteJobdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of season resources. */
export interface SeasonsList200Response extends HttpResponse {
status: "200";
body: SeasonListResponseOutput;
}
/** Returns a paginated list of season resources. */
export interface SeasonsListdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Gets a specified season resource. */
export interface SeasonsGet200Response extends HttpResponse {
status: "200";
body: SeasonOutput;
}
/** Gets a specified season resource. */
export interface SeasonsGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Creates or updates a season resource. */
export interface SeasonsCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: SeasonOutput;
}
/** Creates or updates a season resource. */
export interface SeasonsCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: SeasonOutput;
}
/** Creates or updates a season resource. */
export interface SeasonsCreateOrUpdatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Deletes a specified season resource. */
export interface SeasonsDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes a specified season resource. */
export interface SeasonsDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of tillage data resources under a particular farm. */
export interface TillageDataListByFarmerId200Response extends HttpResponse {
status: "200";
body: TillageDataListResponseOutput;
}
/** Returns a paginated list of tillage data resources under a particular farm. */
export interface TillageDataListByFarmerIddefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of tillage data resources across all farmers. */
export interface TillageDataList200Response extends HttpResponse {
status: "200";
body: TillageDataListResponseOutput;
}
/** Returns a paginated list of tillage data resources across all farmers. */
export interface TillageDataListdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Get a specified tillage data resource under a particular farmer. */
export interface TillageDataGet200Response extends HttpResponse {
status: "200";
body: TillageDataOutput;
}
/** Get a specified tillage data resource under a particular farmer. */
export interface TillageDataGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Creates or updates an tillage data resource under a particular farmer. */
export interface TillageDataCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: TillageDataOutput;
}
/** Creates or updates an tillage data resource under a particular farmer. */
export interface TillageDataCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: TillageDataOutput;
}
/** Creates or updates an tillage data resource under a particular farmer. */
export interface TillageDataCreateOrUpdatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Deletes a specified tillage data resource under a particular farmer. */
export interface TillageDataDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes a specified tillage data resource under a particular farmer. */
export interface TillageDataDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Returns a paginated list of weather data. */
export interface WeatherList200Response extends HttpResponse {
status: "200";
body: WeatherDataListResponseOutput;
}
/** Returns a paginated list of weather data. */
export interface WeatherListdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Get weather ingestion job. */
export interface WeatherGetDataIngestionJobDetails200Response
extends HttpResponse {
status: "200";
body: WeatherDataIngestionJobOutput;
}
/** Get weather ingestion job. */
export interface WeatherGetDataIngestionJobDetailsdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Create a weather data ingestion job. */
export interface WeatherCreateDataIngestionJob202Response extends HttpResponse {
status: "202";
body: WeatherDataIngestionJobOutput;
}
/** Create a weather data ingestion job. */
export interface WeatherCreateDataIngestionJobdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Get weather data delete job. */
export interface WeatherGetDataDeleteJobDetails200Response
extends HttpResponse {
status: "200";
body: WeatherDataDeleteJobOutput;
}
/** Get weather data delete job. */
export interface WeatherGetDataDeleteJobDetailsdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
}
/** Create a weather data delete job. */
export interface WeatherCreateDataDeleteJob202Response extends HttpResponse {
status: "202";
body: WeatherDataDeleteJobOutput;
}
/** Create a weather data delete job. */
export interface WeatherCreateDataDeleteJobdefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseOutput;
} | the_stack |
import {
Directive,
EventEmitter,
Input,
OnDestroy,
Output,
} from "@angular/core";
import {
Control,
ControlPosition,
LeafletEvent,
LeafletMouseEvent,
Map,
} from "leaflet";
import { LayersControlProvider } from "./layers-control.provider";
import { MapProvider } from "./map.provider";
import { enhanceMouseEvent } from "./mouse-event-helper";
/**
* Angular2 directive for the attribution-control of Leaflet.
*
* *You can use this directive in an Angular2 template after importing `YagaModule`.*
*
* How to use in a template:
* ```html
* <yaga-map>
* <yaga-layers-control
* [(display)]="..."
* [(zIndex)]="..."
* [(position)]="..."
*
* (add)="..."
* (remove)="..."
* (click)="..."
* (dblclick)="..."
* (mousedown)="..."
* (mouseover)="..."
* (mouseout)="..."
* >
* <yaga-tile-layer yaga-base-layer="OSM"></yaga-tile-layer>
* <yaga-geojson yaga-overlay-layer="My points"></yaga-geojson>
* </yaga-layers-control>
* </yaga-map>
* ```
*
* @link http://leafletjs.com/reference-1.2.0.html#control-layers Original Leaflet documentation
* @link https://leaflet-ng2.yagajs.org/latest/browser-test?grep=Scale-Control%20Directive Unit-Test
* @link https://leaflet-ng2.yagajs.org/latest/coverage/lcov-report/lib/attribution-control.directive.js.html
* Test coverage
* @link https://leaflet-ng2.yagajs.org/latest/typedoc/classes/layerscontroldirective.html API documentation
* @example https://leaflet-ng2.yagajs.org/latest/examples/layers-control-directive/
*/
@Directive({
providers: [ LayersControlProvider ],
selector: "yaga-layers-control",
})
export class LayersControlDirective extends Control.Layers implements OnDestroy {
/**
* Two-Way bound property for the display status of the control.
* Use it with `<yaga-layers-control [(display)]="someValue">`
* or `<yaga-layers-control (displayChange)="processEvent($event)">`
*/
@Output() public displayChange: EventEmitter<boolean> = new EventEmitter();
/**
* Two-Way bound property for the zIndex of the control.
* Use it with `<yaga-layers-control [(zIndex)]="someValue">`
* or `<yaga-layers-control (zIndexChange)="processEvent($event)">`
*/
@Output() public zIndexChange: EventEmitter<number> = new EventEmitter();
/**
* Two-Way bound property for the position of the control.
* Use it with `<yaga-layers-control [(position)]="someValue">`
* or `<yaga-layers-control (positionChange)="processEvent($event)">`
*/
@Output() public positionChange: EventEmitter<ControlPosition> = new EventEmitter();
/**
* From leaflet fired add event.
* Use it with `<yaga-layers-control (add)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#control-layers-add Original Leaflet documentation
*/
@Output("add") public addEvent: EventEmitter<LeafletEvent> = new EventEmitter();
/**
* From leaflet fired remove event.
* Use it with `<yaga-layers-control (remove)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#control-layers-remove Original Leaflet documentation
*/
@Output("remove") public removeEvent: EventEmitter<LeafletEvent> = new EventEmitter();
/**
* From leaflet fired click event.
* Use it with `<yaga-layers-control (click)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#control-layers-click Original Leaflet documentation
*/
@Output("click") public clickEvent: EventEmitter<LeafletMouseEvent> = new EventEmitter();
/**
* From leaflet fired dblclick event.
* Use it with `<yaga-layers-control (dblclick)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#control-layers-dblclick Original Leaflet documentation
*/
@Output("dblclick") public dblclickEvent: EventEmitter<LeafletMouseEvent> = new EventEmitter();
/**
* From leaflet fired mousedown event.
* Use it with `<yaga-layers-control (mousedown)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#control-layers-mousedown Original Leaflet documentation
*/
@Output("mousedown") public mousedownEvent: EventEmitter<LeafletMouseEvent> = new EventEmitter();
/**
* From leaflet fired mouseover event.
* Use it with `<yaga-layers-control (mouseover)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#control-layers-mouseover Original Leaflet documentation
*/
@Output("mouseover") public mouseoverEvent: EventEmitter<LeafletMouseEvent> = new EventEmitter();
/**
* From leaflet fired mouseout event.
* Use it with `<yaga-layers-control (mouseout)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#control-layers-mouseout Original Leaflet documentation
*/
@Output("mouseout") public mouseoutEvent: EventEmitter<LeafletMouseEvent> = new EventEmitter();
constructor(
protected mapProvider: MapProvider,
layersControlProvider: LayersControlProvider,
) {
super();
layersControlProvider.ref = this;
this.mapProvider.ref!.addControl(this);
}
/**
* Internal method to provide the removal of the control in Leaflet, when removing it from the Angular template
*/
public ngOnDestroy(): void {
this.mapProvider.ref!.removeControl(this);
}
/**
* Derived remove function
*/
public remove(): this {
/* tslint:disable */
super.remove();
this.displayChange.emit(false);
this.removeEvent.emit({target: this, type: "remove"});
return this;
}
/**
* Derived addTo function
*/
public addTo(map: Map) {
/* tslint:disable */
super.addTo(map);
this.displayChange.emit(true);
this.addEvent.emit({target: this, type: "add"});
return this;
}
/**
* Derived method of the original setPosition.
* @link http://leafletjs.com/reference-1.2.0.html#control-layers-setposition Original Leaflet documentation
*/
public setPosition(val: ControlPosition): this {
super.setPosition(val);
this.positionChange.emit(val);
return this;
}
/**
* Two-Way bound property for the opacity.
* Use it with `<yaga-layers-control [(opacity)]="someValue">`
* or `<yaga-layers-control [opacity]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#control-layers-opacity Original Leaflet documentation
*/
@Input() public set opacity(val: number | undefined) {
if (typeof val === "number") {
this.getContainer()!.style.opacity = val.toString();
return;
}
this.getContainer()!.style.opacity = null;
}
public get opacity(): number | undefined {
if (typeof this.getContainer()!.style.opacity === "string") {
return parseFloat(this.getContainer()!.style.opacity!);
}
}
/**
* Two-Way bound property for the display state.
* Use it with `<yaga-layers-control [(display)]="someValue">`
* or `<yaga-layers-control [display]="someValue">`
*/
@Input() public set display(val: boolean) {
if (!(this as any)._map) {
// No map available...
return;
}
if (val) {
this.getContainer()!.style.display = "";
return;
}
this.getContainer()!.style.display = "none";
return;
}
public get display(): boolean {
return !!(this as any)._map && this.getContainer()!.style.display !== "none";
}
/**
* Two-Way bound property for the position.
* Use it with `<yaga-layers-control [(position)]="someValue">`
* or `<yaga-layers-control [position]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#control-layers-position Original Leaflet documentation
*/
@Input() public set position(val: ControlPosition) {
this.setPosition(val);
}
public get position(): ControlPosition {
return this.getPosition();
}
/**
* Two-Way bound property for the zIndex of the control.
* Use it with `<yaga-layers-control [(zIndex)]="someValue">`
* or `<yaga-layers-control (zIndexChange)="processEvent($event)">`
*/
@Input() public set zIndex(zIndex: number | undefined) {
if (typeof zIndex === "number") {
this.getContainer()!.style.zIndex = zIndex.toString();
return;
}
this.getContainer()!.style.zIndex = null;
}
public get zIndex(): number | undefined {
if (typeof this.getContainer()!.style.zIndex === "string") {
return parseInt(this.getContainer()!.style.zIndex!, 10);
}
}
/**
* Reimplemention of initLayout private function to register event listeners after DOM creation.
*/
protected _initLayout() {
// @ts-ignore
super._initLayout();
// Events
this.getContainer()!.addEventListener("click", (event: MouseEvent) => {
this.clickEvent.emit(enhanceMouseEvent(event, (this as any)._map as Map));
});
this.getContainer()!.addEventListener("dblclick", (event: MouseEvent) => {
this.dblclickEvent.emit(enhanceMouseEvent(event, (this as any)._map as Map));
});
this.getContainer()!.addEventListener("mousedown", (event: MouseEvent) => {
this.mousedownEvent.emit(enhanceMouseEvent(event, (this as any)._map as Map));
});
this.getContainer()!.addEventListener("mouseover", (event: MouseEvent) => {
this.mouseoverEvent.emit(enhanceMouseEvent(event, (this as any)._map as Map));
});
this.getContainer()!.addEventListener("mouseout", (event: MouseEvent) => {
this.mouseoutEvent.emit(enhanceMouseEvent(event, (this as any)._map as Map));
});
}
} | the_stack |
import * as React from "react";
import { Nav } from "../components/Nav";
import Head from "next/head";
import { Transition } from "@tailwindui/react";
import { FlagBag } from "@happykit/flags/client";
export function Layout(props: {
title: string;
source?: string;
children: React.ReactNode;
flagBag: FlagBag | null;
}) {
const [expanded, setExpanded] = React.useState<boolean>(false);
// has to be done this way to avoid differing output in client and server render
const [supportsPerformanceMetrics, setSupportsPerformanceMetrics] =
React.useState<boolean>(false);
React.useEffect(
() => setSupportsPerformanceMetrics(typeof performance !== "undefined"),
[]
);
const [performanceEntry, setPerformanceEntry] =
React.useState<null | PerformanceResourceTiming>(null);
React.useEffect(() => {
if (typeof performance === "undefined") return;
if (props.flagBag && props.flagBag.settled) {
const entries = performance
.getEntriesByType("resource")
.filter(
(entry) =>
entry.name ===
[
process.env.NEXT_PUBLIC_FLAGS_ENDPOINT!,
process.env.NEXT_PUBLIC_FLAGS_ENV_KEY!,
].join("/")
);
if (entries.length > 0) {
setPerformanceEntry(
entries[entries.length - 1] as PerformanceResourceTiming
);
}
}
}, [props.flagBag]);
// clear timings so the next page doesn't accidentally load timings
// of the current page
React.useEffect(() => {
if (typeof performance === "undefined") return;
return () => {
performance.clearResourceTimings();
performance.clearMeasures();
performance.clearMarks();
};
}, []);
return (
<React.Fragment>
<Head>
<title>{props.title} · HappyKit Flags Documentation</title>
</Head>
{/* This example requires Tailwind CSS v2.0+ */}
<div className="h-screen flex overflow-hidden bg-gray-100">
{/* Off-canvas menu for mobile, show/hide based on off-canvas menu state. */}
{expanded && (
<div className="md:hidden">
<div className="fixed inset-0 flex z-40">
<Transition
show={expanded}
enter="transition-opacity ease-linear duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="transition-opacity ease-linear duration-300"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0">
<div className="absolute inset-0 bg-gray-600 opacity-75" />
</div>
</Transition>
<Transition
show={expanded}
enter="transition ease-in-out duration-300 transform"
enterFrom="-translate-x-full"
enterTo="translate-x-0"
leave="transition ease-in-out duration-300 transform"
leaveFrom="translate-x-0"
leaveTo="-translate-x-full"
>
<div className="relative flex-1 flex flex-col max-w-xs w-full h-full bg-white">
<div className="absolute top-0 right-0 -mr-12 pt-2">
<button
type="button"
className="ml-1 flex items-center justify-center h-10 w-10 rounded-full focus:outline-none focus:ring-2 focus:ring-inset focus:ring-white"
onClick={() => setExpanded(false)}
>
<span className="sr-only">Close sidebar</span>
{/* Heroicon name: outline/x */}
<svg
className="h-6 w-6 text-white"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
</div>
<div className="flex-shrink-0 flex items-center px-4 pt-5">
<img
className="h-8 w-auto"
src="/logo.svg"
alt="HappyKit Logo"
/>
</div>
<div className="flex-1 h-0 pt-5 pb-4 overflow-y-auto">
<nav
className="mt-5 flex-1 pl-2 pr-4 space-y-1 bg-white"
aria-label="Sidebar"
>
<Nav />
</nav>
</div>
<div className="flex-shrink-0 flex border-t border-gray-200 p-4">
<a
href="https://github.com/happykit/flags"
className="flex-shrink-0 group block"
>
<div className="flex items-center">
<div>
<img
className="inline-block h-10 w-10 rounded-full"
src="/github.svg"
alt=""
/>
</div>
<div className="ml-3">
<p className="text-sm font-mono font-light text-gray-700 group-hover:text-gray-900">
@happykit/flags
</p>
<p className="text-xs font-medium text-gray-500 group-hover:text-gray-700">
Open on GitHub
</p>
</div>
</div>
</a>
</div>
</div>
<div className="flex-shrink-0 w-14">
{/* Force sidebar to shrink to fit close icon */}
</div>
</Transition>
</div>
</div>
)}{" "}
{/* Static sidebar for desktop */}
<div className="hidden md:flex md:flex-shrink-0">
<div className="flex flex-col w-80">
<div className="flex flex-col h-0 flex-1 border-r border-gray-200 bg-white">
<div className="flex items-center flex-shrink-0 px-4 pt-5">
<img
className="h-8 w-auto"
src="/logo.svg"
alt="HappyKit Logo"
/>
</div>
<div className="flex-1 flex flex-col pb-4 overflow-y-auto">
<div className="mt-3 flex-1 px-2 bg-white space-y-1">
<div className="mt-3 flex-grow flex flex-col">
<nav
className="flex-1 px-2 space-y-1 bg-white"
aria-label="Sidebar"
>
<Nav />
</nav>
</div>
</div>
</div>
<div className="flex-shrink-0 flex border-t border-gray-200 p-4">
<a
href="https://github.com/happykit/flags"
className="flex-shrink-0 w-full group block"
>
<div className="flex items-center">
<div>
<img
className="inline-block h-9 w-9 rounded-full"
src="/github.svg"
alt=""
/>
</div>
<div className="ml-3">
<p className="text-sm font-mono font-light text-gray-700 group-hover:text-gray-900">
@happykit/flags
</p>
<p className="text-xs font-medium text-gray-500 group-hover:text-gray-700">
Open on GitHub
</p>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
<div className="flex flex-col w-0 flex-1 overflow-hidden">
<div className="md:hidden pl-1 pt-1 sm:pl-3 sm:pt-3">
<button
className="-ml-0.5 -mt-0.5 h-12 w-12 inline-flex items-center justify-center rounded-md text-gray-500 hover:text-gray-900 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-indigo-500"
type="button"
onClick={() => setExpanded(true)}
>
<span className="sr-only">Open sidebar</span>
{/* Heroicon name: outline/menu */}
<svg
className="h-6 w-6"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M4 6h16M4 12h16M4 18h16"
/>
</svg>
</button>
</div>
<main
className="flex-1 relative z-0 overflow-y-auto focus:outline-none flex flex-col min-h-screen"
tabIndex={0}
>
<div className="py-6 max-w-prose flex-auto">
<div className="max-w-7xl mx-auto px-4 sm:px-6 md:px-8">
<h1 className="text-2xl font-semibold text-gray-900">
{props.title}
</h1>
{props.source && (
<div className="mt-4 rounded-md bg-blue-50 border border-blue-200 p-4">
<div className="flex">
<div className="flex-shrink-0">
{/* Heroicon name: solid/information-circle */}
<svg
className="h-5 w-5 text-blue-400"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fillRule="evenodd"
d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
clipRule="evenodd"
/>
</svg>
</div>
<div className="ml-3">
<p className="text-sm text-blue-600">
This demo is easiest to understand if you open its
source code in a parallel tab.
</p>
<p className="mt-3 text-sm">
<a
href={props.source}
target="_blank"
className="whitespace-nowrap font-medium text-blue-600 hover:text-blue-700"
>
Source code <span aria-hidden="true">→</span>
</a>
</p>
</div>
</div>
</div>
)}
</div>
<div className="max-w-7xl mx-auto px-4 sm:px-6 md:px-8">
{props.children}
</div>
</div>
{supportsPerformanceMetrics && (
<div className="bg-gray-100">
<hr />
<div className="pt-3 pb-1 font-semibold max-w-7xl mx-auto px-4 sm:px-6 md:px-8 text-gray-500 uppercase tracking-wide text-sm">
Performance
</div>
{performanceEntry ? (
<div className="pb-3 max-w-7xl mx-auto px-4 sm:px-6 md:px-8 text-gray-500 text-sm">
The last flag evaluation request took{" "}
{Math.floor(performanceEntry.duration)}ms.{" "}
{Math.floor(performanceEntry.duration) < 100 && (
<React.Fragment>
For comparison:{" "}
<a
href="https://en.wikipedia.org/wiki/Blinking"
className="hover:underline"
rel="noopener noreferrer"
target="_blank"
>
The blink of a human eye takes 100ms
</a>
.
</React.Fragment>
)}
</div>
) : (
<div className="pb-3 max-w-7xl mx-auto px-4 sm:px-6 md:px-8 text-gray-500 text-sm">
No feature flags loaded by the browser so far.
</div>
)}
</div>
)}
</main>
</div>
</div>
</React.Fragment>
);
} | the_stack |
// region IMPORTS
// tslint:disable-next-line:max-line-length
import { Action, Aggregator, Dynamic, Indexer, Predicate, Selector, ZipSelector, Type } from "./Types";
import
{
ArrayEnumerable,
ConcatEnumerable,
ConditionalEnumerable,
Enumerable,
IEnumerable,
IGrouping,
IKeyValue,
IOrderedEnumerable,
IQueryable,
OrderedEnumerable,
RangeEnumerable,
ReverseEnumerable,
TransformEnumerable,
UniqueEnumerable,
ZippedEnumerable,
} from "./Enumerables";
import { Comparer, EqualityComparer, strictEqualityComparer, createComparer } from "./Comparers";
import { IIterable, ArrayIterator } from "./Iterators";
// endregion
// region EnumerableCollection
export abstract class EnumerableCollection<TElement>
implements IQueryable<TElement>
{
public abstract copy(): IQueryable<TElement>;
public abstract asEnumerable(): IEnumerable<TElement>;
public abstract toArray(): TElement[];
public toList(): IList<TElement>
{
return new List<TElement>(this.toArray());
}
public toDictionary<TKey extends Indexer, TValue>(
keySelector: Selector<TElement, TKey>,
valueSelector: Selector<TElement, TValue>)
: IDictionary<TKey, TValue>
{
return Dictionary.fromArray(this.toArray(), keySelector, valueSelector);
}
public reverse(): IEnumerable<TElement>
{
return new ReverseEnumerable<TElement>(this.asEnumerable());
}
public concat(
other: TElement[] | IQueryable<TElement>,
...others: Array<TElement[] | IQueryable<TElement>>)
: IEnumerable<TElement>
{
return this.asEnumerable().concat(other, ...others);
}
public contains(element: TElement): boolean
{
return this.any(e => e === element);
}
public where(predicate: Predicate<TElement>): IEnumerable<TElement>
{
return new ConditionalEnumerable<TElement>(this.asEnumerable(), predicate);
}
public select<TSelectorOut>(selector: Selector<TElement, TSelectorOut>): IEnumerable<TSelectorOut>
{
return new TransformEnumerable<TElement, TSelectorOut>(this.asEnumerable(), selector);
}
public selectMany<TSelectorOut>(
selector: Selector<TElement, TSelectorOut[] | List<TSelectorOut> | IEnumerable<TSelectorOut>>)
: IEnumerable<TSelectorOut>
{
const selectToEnumerable = (e: TElement) =>
{
const ie = selector(e);
return ie instanceof Array
? new ArrayEnumerable(ie)
: ie.asEnumerable();
};
return this
.select(selectToEnumerable).toArray()
.reduce((p, c) => new ConcatEnumerable(p, c), Enumerable.empty()) as IEnumerable<TSelectorOut>;
}
public elementAt(index: number): TElement
{
const element = this.elementAtOrDefault(index);
if (element === undefined)
{
throw new Error("Out of bounds");
}
return element;
}
public except(other: IQueryable<TElement>): IEnumerable<TElement>
{
return this.asEnumerable().except(other);
}
public first(): TElement;
public first(predicate: Predicate<TElement>): TElement;
public first(predicate?: Predicate<TElement>): TElement
{
let element: TElement | undefined;
if (predicate !== undefined)
{
element = this.firstOrDefault(predicate);
}
else
{
element = this.firstOrDefault();
}
if (element === undefined)
{
throw new Error("Sequence contains no elements");
}
return element;
}
public groupBy<TKey extends Indexer>(
keySelector: Selector<TElement, TKey>)
: IEnumerable<IGrouping<TKey, TElement>>;
public groupBy<TKey extends Indexer, TValue>(
keySelector: Selector<TElement, TKey>,
valueSelector: Selector<TElement, TValue>)
: IEnumerable<IGrouping<TKey, TValue>>;
public groupBy<TKey extends Indexer, TValue>(
keySelector: Selector<TElement, TKey>,
valueSelector?: Selector<TElement, TValue>)
: IEnumerable<IGrouping<TKey, TElement | TValue>>
{
const array = this.toArray();
const dictionary = new Dictionary<TKey, IQueryable<TElement | TValue>>();
for (let i = 0; i < array.length; ++i)
{
const key = keySelector(array[i]);
const value = valueSelector !== undefined
? valueSelector(array[i])
: array[i];
if (!dictionary.containsKey(key))
{
dictionary.set(key, new List<TElement | TValue>());
}
(dictionary.get(key) as IList<TElement | TValue>).push(value);
}
return dictionary.asEnumerable();
}
public last(): TElement;
public last(predicate: Predicate<TElement>): TElement;
public last(predicate?: Predicate<TElement>): TElement
{
let element: TElement | undefined;
if (predicate !== undefined)
{
element = this.lastOrDefault(predicate);
}
else
{
element = this.lastOrDefault();
}
if (element === undefined)
{
throw new Error("Sequence contains no elements");
}
return element;
}
public single(): TElement;
public single(predicate: Predicate<TElement>): TElement;
public single(predicate?: Predicate<TElement>): TElement
{
let element: TElement | undefined;
if (predicate !== undefined)
{
element = this.singleOrDefault(predicate);
}
else
{
element = this.singleOrDefault();
}
if (element === undefined)
{
throw new Error("Sequence contains no elements");
}
return element;
}
public singleOrDefault(): TElement | undefined;
public singleOrDefault(predicate: Predicate<TElement>): TElement | undefined;
public singleOrDefault(predicate?: Predicate<TElement>): TElement | undefined
{
if (predicate !== undefined)
{
return this.asEnumerable().singleOrDefault(predicate);
}
return this.asEnumerable().singleOrDefault();
}
public skipWhile(predicate: Predicate<TElement>): IEnumerable<TElement>
{
return this.asEnumerable().skipWhile(predicate);
}
public takeWhile(predicate: Predicate<TElement>): IEnumerable<TElement>
{
return this.asEnumerable().takeWhile(predicate);
}
public sequenceEqual(other: IQueryable<TElement> | TElement[]): boolean
public sequenceEqual(other: IQueryable<TElement> | TElement[], comparer: EqualityComparer<TElement>): boolean;
public sequenceEqual(other: IQueryable<TElement> | TElement[], comparer?: EqualityComparer<TElement>): boolean
{
if (comparer !== undefined)
{
return this.asEnumerable().sequenceEqual(other, comparer);
}
return this.asEnumerable().sequenceEqual(other);
}
public distinct(): IEnumerable<TElement>;
public distinct<TKey>(keySelector: Selector<TElement, TKey>): IEnumerable<TElement>;
public distinct<TKey>(keySelector?: Selector<TElement, TKey>): IEnumerable<TElement>
{
return new UniqueEnumerable(this.asEnumerable(), keySelector);
}
public min(): TElement;
public min<TSelectorOut>(selector: Selector<TElement, TSelectorOut>): TSelectorOut;
public min<TSelectorOut>(selector?: Selector<TElement, TSelectorOut>): TElement | TSelectorOut
{
if (selector !== undefined)
{
// Don't copy iterators
return new TransformEnumerable<TElement, TSelectorOut>(this.asEnumerable(), selector).min();
}
return this.aggregate((previous, current) =>
(previous !== undefined && previous < current)
? previous
: current);
}
public orderBy<TKey>(
keySelector: Selector<TElement, TKey>): IOrderedEnumerable<TElement>;
public orderBy<TKey>(
keySelector: Selector<TElement, TKey>,
comparer: Comparer<TKey>): IOrderedEnumerable<TElement>;
public orderBy<TKey>(
keySelector: Selector<TElement, TKey>,
comparer?: Comparer<TKey>): IOrderedEnumerable<TElement>
{
return new OrderedEnumerable(this.asEnumerable(), createComparer(keySelector, true, comparer));
}
public orderByDescending<TKey>(
keySelector: Selector<TElement, TKey>): IOrderedEnumerable<TElement>
{
return new OrderedEnumerable(this.asEnumerable(), createComparer(keySelector, false, undefined));
}
public max(): TElement;
public max<TSelectorOut>(selector: Selector<TElement, TSelectorOut>): TSelectorOut;
public max<TSelectorOut>(selector?: Selector<TElement, TSelectorOut>): TElement | TSelectorOut
{
if (selector !== undefined)
{
// Don't copy iterators
return new TransformEnumerable<TElement, TSelectorOut>(this.asEnumerable(), selector).max();
}
return this.aggregate((previous, current) =>
(previous !== undefined && previous > current)
? previous
: current);
}
public sum(selector: Selector<TElement, number>): number
{
return this.aggregate(
(previous: number, current: TElement) => previous + selector(current), 0);
}
public skip(amount: number): IEnumerable<TElement>
{
return new RangeEnumerable<TElement>(this.asEnumerable(), amount, undefined);
}
public take(amount: number): IEnumerable<TElement>
{
return new RangeEnumerable<TElement>(this.asEnumerable(), undefined, amount);
}
public union(other: IQueryable<TElement>): IEnumerable<TElement>
{
return new UniqueEnumerable(this.concat(other));
}
public aggregate(aggregator: Aggregator<TElement, TElement | undefined>): TElement;
public aggregate<TValue>(aggregator: Aggregator<TElement, TValue>, initialValue: TValue): TValue;
public aggregate<TValue>(
aggregator: Aggregator<TElement, TValue | TElement | undefined>,
initialValue?: TValue): TValue | TElement
{
if (initialValue !== undefined)
{
return this.asEnumerable().aggregate(
aggregator as Aggregator<TElement, TValue>,
initialValue);
}
return this.asEnumerable().aggregate(
aggregator as Aggregator<TElement, TElement | undefined>);
}
public any(): boolean;
public any(predicate: Predicate<TElement>): boolean;
public any(predicate?: Predicate<TElement>): boolean
{
if (predicate !== undefined)
{
return this.asEnumerable().any(predicate);
}
return this.asEnumerable().any();
}
public all(predicate: Predicate<TElement>): boolean
{
return this.asEnumerable().all(predicate);
}
public average(selector: Selector<TElement, number>): number
{
return this.asEnumerable().average(selector);
}
public count(): number;
public count(predicate: Predicate<TElement>): number;
public count(predicate?: Predicate<TElement>): number
{
if (predicate !== undefined)
{
return this.asEnumerable().count(predicate);
}
return this.asEnumerable().count();
}
public elementAtOrDefault(index: number): TElement | undefined
{
return this.asEnumerable().elementAtOrDefault(index);
}
public firstOrDefault(): TElement | undefined;
public firstOrDefault(predicate: Predicate<TElement>): TElement | undefined;
public firstOrDefault(predicate?: Predicate<TElement>): TElement | undefined
{
if (predicate !== undefined)
{
return this.asEnumerable().firstOrDefault(predicate);
}
return this.asEnumerable().firstOrDefault();
}
public lastOrDefault(): TElement | undefined;
public lastOrDefault(predicate: Predicate<TElement>): TElement | undefined;
public lastOrDefault(predicate?: Predicate<TElement>): TElement | undefined
{
if (predicate !== undefined)
{
return this.asEnumerable().lastOrDefault(predicate);
}
return this.asEnumerable().lastOrDefault();
}
public forEach(action: Action<TElement>): void
{
return this.asEnumerable().forEach(action);
}
public defaultIfEmpty(): IEnumerable<TElement | undefined>;
public defaultIfEmpty(defaultValue: TElement): IEnumerable<TElement>;
public defaultIfEmpty(defaultValue?: TElement): IEnumerable<TElement | undefined>
{
if (defaultValue !== undefined)
{
return this.asEnumerable().defaultIfEmpty(defaultValue);
}
return this.asEnumerable().defaultIfEmpty();
}
public zip<TOther, TSelectorOut>(other: IQueryable<TOther> | TOther[], selector: ZipSelector<TElement, TOther, TSelectorOut>): IEnumerable<TSelectorOut>
{
return this.asEnumerable().zip(other, selector);
}
}
// endregion
// region ArrayQueryable
export abstract class ArrayQueryable<TElement>
extends EnumerableCollection<TElement>
{
protected source: TElement[];
public abstract copy(): IQueryable<TElement>;
public constructor();
public constructor(elements: TElement[])
public constructor(elements: TElement[] = [])
{
super();
this.source = elements;
}
public asArray(): TElement[]
{
return this.source;
}
public toArray(): TElement[]
{
return ([] as TElement[]).concat(this.source);
}
public toList(): IList<TElement>
{
return new List<TElement>(this.toArray());
}
public asEnumerable(): IEnumerable<TElement>
{
return new ArrayEnumerable(this.source);
}
public aggregate(aggregator: Aggregator<TElement, TElement | undefined>): TElement;
public aggregate<TValue>(aggregator: Aggregator<TElement, TValue>, initialValue: TValue): TValue;
public aggregate<TValue>(
aggregator: Aggregator<TElement, TValue | TElement | undefined>,
initialValue?: TValue): TValue | TElement
{
if (initialValue !== undefined)
{
return this.source.reduce(
aggregator as Aggregator<TElement, TValue>,
initialValue);
}
return this.source.reduce(aggregator as Aggregator<TElement, TElement>);
}
public any(): boolean;
public any(predicate: Predicate<TElement>): boolean;
public any(predicate?: Predicate<TElement>): boolean
{
if (predicate !== undefined)
{
return this.source.some(predicate);
}
return this.source.length > 0;
}
public all(predicate: Predicate<TElement>): boolean
{
return this.source.every(predicate);
}
public average(selector: Selector<TElement, number>): number
{
if (this.count() === 0)
{
throw new Error("Sequence contains no elements");
}
let sum = 0;
for (let i = 0, end = this.source.length; i < end; ++i)
{
sum += selector(this.source[i]);
}
return sum / this.source.length;
}
public count(): number;
public count(predicate: Predicate<TElement>): number;
public count(predicate?: Predicate<TElement>): number
{
if (predicate !== undefined)
{
return this.source.filter(predicate).length;
}
return this.source.length;
}
public elementAtOrDefault(index: number): TElement | undefined
{
if (index < 0)
{
throw new Error("Negative index is forbiden");
}
return this.source[index];
}
public firstOrDefault(): TElement | undefined;
public firstOrDefault(predicate: Predicate<TElement>): TElement | undefined;
public firstOrDefault(predicate?: Predicate<TElement>): TElement | undefined
{
if (predicate !== undefined)
{
return this.source.filter(predicate)[0];
}
return this.source[0];
}
public groupBy<TKey extends Indexer>(
keySelector: Selector<TElement, TKey>)
: IEnumerable<IGrouping<TKey, TElement>>;
public groupBy<TKey extends Indexer, TValue>(
keySelector: Selector<TElement, TKey>,
valueSelector: Selector<TElement, TValue>)
: IEnumerable<IGrouping<TKey, TValue>>;
public groupBy<TKey extends Indexer, TValue>(
keySelector: Selector<TElement, TKey>,
valueSelector?: Selector<TElement, TValue>)
: IEnumerable<IGrouping<TKey, TElement | TValue>>
{
const array = this.asArray();
const dictionary = new Dictionary<TKey, IQueryable<TElement | TValue>>();
for (let i = 0; i < array.length; ++i)
{
const key = keySelector(array[i]);
const value = valueSelector !== undefined
? valueSelector(array[i])
: array[i];
if (!dictionary.containsKey(key))
{
dictionary.set(key, new List<TElement | TValue>());
}
(dictionary.get(key) as IList<TElement | TValue>).push(value);
}
return dictionary.asEnumerable();
}
public lastOrDefault(): TElement | undefined;
public lastOrDefault(predicate: Predicate<TElement>): TElement | undefined;
public lastOrDefault(predicate?: Predicate<TElement>): TElement | undefined
{
if (predicate !== undefined)
{
const records = this.source.filter(predicate);
return records[records.length - 1];
}
return this.source[this.source.length - 1];
}
public forEach(action: Action<TElement>): void
{
for (let i = 0, end = this.source.length; i < end; ++i)
{
action(this.source[i], i);
}
}
public sequenceEqual(other: IQueryable<TElement> | TElement[]): boolean;
public sequenceEqual(other: IQueryable<TElement> | TElement[], comparer: EqualityComparer<TElement>): boolean;
public sequenceEqual(other: IQueryable<TElement> | TElement[], comparer: EqualityComparer<TElement> = strictEqualityComparer<TElement>()): boolean
{
if (other instanceof ArrayQueryable
|| other instanceof Array)
{
const thisArray = this.asArray();
const otherArray = other instanceof ArrayQueryable
? other.asArray() as TElement[]
: other;
if (thisArray.length != otherArray.length)
{
return false;
}
for (let i = 0; i < thisArray.length; ++i)
{
if (!comparer(thisArray[i], otherArray[i]))
{
return false;
}
}
return true;
}
return this.asEnumerable().sequenceEqual(other, comparer);
}
}
// endregion
// region List
export interface IReadOnlyList<TElement>
extends IQueryable<TElement>
{
copy(): IList<TElement>;
get(index: number): TElement | undefined;
indexOf(element: TElement): number;
}
export interface IList<TElement>
extends IReadOnlyList<TElement>
{
asReadOnly(): IReadOnlyList<TElement>;
asArray(): TElement[];
clear(): void;
push(element: TElement): number;
pushRange(elements: TElement[] | IQueryable<TElement>): number;
pushFront(element: TElement): number;
pop(): TElement | undefined;
popFront(): TElement | undefined;
remove(element: TElement): void;
removeAt(index: number): TElement | undefined;
set(index: number, element: TElement): void;
insert(index: number, element: TElement): void;
}
export class List<TElement>
extends ArrayQueryable<TElement>
implements IList<TElement>
{
public copy(): IList<TElement>
{
return new List<TElement>(this.toArray());
}
public asReadOnly(): IReadOnlyList<TElement>
{
return this;
}
public clear(): void
{
this.source = [];
}
public remove(element: TElement): void
{
const newSource: TElement[] = [];
for (let i = 0, end = this.source.length; i < end; ++i)
{
if (this.source[i] !== element)
{
newSource.push(this.source[i]);
}
}
this.source = newSource;
}
public removeAt(index: number): TElement | undefined
{
if (index < 0 || this.source[index] === undefined)
{
throw new Error("Out of bounds");
}
return this.source.splice(index, 1)[0];
}
public get(index: number): TElement | undefined
{
return this.source[index];
}
public push(element: TElement): number
{
return this.source.push(element);
}
public pushRange(elements: TElement[] | IQueryable<TElement>): number
{
if (!(elements instanceof Array))
{
elements = elements.toArray();
}
return this.source.push.apply(this.source, elements);
}
public pushFront(element: TElement): number
{
return this.source.unshift(element);
}
public pop(): TElement | undefined
{
return this.source.pop();
}
public popFront(): TElement | undefined
{
return this.source.shift();
}
public set(index: number, element: TElement): void
{
if (index < 0)
{
throw new Error("Out of bounds");
}
this.source[index] = element;
}
public insert(index: number, element: TElement): void
{
if (index < 0 || index > this.source.length)
{
throw new Error("Out of bounds");
}
this.source.splice(index, 0, element);
}
public indexOf(element: TElement): number
{
return this.source.indexOf(element);
}
}
// endregion
// region Stack
export interface IStack<TElement>
extends IQueryable<TElement>
{
copy(): IStack<TElement>;
asArray(): TElement[];
clear(): void;
peek(): TElement | undefined;
pop(): TElement | undefined;
push(element: TElement): number;
}
export class Stack<TElement>
extends ArrayQueryable<TElement>
implements IStack<TElement>
{
public copy(): IStack<TElement>
{
return new Stack<TElement>(this.toArray());
}
public clear(): void
{
this.source = [];
}
public peek(): TElement | undefined
{
return this.source[this.source.length - 1];
}
public pop(): TElement | undefined
{
return this.source.pop();
}
public push(element: TElement): number
{
return this.source.push(element);
}
}
// endregion
// region Dictionary
export interface IReadOnlyDictionary<TKey extends Indexer, TValue>
extends IQueryable<IKeyValue<TKey, TValue>>
{
copy(): IDictionary<TKey, TValue>;
containsKey(key: TKey): boolean;
containsValue(value: TValue): boolean;
getKeys(): IList<TKey>;
getValues(): IList<TValue>;
get(key: TKey): TValue;
}
export interface IDictionary<TKey extends Indexer, TValue>
extends IReadOnlyDictionary<TKey, TValue>
{
asReadOnly(): IReadOnlyDictionary<TKey, TValue>;
clear(): void;
remove(key: TKey): void;
set(key: TKey, value: TValue): void;
setOrUpdate(key: TKey, value: TValue): void;
}
export class Dictionary<TKey extends Indexer, TValue>
extends EnumerableCollection<IKeyValue<TKey, TValue>>
implements IDictionary<TKey, TValue>
{
public static fromArray<TArray, TKey extends Indexer, TValue>(
array: TArray[],
keySelector: Selector<TArray, TKey>,
valueSelector: Selector<TArray, TValue>)
: IDictionary<TKey, TValue>
{
const keyValuePairs = array.map<IKeyValue<TKey, TValue>>(v =>
{
return {
key: keySelector(v),
value: valueSelector(v),
};
});
return new Dictionary(keyValuePairs);
}
public static fromJsObject<TValue = string>(
object: Dynamic)
: IDictionary<string, TValue>
{
const keys = new List(Object.getOwnPropertyNames(object));
const keyValues = keys.select(k => <IKeyValue<string, TValue>>{ key: k, value: object[k] });
return new Dictionary(keyValues.toArray());
}
protected dictionary: Dynamic;
protected keyType: Type;
public constructor();
public constructor(keyValuePairs: Array<IKeyValue<TKey, TValue>>);
public constructor(keyValuePairs?: Array<IKeyValue<TKey, TValue>>)
{
super();
this.clear();
if (keyValuePairs !== undefined)
{
for (let i = 0; i < keyValuePairs.length; ++i)
{
const pair = keyValuePairs[i];
this.set(pair.key, pair.value);
}
}
}
public copy(): IDictionary<TKey, TValue>
{
return new Dictionary<TKey, TValue>(this.toArray());
}
public asReadOnly(): IReadOnlyDictionary<TKey, TValue>
{
return this;
}
public asEnumerable(): IEnumerable<IKeyValue<TKey, TValue>>
{
return new ArrayEnumerable(this.toArray());
}
public toArray(): Array<IKeyValue<TKey, TValue>>
{
return this.getKeys().select<IKeyValue<TKey, TValue>>(p =>
{
return {
key: p,
value: this.dictionary[p],
};
}).toArray();
}
public clear(): void
{
this.dictionary = {};
}
public containsKey(key: TKey): boolean
{
return this.dictionary.hasOwnProperty(key);
}
public containsValue(value: TValue): boolean
{
const keys = this.getKeysFast();
for (let i = 0; i < keys.length; ++i)
{
if (this.dictionary[keys[i]] === value)
{
return true;
}
}
return false;
}
public getKeys(): IList<TKey>
{
const keys = this.getKeysFast();
return new List(keys.map(
k => this.keyType === "number"
? parseFloat(k)
: k) as TKey[]);
}
protected getKeysFast(): string[]
{
return Object.getOwnPropertyNames(this.dictionary);
}
public getValues(): IList<TValue>
{
const keys = this.getKeysFast();
const result = new Array<TValue>(keys.length);
for (let i = 0; i < keys.length; ++i)
{
result[i] = this.dictionary[keys[i]];
}
return new List(result);
}
public remove(key: TKey): void
{
if (this.containsKey(key))
{
delete this.dictionary[key];
}
}
public get(key: TKey): TValue
{
if (!this.containsKey(key))
{
throw new Error(`Key doesn't exist: ${key}`)
}
return this.dictionary[key];
}
public set(key: TKey, value: TValue): void
{
if (this.containsKey(key))
{
throw new Error(`Key already exists: ${key}`);
}
this.setOrUpdate(key, value);
}
public setOrUpdate(key: TKey, value: TValue): void
{
if (this.keyType === undefined)
{
this.keyType = typeof key;
}
this.dictionary[key] = value;
}
}
// endregion | the_stack |
import { expect } from 'chai';
import { mergeWith } from 'lodash';
import { getMovableItemsCounts, mergeAccounts, simulateMergeAccounts } from '../../../server/lib/merge-accounts';
import models from '../../../server/models';
import { LEGAL_DOCUMENT_TYPE } from '../../../server/models/LegalDocument';
import { MigrationLogDataForMergeAccounts, MigrationLogType } from '../../../server/models/MigrationLog';
import * as Faker from '../../test-helpers/fake-data';
import { resetTestDB } from '../../utils';
/** Helper to create an account with many associations */
const addFakeDataToAccount = async (account): Promise<void> => {
// Pre-generating a random collective to save some performance
const randomCollective = await Faker.fakeCollective();
const user = account.type === 'USER' ? await account.getUser() : await Faker.fakeUser();
await Promise.all([
Faker.fakeActivity({ CollectiveId: account.id }, { hooks: false }),
Faker.fakeApplication({ CollectiveId: account.id }),
Faker.fakeComment({ CollectiveId: account.id, FromCollectiveId: randomCollective.id }, { hooks: false }),
Faker.fakeComment({ FromCollectiveId: account.id, CollectiveId: randomCollective.id }, { hooks: false }),
Faker.fakeConnectedAccount({ CollectiveId: account.id }, { hooks: false }),
Faker.fakeConversation({ CollectiveId: account.id, FromCollectiveId: randomCollective.id }, { hooks: false }),
Faker.fakeConversation({ FromCollectiveId: account.id, CollectiveId: randomCollective.id }, { hooks: false }),
Faker.fakeEmojiReaction({ FromCollectiveId: account.id }),
Faker.fakeExpense({ CollectiveId: account.id, FromCollectiveId: randomCollective.id, UserId: user.id }),
Faker.fakeExpense({ FromCollectiveId: account.id, CollectiveId: randomCollective.id, UserId: user.id }),
// TODO Faker.fakeHostApplication({ HostCollectiveId: account.id, CollectiveId: randomCollective.id }),
// TODO Faker.fakeHostApplication({ CollectiveId: account.id, HostCollectiveId: randomCollective.id }),
Faker.fakeLegalDocument({ CollectiveId: account.id, year: 2020, documentType: LEGAL_DOCUMENT_TYPE.US_TAX_FORM }),
// TODO Faker.fakeMemberInvitation({ MemberCollectiveId: account.id }),
Faker.fakeMember({ MemberCollectiveId: account.id, CollectiveId: randomCollective.id }),
Faker.fakeNotification({ CollectiveId: account.id, UserId: user.id }),
Faker.fakeOrder({
FromCollectiveId: account.id,
CollectiveId: randomCollective.id,
CreatedByUserId: user.id,
}),
Faker.fakeOrder({
CollectiveId: account.id,
FromCollectiveId: randomCollective.id,
CreatedByUserId: user.id,
}),
Faker.fakePaymentMethod({ CollectiveId: account.id, service: 'stripe', type: 'creditcard' }),
Faker.fakePayoutMethod({ CollectiveId: account.id }),
Faker.fakePaypalProduct({ CollectiveId: account.id }),
// TODO Faker.fakeRequiredLegalDocument({ HostCollectiveId: account.id }),
Faker.fakeTier({ CollectiveId: account.id }),
Faker.fakeTransaction({ FromCollectiveId: account.id, CollectiveId: randomCollective.id }),
Faker.fakeTransaction({ CollectiveId: account.id, FromCollectiveId: randomCollective.id }),
Faker.fakeTransaction({
UsingGiftCardFromCollectiveId: account.id,
FromCollectiveId: randomCollective.id,
CollectiveId: randomCollective.id,
}),
Faker.fakeUpdate({ CollectiveId: account.id }, { hooks: false }),
Faker.fakeUpdate({ FromCollectiveId: account.id }, { hooks: false }),
]);
if (account.type !== 'USER') {
await Promise.all([
// TODO Faker.fakeMemberInvitation({ CollectiveId: account.id }),
Faker.fakeMember({ CollectiveId: account.id, MemberCollectiveId: randomCollective.id }),
Faker.fakeCollective({ HostCollectiveId: account.id }, { hooks: false }),
Faker.fakeCollective({ ParentCollectiveId: account.id, HostCollectiveId: null }, { hooks: false }),
]);
if (account.HostCollectiveId) {
await Promise.all([
Faker.fakeVirtualCard({ CollectiveId: account.id, HostCollectiveId: randomCollective.id }),
Faker.fakeVirtualCard({ HostCollectiveId: account.id, CollectiveId: randomCollective.id }),
]);
}
}
};
const sumCounts = (count1, count2) => {
return {
account: mergeWith(count1.account, count2.account, (objValue, srcValue) => {
return (objValue || 0) + (srcValue || 0);
}),
user: !count1.user
? null
: mergeWith(count1.user, count2.user, (objValue, srcValue) => {
return (objValue || 0) + (srcValue || 0);
}),
};
};
describe('server/lib/merge-accounts', () => {
let fromUser, toUser, fromOrganization, toOrganization, fromCollective, toCollective;
before(async function () {
// This test can take some time to setup on local env
this.timeout(30000);
await resetTestDB();
// Create noise data to make sure merge tools don't affect others data
await addFakeDataToAccount(await Faker.fakeCollective({ slug: 'noise-collective' }));
await addFakeDataToAccount(await Faker.fakeOrganization({ slug: 'noise-organization' }));
await addFakeDataToAccount((await Faker.fakeUser({}, { slug: 'noise-user' })).collective);
// Create the accounts that will be merged
fromCollective = await Faker.fakeCollective({ slug: 'from-collective' });
toCollective = await Faker.fakeCollective({ slug: 'to-collective' });
await addFakeDataToAccount(fromCollective);
await addFakeDataToAccount(toCollective);
fromUser = await Faker.fakeUser({}, { slug: 'from-user', countryISO: 'FR' });
toUser = await Faker.fakeUser({}, { slug: 'to-user', countryISO: null });
await addFakeDataToAccount(fromUser.collective);
await addFakeDataToAccount(toUser.collective);
fromOrganization = await Faker.fakeCollective({ slug: 'from-org', countryISO: 'FR' });
toOrganization = await Faker.fakeCollective({ slug: 'to-org', countryISO: null });
await addFakeDataToAccount(fromOrganization);
await addFakeDataToAccount(toOrganization);
});
describe('simulateMergeAccounts', () => {
it('Correctly estimates the number of items to move for collective account', async () => {
// Generate & check summary
const summary = await simulateMergeAccounts(fromCollective, toCollective);
expect(summary).to.matchSnapshot();
});
it('Correctly estimates the number of items to move for organization account', async () => {
// Generate & check summary
const summary = await simulateMergeAccounts(fromOrganization, toOrganization);
expect(summary).to.matchSnapshot();
});
it('Correctly estimates the number of items to move for user account', async () => {
// Generate & check summary
const summary = await simulateMergeAccounts(fromUser.collective, toUser.collective);
expect(summary).to.matchSnapshot();
});
});
describe('mergeAccounts', () => {
it('Merges an organization', async () => {
// Check seed data
const preMoveFromItemsCounts = await getMovableItemsCounts(fromOrganization);
const preMoveToItemsCounts = await getMovableItemsCounts(toOrganization);
expect(preMoveFromItemsCounts.account).to.matchSnapshot();
expect(preMoveToItemsCounts.account).to.matchSnapshot();
expect(preMoveFromItemsCounts.user).to.be.null;
expect(preMoveToItemsCounts.user).to.be.null;
// Merge accounts
await mergeAccounts(fromOrganization, toOrganization);
// Profile info
await fromOrganization.reload({ paranoid: false });
await toOrganization.reload();
expect(fromOrganization.deletedAt).to.not.be.null;
expect(fromOrganization.slug).to.eq('from-org-merged');
expect(fromOrganization.data.mergedIntoCollectiveId).to.eq(toOrganization.id);
expect(toOrganization.countryISO).to.eq('FR');
// Associated data
const postMoveFromItemsCounts = await getMovableItemsCounts(fromOrganization);
const postMoveToItemsCounts = await getMovableItemsCounts(toOrganization);
const expectedCounts = sumCounts(preMoveFromItemsCounts, preMoveToItemsCounts);
expectedCounts.account.legalDocuments -= 1; // Should not be transferred as one already exists
expect(postMoveToItemsCounts.account).to.matchSnapshot();
expect(postMoveToItemsCounts).to.deep.equal(expectedCounts);
expect(postMoveFromItemsCounts.user).to.be.null;
expect(postMoveToItemsCounts.user).to.be.null;
Object.values(postMoveFromItemsCounts.account).forEach(count => expect(count).to.eq(0));
// Creates a MigrationLog
const migrationLog = await models.MigrationLog.findOne({
where: {
type: MigrationLogType.MERGE_ACCOUNTS,
description: 'Merge from-org into to-org',
},
});
const migrationLogData = <MigrationLogDataForMergeAccounts>migrationLog.data;
expect(migrationLogData).to.exist;
expect(migrationLogData.fromAccount).to.eq(fromOrganization.id);
expect(migrationLogData.intoAccount).to.eq(toOrganization.id);
expect(migrationLogData.associations.members).to.have.length(2);
expect(migrationLogData.associations.expenses).to.have.length(1);
expect(migrationLogData.associations.giftCardTransactions).to.have.length(1);
});
it('Merges a user profile', async () => {
// Check seed data
const preMoveFromItemsCounts = await getMovableItemsCounts(fromUser.collective);
const preMoveToItemsCounts = await getMovableItemsCounts(toUser.collective);
expect(preMoveFromItemsCounts.account).to.matchSnapshot();
expect(preMoveToItemsCounts.account).to.matchSnapshot();
expect(preMoveFromItemsCounts.user).to.matchSnapshot();
expect(preMoveToItemsCounts.user).to.matchSnapshot();
// Prepare test data
await mergeAccounts(fromUser.collective, toUser.collective);
// Profile info
await fromUser.reload({ paranoid: false });
await fromUser.collective.reload({ paranoid: false });
await toUser.reload();
expect(fromUser.deletedAt).to.not.be.null;
expect(fromUser.collective.deletedAt).to.not.be.null;
expect(fromUser.collective.slug).to.eq('from-user-merged');
expect(fromUser.collective.data.mergedIntoCollectiveId).to.eq(toUser.CollectiveId);
expect(fromUser.data.mergedIntoUserId).to.eq(toUser.id);
expect(toUser.collective.countryISO).to.eq('FR');
// Associated data
const postMoveFromItemsCounts = await getMovableItemsCounts(fromUser.collective);
const postMoveToItemsCounts = await getMovableItemsCounts(toUser.collective);
const expectedCounts = sumCounts(preMoveFromItemsCounts, preMoveToItemsCounts);
expectedCounts.account.legalDocuments -= 1; // Should not be transferred as one already exists
expectedCounts.user.collectives -= 1; // User profile is not merged, not transferred
expect(postMoveToItemsCounts.account).to.matchSnapshot();
expect(postMoveToItemsCounts).to.deep.equal(expectedCounts);
Object.values(postMoveFromItemsCounts.account).forEach(count => expect(count).to.eq(0));
Object.values(postMoveFromItemsCounts.user).forEach(count => expect(count).to.eq(0));
// Creates a MigrationLog
const migrationLog = await models.MigrationLog.findOne({
where: {
type: MigrationLogType.MERGE_ACCOUNTS,
description: 'Merge from-user into to-user',
},
});
const migrationLogData = <MigrationLogDataForMergeAccounts>migrationLog.data;
expect(migrationLogData).to.exist;
expect(migrationLogData.fromAccount).to.eq(fromUser.collective.id);
expect(migrationLogData.intoAccount).to.eq(toUser.collective.id);
expect(migrationLogData.associations.giftCardTransactions).to.have.length(1);
expect(migrationLogData.associations.expenses).to.have.length(1);
expect(migrationLogData.userChanges.notifications).to.have.length(1);
});
});
}); | the_stack |
import {
CompletionItem,
CompletionItemKind,
createConnection,
Diagnostic,
DiagnosticSeverity,
DidChangeConfigurationNotification,
InitializeParams,
ProposedFeatures,
TextDocument,
TextDocumentPositionParams,
TextDocuments,
} from "vscode-languageserver";
import { Stack } from "../stack";
const connection = createConnection(ProposedFeatures.all);
const documents: TextDocuments = new TextDocuments();
let hasConfigCapability: boolean = false;
let hasWorkspaceFolderCapability: boolean = false;
let hasDiagnosticRelatedInfoCapability: boolean = false;
const problemSourceName = "esp-idf";
connection.onInitialize((params: InitializeParams) => {
const capabilities = params.capabilities;
hasConfigCapability = !!(
capabilities.workspace && !!capabilities.workspace.configuration
);
hasWorkspaceFolderCapability = !!(
capabilities.workspace && !!capabilities.workspace.workspaceFolders
);
hasDiagnosticRelatedInfoCapability = !!(
capabilities.textDocument &&
capabilities.textDocument.publishDiagnostics &&
capabilities.textDocument.publishDiagnostics.relatedInformation
);
return {
capabilities: {
completionProvider: {
resolveProvider: true,
},
textDocumentSync: documents.syncKind,
},
};
});
connection.onInitialized(() => {
if (hasConfigCapability) {
connection.client.register(
DidChangeConfigurationNotification.type,
undefined
);
}
if (hasWorkspaceFolderCapability) {
connection.workspace.onDidChangeWorkspaceFolders((event) => {
connection.console.log("Workspace folder change received.");
});
}
});
// Kconfig Settings interface
interface IKconfigSettings {
maxNumberOfProblems: number;
useIDFKconfigStyle: boolean;
}
const defaultSettings: IKconfigSettings = {
maxNumberOfProblems: 1000,
useIDFKconfigStyle: false,
};
let globalSettings: IKconfigSettings = defaultSettings;
// Cache of open documents settings
const docsSettings: Map<string, Thenable<IKconfigSettings>> = new Map();
connection.onDidChangeConfiguration((change) => {
if (hasConfigCapability) {
docsSettings.clear();
} else {
globalSettings = (change.settings.kconfigServer ||
defaultSettings) as IKconfigSettings;
}
documents.all().forEach(validateKConfigDocument);
});
function getDocumentsSettings(resource: string): Thenable<IKconfigSettings> {
if (!hasConfigCapability) {
return Promise.resolve(globalSettings);
}
let result = docsSettings.get(resource);
if (!result) {
result = connection.workspace.getConfiguration({
scopeUri: resource,
section: "idf",
});
docsSettings.set(resource, result);
}
return result;
}
documents.onDidClose((e) => {
docsSettings.delete(e.document.uri);
});
// The document content has changed, which triggers the next method
documents.onDidChangeContent((change) => {
validateKConfigDocument(change.document);
});
async function validateKConfigDocument(
kconfigDocument: TextDocument
): Promise<void> {
// This method would perform a lot of syntax validation ensuring file is ok.
// const settings = await getDocumentsSettings(kconfigDocument.uri);
const menuPattern = /^(\s*)\bmenu\b/g;
const endmenuPattern = /^(\s*)\bendmenu\b/gm;
const choicePattern = /^(\s*)\bchoice\b/g;
const endChoicePattern = /^(\s*)\bendchoice\b/gm;
const settings = await getDocumentsSettings(kconfigDocument.uri);
const diagnostics: Diagnostic[] = [];
diagnostics.push(
...getBlockDiagnosticsFor(menuPattern, endmenuPattern, kconfigDocument, [
"menu",
"endmenu",
])
);
diagnostics.push(
...getBlockDiagnosticsFor(
choicePattern,
endChoicePattern,
kconfigDocument,
["choice", "enchoice"]
)
);
// Use ESP-IDF Kconfig Style validation
if (settings.useIDFKconfigStyle) {
diagnostics.push(...getStringDiagnostics(kconfigDocument));
diagnostics.push(...getLineDiagnostics(kconfigDocument));
diagnostics.push(...getTreeIndentDiagnostics(kconfigDocument));
diagnostics.push(...getEmptyBlocksDiagnostics(kconfigDocument));
}
connection.sendDiagnostics({ uri: kconfigDocument.uri, diagnostics });
}
function getLineDiagnostics(kconfigDocument: TextDocument) {
const MAX_LINE_SIZE = 120;
const text = kconfigDocument.getText();
const diagnostics: Diagnostic[] = [];
const lines = text.split("\n");
let textPosition = 0;
let lineNum = 0;
for (const line of lines) {
lineNum += 1;
// Check line size is bigger than MAX_LINE_SIZE
if (line.length > MAX_LINE_SIZE) {
const diagnostic: Diagnostic = {
message: `Line ${lineNum} text should be 120 chars max. (${line.length})`,
range: {
end: kconfigDocument.positionAt(textPosition + line.length),
start: kconfigDocument.positionAt(textPosition),
},
severity: DiagnosticSeverity.Warning,
source: `${problemSourceName}`,
};
diagnostics.push(diagnostic);
}
// Check text is not wrapped with backslash (\)
const backslashWrappedPattern = /\\(.*)\\/g;
let backslashMatch = backslashWrappedPattern.exec(line);
while (backslashMatch !== null) {
const diagnostic: Diagnostic = {
message: `Line ${lineNum} wrapped by \\ is not valid.`,
range: {
end: kconfigDocument.positionAt(
textPosition + backslashMatch.index + backslashMatch.input.length
),
start: kconfigDocument.positionAt(
textPosition + backslashMatch.index
),
},
severity: DiagnosticSeverity.Error,
source: `${problemSourceName}`,
};
diagnostics.push(diagnostic);
backslashMatch = backslashWrappedPattern.exec(line);
}
// Check text doesn't start with \
const badStartPattern = /^(\\)(.*)/g;
let badStartMatch = badStartPattern.exec(line);
while (badStartMatch !== null) {
const diagnostic: Diagnostic = {
message: `Line ${lineNum} should not start with \\`,
range: {
end: kconfigDocument.positionAt(
textPosition + badStartMatch.index + badStartMatch.input.length
),
start: kconfigDocument.positionAt(textPosition + badStartMatch.index),
},
severity: DiagnosticSeverity.Warning,
source: `${problemSourceName}`,
};
diagnostics.push(diagnostic);
badStartMatch = badStartPattern.exec(line);
}
// Check there is no trailing space in each line.
const hasTrailingSpace = line[line.length - 1] === " ";
if (hasTrailingSpace) {
const diagnostic: Diagnostic = {
message: `Line ${lineNum} should not have trailing whitespace`,
range: {
end: kconfigDocument.positionAt(textPosition + line.length),
start: kconfigDocument.positionAt(textPosition + line.length - 1),
},
severity: DiagnosticSeverity.Error,
source: `${problemSourceName}`,
};
diagnostics.push(diagnostic);
}
textPosition += line.length + "\n".length;
}
return diagnostics;
}
function getTreeIndentDiagnostics(kconfigDocument: TextDocument) {
const indentSize = 4; // connection.workspace.getConfiguration("editor.tabSize");
const text = kconfigDocument.getText();
const diagnostics: Diagnostic[] = [];
const lines = text.split("\n");
let textPosition = 0;
const parentStack = new Stack();
let lineNum = 0;
for (const line of lines) {
lineNum++;
const indentRegex = /^(?!=\n)([ ]+)/g;
const lineMatch = indentRegex.exec(line);
const openingMatches = /^(\s*)\b(menu|choice|config|menuconfig|endmenu|endchoice|help|mainmenu)\b/g.exec(
line
);
if (
parentStack.size() > 0 &&
openingMatches &&
(openingMatches[0].trim() === "menu" ||
openingMatches[0].trim() === "menuconfig" ||
openingMatches[0].trim() === "choice" ||
openingMatches[0].trim() === "config")
) {
if (parentStack.peek() === "help") {
parentStack.pop();
if (parentStack.peek() !== "choice") {
parentStack.pop();
}
} else if (
parentStack.peek() === "config" ||
parentStack.peek() === "menuconfig"
) {
parentStack.pop();
}
} else if (
parentStack.size() > 0 &&
openingMatches &&
(openingMatches[0].trim() === "endmenu" ||
openingMatches[0].trim() === "endchoice")
) {
while (parentStack.size() > 0) {
const startingWord = parentStack.pop();
if (
(startingWord === "menu" && openingMatches[0].trim() === "endmenu") ||
(startingWord === "choice" &&
openingMatches[0].trim() === "endchoice")
) {
break;
}
}
}
if (
lineMatch &&
((parentStack.peek() !== "help" &&
lineMatch[1].length !== indentSize * parentStack.size()) ||
(parentStack.peek() === "help" &&
lineMatch[1].length < indentSize * parentStack.size()))
) {
const diagnostic: Diagnostic = {
message: `Line ${lineNum} has ${lineMatch[1].length}.
Expect indent ${indentSize * parentStack.size()}`,
range: {
end: kconfigDocument.positionAt(
textPosition + lineMatch.index + lineMatch[1].length
),
start: kconfigDocument.positionAt(textPosition),
},
severity: DiagnosticSeverity.Warning,
source: `${problemSourceName}`,
};
diagnostics.push(diagnostic);
}
if (openingMatches) {
if (
openingMatches[0].trim() !== "endmenu" &&
openingMatches[0].trim() !== "endchoice"
) {
parentStack.push(openingMatches[0].trim());
}
}
textPosition += line.length + "\n".length;
}
return diagnostics;
}
function getStringDiagnostics(kconfigDocument: TextDocument): Diagnostic[] {
// Resolve diagnostics for keywords that take double quoted strings
// Example: menu "mymenu"
const textPattern = /^(\s*)\b(prompt|menu|mainmenu|source|comment)\b\s(?:\")(.*)(?:\")/g;
const keyPattern = /^(\s*)\b(prompt|menu|mainmenu|source|comment)\b/g;
const text = kconfigDocument.getText();
const lines = text.split("\n");
const diagnostics: Diagnostic[] = [];
let textPosition = 0;
for (const line of lines) {
const keyMatch = keyPattern.exec(line);
const stringMatch = textPattern.exec(line);
if (keyMatch !== null && stringMatch === null) {
const diagnostic: Diagnostic = {
message: `${keyMatch[0].trim()} text should be enclosed like \"some text\"`,
range: {
end: kconfigDocument.positionAt(textPosition + line.length),
start: kconfigDocument.positionAt(
textPosition + keyMatch.index + keyMatch[1].length
),
},
severity: DiagnosticSeverity.Warning,
source: `${problemSourceName}`,
};
diagnostics.push(diagnostic);
}
textPosition += line.length + "\n".length;
}
return diagnostics;
}
function getBlockDiagnosticsFor(
openingPattern: RegExp,
closingPattern: RegExp,
kconfigDocument: TextDocument,
blockName: string[]
): Diagnostic[] {
const diagnostics: Diagnostic[] = [];
const openIndices = [];
const closeIndices = [];
const text = kconfigDocument.getText();
let openMatch = openingPattern.exec(text);
const openWordLength = blockName[0].length;
let closeMatch = closingPattern.exec(text);
while (openMatch !== null) {
openIndices.push(openMatch.index);
openMatch = openingPattern.exec(text);
}
while (closeMatch !== null) {
closeIndices.push(closeMatch.index);
closeMatch = closingPattern.exec(text);
}
for (let i = 0; i < openIndices.length; i++) {
if (closeIndices.length === 0) {
const diagnostic: Diagnostic = {
message: `${blockName[0]} statement doesn't have corresponding ${blockName[1]}`,
range: {
end: kconfigDocument.positionAt(openIndices[i] + openWordLength),
start: kconfigDocument.positionAt(openIndices[i]),
},
severity: DiagnosticSeverity.Error,
source: `${problemSourceName}`,
};
diagnostics.push(diagnostic);
continue;
}
let isCloseFound = false;
for (const closingIndex of closeIndices) {
if (closingIndex > openIndices[i] && closingIndex < openIndices[i + 1]) {
isCloseFound = true;
break;
} else if (
i === openIndices.length - 1 &&
closingIndex > openIndices[i]
) {
isCloseFound = true;
break;
}
}
if (!isCloseFound) {
const diagnostic: Diagnostic = {
message: `${blockName[0]} statement doesn't have corresponding ${blockName[1]}`,
range: {
end: kconfigDocument.positionAt(openIndices[i] + openWordLength),
start: kconfigDocument.positionAt(openIndices[i]),
},
severity: DiagnosticSeverity.Error,
source: `${problemSourceName}`,
};
diagnostics.push(diagnostic);
}
}
return diagnostics;
}
function getEmptyBlocksDiagnostics(
kconfigDocument: TextDocument
): Diagnostic[] {
const diagnostics: Diagnostic[] = [];
const menuPattern = /^menu \"(.*)\"([\s\S]+?)endmenu$/gm;
const choicePattern = /^choice (.*)([\s\S]+?)endchoice$/gm;
const ifBlockPattern = /^if (.*)([\s\S]+?)endif$/gm;
const text = kconfigDocument.getText();
let menuMatch = menuPattern.exec(text);
let choiceMatch = choicePattern.exec(text);
let ifBlockMatch = ifBlockPattern.exec(text);
while (menuMatch !== null) {
if (menuMatch[2] && menuMatch[2].length > 0 && menuMatch[2] === "\n") {
const diagnostic: Diagnostic = {
message: `menu statement doesn't have corresponding any sub-settings.`,
range: {
end: kconfigDocument.positionAt(
menuMatch.index +
`menu ""`.length +
menuMatch[1].length +
menuMatch[2].length
),
start: kconfigDocument.positionAt(
menuMatch.index + menuMatch[1].length
),
},
severity: DiagnosticSeverity.Error,
source: `${problemSourceName}`,
};
diagnostics.push(diagnostic);
}
menuMatch = menuPattern.exec(text);
}
while (choiceMatch !== null) {
if (
choiceMatch[2] &&
choiceMatch[2].length > 0 &&
choiceMatch[2] === "\n"
) {
const diagnostic: Diagnostic = {
message: `choice statement doesn't have any config options.`,
range: {
end: kconfigDocument.positionAt(
choiceMatch.index +
`choice `.length +
choiceMatch[1].length +
choiceMatch[2].length
),
start: kconfigDocument.positionAt(
choiceMatch.index + choiceMatch[1].length
),
},
severity: DiagnosticSeverity.Error,
source: `${problemSourceName}`,
};
diagnostics.push(diagnostic);
}
choiceMatch = choicePattern.exec(text);
}
while (ifBlockMatch !== null) {
if (
ifBlockMatch[2] &&
ifBlockMatch[2].length > 0 &&
ifBlockMatch[2] === "\n"
) {
const diagnostic: Diagnostic = {
message: `if statement doesn't have any config options.`,
range: {
end: kconfigDocument.positionAt(
ifBlockMatch.index +
`if `.length +
ifBlockMatch[1].length +
ifBlockMatch[2].length
),
start: kconfigDocument.positionAt(
ifBlockMatch.index + ifBlockMatch[1].length
),
},
severity: DiagnosticSeverity.Error,
source: `${problemSourceName}`,
};
diagnostics.push(diagnostic);
}
ifBlockMatch = ifBlockPattern.exec(text);
}
return diagnostics;
}
// This handler provides a list of completion items
connection.onCompletion(
(kconfigDocumentPosition: TextDocumentPositionParams) => {
return [
{
data: 1,
kind: CompletionItemKind.Text,
label: "config ",
},
{
data: 2,
kind: CompletionItemKind.Text,
label: "menu ",
},
{
data: 3,
kind: CompletionItemKind.Text,
label: "endmenu",
},
{
data: 4,
kind: CompletionItemKind.Text,
label: "bool ",
},
{
data: 5,
kind: CompletionItemKind.Text,
label: "depends on ",
},
{
data: 6,
kind: CompletionItemKind.Text,
label: "help ",
},
{
data: 7,
kind: CompletionItemKind.Text,
label: "hex ",
},
{
data: 8,
kind: CompletionItemKind.Text,
label: "tristate ",
},
{
data: 9,
kind: CompletionItemKind.Text,
label: "int ",
},
{
data: 10,
kind: CompletionItemKind.Text,
label: "string ",
},
{
data: 11,
kind: CompletionItemKind.Text,
label: "prompt ",
},
{
data: 12,
kind: CompletionItemKind.Text,
label: "default ",
},
{
data: 13,
kind: CompletionItemKind.Text,
label: "if ",
},
{
data: 14,
kind: CompletionItemKind.Text,
label: "endif",
},
{
data: 15,
kind: CompletionItemKind.Text,
label: "visible if ",
},
{
data: 16,
kind: CompletionItemKind.Text,
label: "range ",
},
{
data: 17,
kind: CompletionItemKind.Text,
label: "option ",
},
{
data: 18,
kind: CompletionItemKind.Text,
label: "defconfig_list",
},
{
data: 19,
kind: CompletionItemKind.Text,
label: "modules ",
},
{
data: 20,
kind: CompletionItemKind.Text,
label: "allnoconfig_y",
},
{
data: 21,
kind: CompletionItemKind.Text,
label: "menuconfig ",
},
{
data: 22,
kind: CompletionItemKind.Text,
label: "comment ",
},
{
data: 23,
kind: CompletionItemKind.Text,
label: "source ",
},
{
data: 24,
kind: CompletionItemKind.Text,
label: "choice ",
},
{
data: 25,
kind: CompletionItemKind.Text,
label: "endchoice",
},
{
data: 26,
kind: CompletionItemKind.Text,
label: "mainmenu ",
},
];
}
);
connection.onCompletionResolve(
(item: CompletionItem): CompletionItem => {
switch (item.data) {
case 1:
item.detail = "config <symbol>";
item.documentation = "This defines a config symbol <symbol>.";
break;
case 2:
item.detail = "menu <symbol>";
item.documentation =
"This defines a menu block <symbol>. Should end with 'endmenu'";
break;
case 21:
item.detail = "menuconfig <symbol>";
item.documentation =
"Define a config entry <symbol> with frontend hint to separate suboptions.";
break;
case 24:
item.detail = "choice <symbol>";
item.documentation = `This defines a choice group <symbol> accepting config or menuconfig as options.
Should end with 'endchoice'`;
break;
case 22:
item.detail = "comment <prompt>";
item.documentation =
"This defines a comment displayed to the user during configuration process.";
break;
case 13:
item.detail = "if <expression>";
item.documentation =
"This defines an if block. Should end with 'endif'";
break;
case 23:
item.detail = "source <prompt>";
item.documentation =
"This reads the specified configuration file. This file is always parsed.";
break;
case 26:
item.detail = "mainmenu <prompt>";
item.documentation =
"This sets the config program's title bar if the config program chooses to use it.";
break;
default:
break;
}
return item;
}
);
// Text document manager listens to connection for open change and close events
// of Kconfig document events
documents.listen(connection);
connection.listen(); | the_stack |
if (typeof window === 'undefined') {
throw new Error(`You really shouldnt be importing ${__filename} outsite of the app`)
}
import {
WorkerDiscovery, BitcoreBlockchain, AccountLoadStatus,
UtxoInfo as BaseUtxoInfo, AccountInfo as BaseAccountInfo,
} from 'hd-wallet'
import { TransactionBuilder } from 'bitcoinjs-lib'
import { pick, omit } from 'lodash'
import b58 from 'bs58check'
import bchaddr from 'bchaddrjs'
// @ts-ignore
import xpubWasmFile from 'hd-wallet/lib/fastxpub/fastxpub.wasm?file'
// @ts-ignore
import XpubWorker from 'hd-wallet/lib/fastxpub/fastxpub?worker'
// @ts-ignore
import SocketWorker from 'hd-wallet/lib/socketio-worker/inside?worker'
// @ts-ignore
import DiscoveryWorker from 'hd-wallet/lib/discovery/worker/inside?worker'
import log from 'Utilities/log'
import {
estimateTxFee, getPaymentTypeForHdKey, convertHdKeyAddressEncoding, isSegwitSupported,
} from 'Utilities/bitcoin'
import networks, { NetworkConfig } from 'Utilities/networks'
import { FeeRate } from 'Types'
// setting up workers
const xpubWasmFilePromise = fetch(xpubWasmFile)
.then((response) => response.ok ? response.arrayBuffer() : Promise.reject('failed to load fastxpub.wasm'))
const socketWorkerFactory = () => new SocketWorker()
const discoveryWorkerFactory = () => new DiscoveryWorker()
export type UtxoInfo = BaseUtxoInfo & {
confirmations: number,
}
export type AccountInfo = BaseAccountInfo & {
utxos: UtxoInfo[],
}
export type TxOutput = {
address: string,
amount: number,
}
export type PaymentTx = {
inputUtxos: UtxoInfo[]
outputs: TxOutput[]
outputScript: string,
fee: number,
change: number,
changePath: number[],
changeAddress: string,
isSegwit: boolean,
}
/**
* Sort the utxos for input selection
*/
function sortUtxos(utxoList: UtxoInfo[]): UtxoInfo[] {
const matureList: UtxoInfo[] = []
const immatureList: UtxoInfo[] = []
utxoList.forEach((utxo) => {
if (utxo.confirmations >= 6) {
matureList.push(utxo)
} else {
immatureList.push(utxo)
}
})
matureList.sort((a, b) => a.value - b.value) // Ascending order by value
immatureList.sort((a, b) => b.confirmations - a.confirmations) // Descending order by confirmations
return matureList.concat(immatureList)
}
export class Bitcore extends BitcoreBlockchain {
assetSymbol: string
network: NetworkConfig
discovery: WorkerDiscovery
constructor(config: NetworkConfig) {
super(config.bitcoreUrls, socketWorkerFactory)
this.assetSymbol = config.symbol
this.network = config
this.discovery = new WorkerDiscovery(discoveryWorkerFactory, new XpubWorker(), xpubWasmFilePromise, this)
}
toJSON() {
return Object.assign({}, this, {
discovery: omit(this.discovery, 'chain'), // Avoid circular reference
})
}
/**
* Discover the balance, transactions, unused addresses, etc of an extended public key.
*
* @param hdKey - The extended public key to discover
* @param [onUpdate] - Callback for partial updates to discover result
* @returns Account info promise
*/
discoverAccount(hdKey: string, onUpdate?: (status: AccountLoadStatus) => void): Promise<AccountInfo> {
return Promise.resolve()
.then(() => {
const paymentType = getPaymentTypeForHdKey(hdKey, this.network)
const { addressEncoding } = paymentType
if (!(['P2PKH', 'P2SH-P2WPKH']).includes(addressEncoding)) {
throw new Error(`discoverAccount does not support ${addressEncoding} addressEncoding`)
}
/*
* I noticed that while discovering a bitcoin and litecoin account simultaneously, the call to deriveXpub
* used by discoverAccount returned the same result for both calls resulting in one of them throwing an
* "Invalid network version" error as the invalid key was passed into HDNode.fromBase58.
* From this is was able to determine that the xpub derivation library used by discoverAccount is
* stateful in some way and doesn't support simultaneous derivations with different bip32 versions.
* I was able to work around this issue by always passing in a new XpubWorker when creating WorkerDiscovery
* but this only helped with collisions between currencies. I believe the issue is still present if you were
* to try deriving an bitcoin xpub and ypub simultaneously because they use different bip32 versions.
* To work around this we can convert all hd keys into their xpub or P2PKH format so that the bip32
* versions used are the same for all accounts of a specific currency.
*/
const segwit: 'off' | 'p2sh' = addressEncoding === 'P2SH-P2WPKH' ? 'p2sh' : 'off'
const xpub = addressEncoding === 'P2PKH' ? hdKey : convertHdKeyAddressEncoding(hdKey, 'P2PKH', this.network)
const cashAddress = false // To maintain compatability with bitcoinjs-lib don't use bchaddr format
const process = this.discovery.discoverAccount(null, xpub, this.network.bitcoinJsNetwork, segwit, cashAddress)
if (onUpdate) {
process.stream.values.attach(onUpdate)
}
return process.ending
.then((result: BaseAccountInfo) => ({
...result,
utxos: result.utxos.map((utxo: BaseUtxoInfo) => ({
...utxo,
confirmations: utxo.height ? result.lastBlock.height - utxo.height : 0,
})),
}))
.catch((e: Error) => {
log.error(`${this.network.symbol} discoverAccount error for ${paymentType.bip32.publicPrefix} key`, e)
throw e
})
})
}
/**
* Build a simple payment transaction.
* Note: fee will be subtracted from first output when attempting to send entire account balance
*
* @param {Object} account - The result of calling discoverAccount
* @param {Number} account.changeIndex - The index of the next unused changeAddress
* @param {String[]} account.changeAddresses - An array of all change addresses
* @param {Object[]} account.utxos - The unspent transaction outputs for the account
* @param {Number} account.utxos[].value - The value of the utxo (unit: satoshi)
* @param {Number} account.utxos[].confirmations - The confirmations of the utxo
* @param {String} account.utxos[].transactionHash - The hash of the transaction this utxo is in
* @param {Number} account.utxos[].index - The index of this utxo in the transaction
* @param {Number[]} account.utxos[].addressPath - The bip44 address path of the utxo
* @param {Object[]} desiredOutputs - Outputs for the transaction (excluding change)
* @param {String} desiredOutputs[].address - address to send to
* @param {Number} desiredOutputs[].amount - amount to send (unit: satoshi)
* @param {FeeRate|Number} feeRate - desired fee (unit: satoshi per byte)
* @param {Boolean} [isSegwit=true] - True if this is a segwit transaction
* @param {Number} [dustThreshold=546] - A change output will only be included when greater than this value.
* Otherwise it will be included as a fee instead (unit: satoshi)
* @returns {Object}
*/
buildPaymentTx(
account: AccountInfo,
desiredOutputs: Array<{ address: string, amount: number}>,
feeRate: FeeRate | number,
isSegwit = true,
dustThreshold?: number,
): PaymentTx {
const { utxos, changeIndex, changeAddresses } = account
let changeAddress = changeAddresses[changeIndex]
const sortedUtxos = sortUtxos(utxos)
if (isSegwit && !isSegwitSupported(this.network)) {
throw new Error(`Segwit not supported for ${this.network.symbol}`)
}
if (typeof dustThreshold === 'undefined') {
dustThreshold = typeof this.network.dustThreshold !== 'undefined'
? this.network.dustThreshold
: 546
}
const outputs = desiredOutputs
.map(({ address, amount }, i) => {
// validate
if (typeof address !== 'string') {
throw new Error(`Invalid address ${address} provided for output ${i}`)
}
if (typeof amount !== 'number') {
throw new Error(`Invalid amount ${amount} provided for output ${i}`)
}
if (this.network.symbol === 'BCH') {
// Convert to legacy for compatability with bitcoinjs-lib
address = bchaddr.toLegacyAddress(address)
}
// return copy
return { address, amount }
})
const outputCount = outputs.length + 1 // Plus one for change output
let outputTotal = outputs.reduce((total, { amount }) => total + amount, 0)
/* Select inputs and calculate appropriate fee */
const minTxFee = this.network.minTxFee
let fee = 0 // Total fee is recalculated when adding each input
let amountWithFee = outputTotal + fee
const inputUtxos = []
let inputTotal = 0
for (const utxo of sortedUtxos) {
fee = estimateTxFee(feeRate, inputUtxos.length + 1, outputCount, isSegwit)
// Ensure calculated fee is above network minimum
if (minTxFee) {
const minTxFeeSat = estimateTxFee(minTxFee, inputUtxos.length, outputCount, isSegwit)
if (fee < minTxFeeSat) {
fee = minTxFeeSat
}
}
amountWithFee = outputTotal + fee
inputTotal = inputTotal + utxo.value
inputUtxos.push(utxo)
if (inputTotal >= amountWithFee) {
break
}
}
if (amountWithFee > inputTotal) {
const amountWithSymbol = `${outputTotal * 1e-8} ${this.assetSymbol}`
if (outputTotal === inputTotal) {
log.debug(`Attempting to send entire ${amountWithSymbol} balance. ` +
`Subtracting fee of ${fee} sat from first output.`)
amountWithFee = outputTotal
outputs[0].amount -= fee
outputTotal -= fee
if (outputs[0].amount <= dustThreshold) {
throw new Error('First output minus fee is below dust threshold')
}
} else {
throw new Error(`You do not have enough UTXOs to send ${amountWithSymbol} with ${feeRate} sat/byte fee`)
}
}
/* Build outputs */
log.debug(`Creating ${this.assetSymbol} tx with outputs`, outputs)
const outputBuilder = new TransactionBuilder(this.network.bitcoinJsNetwork)
outputs.forEach(({ amount, address }) => outputBuilder.addOutput(address, amount))
let change = inputTotal - amountWithFee
let changePath = [1, changeIndex]
if (change > dustThreshold) { // Avoid creating dust outputs
outputBuilder.addOutput(changeAddress, change)
} else {
log.debug(`Change of ${change} sat is below dustThreshold of ${dustThreshold}, adding to fee`)
fee += change
change = 0
changeAddress = null
changePath = null
}
const outputScript = outputBuilder.buildIncomplete().toHex().slice(10, -8) // required by ledgerjs api
return {
inputUtxos,
outputs,
outputScript,
fee,
change,
changePath,
changeAddress,
isSegwit,
}
}
}
const bitcoreInstances: { [symbol: string]: Bitcore } = {}
/** Get the Bitcore service for the specified asset */
export function getBitcore(assetSymbol: string): Bitcore {
const bitcore = bitcoreInstances[assetSymbol]
if (bitcore) {
return bitcore
}
const networkConfig = networks[assetSymbol]
if (networkConfig) {
log.debug('Creating new Bitcore for network', networkConfig)
return (bitcoreInstances[assetSymbol] = new Bitcore(networkConfig))
}
throw new Error(`Bitcore not configured for asset ${assetSymbol}`)
}
export default {
getBitcore,
Bitcore,
} | the_stack |
import { RemoteRendering } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { RemoteRenderingRestClientContext } from "../remoteRenderingRestClientContext";
import {
CreateConversionSettings,
RemoteRenderingCreateConversionOptionalParams,
RemoteRenderingCreateConversionResponse,
RemoteRenderingGetConversionOptionalParams,
RemoteRenderingGetConversionResponse,
RemoteRenderingListConversionsOptionalParams,
RemoteRenderingListConversionsResponse,
RenderingSessionSettings,
RemoteRenderingCreateSessionOptionalParams,
RemoteRenderingCreateSessionResponse,
RemoteRenderingGetSessionOptionalParams,
RemoteRenderingGetSessionResponse,
UpdateSessionSettings,
RemoteRenderingUpdateSessionOptionalParams,
RemoteRenderingUpdateSessionResponse,
RemoteRenderingStopSessionOptionalParams,
RemoteRenderingStopSessionResponse,
RemoteRenderingListSessionsOptionalParams,
RemoteRenderingListSessionsResponse,
RemoteRenderingListConversionsNextOptionalParams,
RemoteRenderingListConversionsNextResponse,
RemoteRenderingListSessionsNextOptionalParams,
RemoteRenderingListSessionsNextResponse
} from "../models";
/** Class representing a RemoteRendering. */
export class RemoteRenderingImpl implements RemoteRendering {
private readonly client: RemoteRenderingRestClientContext;
/**
* Initialize a new instance of the class RemoteRendering class.
* @param client Reference to the service client
*/
constructor(client: RemoteRenderingRestClientContext) {
this.client = client;
}
/**
* Creates a conversion using an asset stored in an Azure Blob Storage account.
* @param accountId The Azure Remote Rendering account ID.
* @param conversionId An ID uniquely identifying the conversion for the given account. The ID is case
* sensitive, can contain any combination of alphanumeric characters including hyphens and underscores,
* and cannot contain more than 256 characters.
* @param body Request body configuring the settings for an asset conversion.
* @param options The options parameters.
*/
createConversion(
accountId: string,
conversionId: string,
body: CreateConversionSettings,
options?: RemoteRenderingCreateConversionOptionalParams
): Promise<RemoteRenderingCreateConversionResponse> {
return this.client.sendOperationRequest(
{ accountId, conversionId, body, options },
createConversionOperationSpec
);
}
/**
* Gets the status of a particular conversion.
* @param accountId The Azure Remote Rendering account ID.
* @param conversionId An ID uniquely identifying the conversion for the given account. The ID is case
* sensitive, can contain any combination of alphanumeric characters including hyphens and underscores,
* and cannot contain more than 256 characters.
* @param options The options parameters.
*/
getConversion(
accountId: string,
conversionId: string,
options?: RemoteRenderingGetConversionOptionalParams
): Promise<RemoteRenderingGetConversionResponse> {
return this.client.sendOperationRequest(
{ accountId, conversionId, options },
getConversionOperationSpec
);
}
/**
* Gets a list of all conversions.
* @param accountId The Azure Remote Rendering account ID.
* @param options The options parameters.
*/
listConversions(
accountId: string,
options?: RemoteRenderingListConversionsOptionalParams
): Promise<RemoteRenderingListConversionsResponse> {
return this.client.sendOperationRequest(
{ accountId, options },
listConversionsOperationSpec
);
}
/**
* Creates a new rendering session.
* @param accountId The Azure Remote Rendering account ID.
* @param sessionId An ID uniquely identifying the rendering session for the given account. The ID is
* case sensitive, can contain any combination of alphanumeric characters including hyphens and
* underscores, and cannot contain more than 256 characters.
* @param body Settings of the session to be created.
* @param options The options parameters.
*/
createSession(
accountId: string,
sessionId: string,
body: RenderingSessionSettings,
options?: RemoteRenderingCreateSessionOptionalParams
): Promise<RemoteRenderingCreateSessionResponse> {
return this.client.sendOperationRequest(
{ accountId, sessionId, body, options },
createSessionOperationSpec
);
}
/**
* Gets the properties of a particular rendering session.
* @param accountId The Azure Remote Rendering account ID.
* @param sessionId An ID uniquely identifying the rendering session for the given account. The ID is
* case sensitive, can contain any combination of alphanumeric characters including hyphens and
* underscores, and cannot contain more than 256 characters.
* @param options The options parameters.
*/
getSession(
accountId: string,
sessionId: string,
options?: RemoteRenderingGetSessionOptionalParams
): Promise<RemoteRenderingGetSessionResponse> {
return this.client.sendOperationRequest(
{ accountId, sessionId, options },
getSessionOperationSpec
);
}
/**
* Updates the max lease time of a particular rendering session.
* @param accountId The Azure Remote Rendering account ID.
* @param sessionId An ID uniquely identifying the rendering session for the given account. The ID is
* case sensitive, can contain any combination of alphanumeric characters including hyphens and
* underscores, and cannot contain more than 256 characters.
* @param body Settings used to update the session.
* @param options The options parameters.
*/
updateSession(
accountId: string,
sessionId: string,
body: UpdateSessionSettings,
options?: RemoteRenderingUpdateSessionOptionalParams
): Promise<RemoteRenderingUpdateSessionResponse> {
return this.client.sendOperationRequest(
{ accountId, sessionId, body, options },
updateSessionOperationSpec
);
}
/**
* Stops a particular rendering session.
* @param accountId The Azure Remote Rendering account ID.
* @param sessionId An ID uniquely identifying the rendering session for the given account. The ID is
* case sensitive, can contain any combination of alphanumeric characters including hyphens and
* underscores, and cannot contain more than 256 characters.
* @param options The options parameters.
*/
stopSession(
accountId: string,
sessionId: string,
options?: RemoteRenderingStopSessionOptionalParams
): Promise<RemoteRenderingStopSessionResponse> {
return this.client.sendOperationRequest(
{ accountId, sessionId, options },
stopSessionOperationSpec
);
}
/**
* Gets a list of all rendering sessions.
* @param accountId The Azure Remote Rendering account ID.
* @param options The options parameters.
*/
listSessions(
accountId: string,
options?: RemoteRenderingListSessionsOptionalParams
): Promise<RemoteRenderingListSessionsResponse> {
return this.client.sendOperationRequest(
{ accountId, options },
listSessionsOperationSpec
);
}
/**
* ListConversionsNext
* @param accountId The Azure Remote Rendering account ID.
* @param nextLink The nextLink from the previous successful call to the ListConversions method.
* @param options The options parameters.
*/
listConversionsNext(
accountId: string,
nextLink: string,
options?: RemoteRenderingListConversionsNextOptionalParams
): Promise<RemoteRenderingListConversionsNextResponse> {
return this.client.sendOperationRequest(
{ accountId, nextLink, options },
listConversionsNextOperationSpec
);
}
/**
* ListSessionsNext
* @param accountId The Azure Remote Rendering account ID.
* @param nextLink The nextLink from the previous successful call to the ListSessions method.
* @param options The options parameters.
*/
listSessionsNext(
accountId: string,
nextLink: string,
options?: RemoteRenderingListSessionsNextOptionalParams
): Promise<RemoteRenderingListSessionsNextResponse> {
return this.client.sendOperationRequest(
{ accountId, nextLink, options },
listSessionsNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const createConversionOperationSpec: coreClient.OperationSpec = {
path: "/accounts/{account_id}/conversions/{conversion_id}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Conversion,
headersMapper: Mappers.RemoteRenderingCreateConversionHeaders
},
201: {
bodyMapper: Mappers.Conversion,
headersMapper: Mappers.RemoteRenderingCreateConversionHeaders
},
400: {
bodyMapper: Mappers.ErrorResponse,
headersMapper: Mappers.RemoteRenderingCreateConversionExceptionHeaders,
isError: true
},
401: {
headersMapper: Mappers.RemoteRenderingCreateConversionExceptionHeaders,
isError: true
},
403: {
headersMapper: Mappers.RemoteRenderingCreateConversionExceptionHeaders,
isError: true
},
409: {
bodyMapper: Mappers.ErrorResponse,
headersMapper: Mappers.RemoteRenderingCreateConversionExceptionHeaders,
isError: true
},
429: {
headersMapper: Mappers.RemoteRenderingCreateConversionExceptionHeaders,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
isError: true
}
},
requestBody: Parameters.body,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.endpoint,
Parameters.accountId,
Parameters.conversionId
],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const getConversionOperationSpec: coreClient.OperationSpec = {
path: "/accounts/{account_id}/conversions/{conversion_id}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.Conversion,
headersMapper: Mappers.RemoteRenderingGetConversionHeaders
},
401: {
headersMapper: Mappers.RemoteRenderingGetConversionExceptionHeaders,
isError: true
},
403: {
headersMapper: Mappers.RemoteRenderingGetConversionExceptionHeaders,
isError: true
},
404: {
headersMapper: Mappers.RemoteRenderingGetConversionExceptionHeaders,
isError: true
},
429: {
headersMapper: Mappers.RemoteRenderingGetConversionExceptionHeaders,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
headersMapper: Mappers.RemoteRenderingGetConversionExceptionHeaders,
isError: true
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.endpoint,
Parameters.accountId,
Parameters.conversionId
],
headerParameters: [Parameters.accept],
serializer
};
const listConversionsOperationSpec: coreClient.OperationSpec = {
path: "/accounts/{account_id}/conversions",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ConversionList,
headersMapper: Mappers.RemoteRenderingListConversionsHeaders
},
401: {
headersMapper: Mappers.RemoteRenderingListConversionsExceptionHeaders,
isError: true
},
403: {
headersMapper: Mappers.RemoteRenderingListConversionsExceptionHeaders,
isError: true
},
429: {
headersMapper: Mappers.RemoteRenderingListConversionsExceptionHeaders,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
headersMapper: Mappers.RemoteRenderingListConversionsExceptionHeaders,
isError: true
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.endpoint, Parameters.accountId],
headerParameters: [Parameters.accept],
serializer
};
const createSessionOperationSpec: coreClient.OperationSpec = {
path: "/accounts/{account_id}/sessions/{session_id}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.SessionProperties
},
201: {
bodyMapper: Mappers.SessionProperties,
headersMapper: Mappers.RemoteRenderingCreateSessionHeaders
},
400: {
bodyMapper: Mappers.ErrorResponse,
headersMapper: Mappers.RemoteRenderingCreateSessionExceptionHeaders,
isError: true
},
401: {
headersMapper: Mappers.RemoteRenderingCreateSessionExceptionHeaders,
isError: true
},
403: {
headersMapper: Mappers.RemoteRenderingCreateSessionExceptionHeaders,
isError: true
},
409: {
bodyMapper: Mappers.ErrorResponse,
isError: true
},
429: {
headersMapper: Mappers.RemoteRenderingCreateSessionExceptionHeaders,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
headersMapper: Mappers.RemoteRenderingCreateSessionExceptionHeaders,
isError: true
}
},
requestBody: Parameters.body1,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.endpoint,
Parameters.accountId,
Parameters.sessionId
],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const getSessionOperationSpec: coreClient.OperationSpec = {
path: "/accounts/{account_id}/sessions/{session_id}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SessionProperties
},
401: {
headersMapper: Mappers.RemoteRenderingGetSessionExceptionHeaders,
isError: true
},
403: {
headersMapper: Mappers.RemoteRenderingGetSessionExceptionHeaders,
isError: true
},
404: {
headersMapper: Mappers.RemoteRenderingGetSessionExceptionHeaders,
isError: true
},
429: {
headersMapper: Mappers.RemoteRenderingGetSessionExceptionHeaders,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
headersMapper: Mappers.RemoteRenderingGetSessionExceptionHeaders,
isError: true
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.endpoint,
Parameters.accountId,
Parameters.sessionId
],
headerParameters: [Parameters.accept],
serializer
};
const updateSessionOperationSpec: coreClient.OperationSpec = {
path: "/accounts/{account_id}/sessions/{session_id}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.SessionProperties
},
401: {
headersMapper: Mappers.RemoteRenderingUpdateSessionExceptionHeaders,
isError: true
},
403: {
headersMapper: Mappers.RemoteRenderingUpdateSessionExceptionHeaders,
isError: true
},
404: {
headersMapper: Mappers.RemoteRenderingUpdateSessionExceptionHeaders,
isError: true
},
422: {
bodyMapper: Mappers.ErrorResponse,
headersMapper: Mappers.RemoteRenderingUpdateSessionExceptionHeaders,
isError: true
},
429: {
headersMapper: Mappers.RemoteRenderingUpdateSessionExceptionHeaders,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
headersMapper: Mappers.RemoteRenderingUpdateSessionExceptionHeaders,
isError: true
}
},
requestBody: Parameters.body2,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.endpoint,
Parameters.accountId,
Parameters.sessionId
],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const stopSessionOperationSpec: coreClient.OperationSpec = {
path: "/accounts/{account_id}/sessions/{session_id}/:stop",
httpMethod: "POST",
responses: {
204: {
headersMapper: Mappers.RemoteRenderingStopSessionHeaders
},
401: {
headersMapper: Mappers.RemoteRenderingStopSessionExceptionHeaders,
isError: true
},
403: {
headersMapper: Mappers.RemoteRenderingStopSessionExceptionHeaders,
isError: true
},
404: {
headersMapper: Mappers.RemoteRenderingStopSessionExceptionHeaders,
isError: true
},
429: {
headersMapper: Mappers.RemoteRenderingStopSessionExceptionHeaders,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
headersMapper: Mappers.RemoteRenderingStopSessionExceptionHeaders,
isError: true
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.endpoint,
Parameters.accountId,
Parameters.sessionId
],
headerParameters: [Parameters.accept],
serializer
};
const listSessionsOperationSpec: coreClient.OperationSpec = {
path: "/accounts/{account_id}/sessions",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SessionsList
},
401: {
headersMapper: Mappers.RemoteRenderingListSessionsExceptionHeaders,
isError: true
},
403: {
headersMapper: Mappers.RemoteRenderingListSessionsExceptionHeaders,
isError: true
},
429: {
headersMapper: Mappers.RemoteRenderingListSessionsExceptionHeaders,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
headersMapper: Mappers.RemoteRenderingListSessionsExceptionHeaders,
isError: true
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.endpoint, Parameters.accountId],
headerParameters: [Parameters.accept],
serializer
};
const listConversionsNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ConversionList,
headersMapper: Mappers.RemoteRenderingListConversionsNextHeaders
},
401: {
headersMapper: Mappers.RemoteRenderingListConversionsNextExceptionHeaders,
isError: true
},
403: {
headersMapper: Mappers.RemoteRenderingListConversionsNextExceptionHeaders,
isError: true
},
429: {
headersMapper: Mappers.RemoteRenderingListConversionsNextExceptionHeaders,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
headersMapper: Mappers.RemoteRenderingListConversionsNextExceptionHeaders,
isError: true
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.endpoint,
Parameters.accountId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listSessionsNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SessionsList
},
401: {
headersMapper: Mappers.RemoteRenderingListSessionsNextExceptionHeaders,
isError: true
},
403: {
headersMapper: Mappers.RemoteRenderingListSessionsNextExceptionHeaders,
isError: true
},
429: {
headersMapper: Mappers.RemoteRenderingListSessionsNextExceptionHeaders,
isError: true
},
500: {
bodyMapper: Mappers.ErrorResponse,
headersMapper: Mappers.RemoteRenderingListSessionsNextExceptionHeaders,
isError: true
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.endpoint,
Parameters.accountId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
declare module '@schema-plugin-flow/sifo-model' {
interface CommonUtils {
hasOwnProperty: (obj: object, propName: any) => boolean;
keyHolder: (key: any, defValue: any) => any;
loop: (node: SchemaNode, target: string, loopFunc: DefaultFunc, nodeMap?: DynamicObject | undefined) => void;
objectReadOnly: (obj: object) => object;
deepClone(obj: any): any;
}
/**
* schema tree
*/
class SchemaTree {
nodeMap: {
[id: string]: SchemaNode | null;
};
parsedTree: SchemaNode | null;
initialTree: SchemaNode | null;
constructor(initialTree: SchemaNode);
loopUp: (loopFunc: DefaultFunc, id: string) => void;
loopDown: (loopFunc: DefaultFunc, id: string) => void;
}
class EventStatus {
_status: string;
constructor(status: string);
getStatus(): string;
setStatus(status: string): void;
}
interface EventKeyType {
id: string;
eventKey: string;
toString: () => string; // id
valueOf: () => string; // id
}
class EventEmitter {
mApi: ModelApi;
schemaInstance: SchemaTree;
eventHandler: {
[id: string]: {
[eventName: string]: SifoEventListener[] | null;
};
};
updatedStates: DynamicObject;
eventStatus: EventStatus;
constructor(mApi: ModelApi, schemaInstance: SchemaTree);
private eventStart: () => {
getOldAttributes: (id: string) => any;
};
private eventEnd: () => void;
/**
* 插件链中需要对接口进行干预,在插件链前创建保存中间状态,在插件链结束时才真正执行
*/
private mApiWrap(): void;
addEventListener(id: string | EventKeyType, eventName: string, handler: SifoEventListener): void;
/**
* 检查是否有handler
* @param {*} id
* @param {*} eventName
*/
hasHandler(id: string | EventKeyType, eventName: string): boolean;
removeEventListener(id: string | EventKeyType, eventName: string, handler: SifoEventListener): void;
}
interface SchemaUtils {
/**
* 节点修正
* @param {*} schema
* @param {*} dealRules
* @param {*} alias
*/
nodeRevise(schema: SchemaNode, dealRules?: {}, alias?: DynamicObject): SchemaNode;
}
/**
* SifoModel 插件管理模型
*/
class SifoModel {
[key: string]: any;
/**
*
* @param namespace 命名空间
* @param refreshApi 刷新执行接口,如有传callback参数,应在刷新完成后回调
* @param schema schema
* @param plugins 插件
* @param modelOptions 可选参数
*/
constructor(namespace: string, refreshApi: DefaultFunc, schema: SchemaNode, plugins: SifoModel['plugins'], modelOptions?: ModelOptions);
/**
* 开始运行
*/
public run: () => void;
public destroy: () => void;
}
/**
* 事件上下文 context 的 event 参数
*/
export interface SifoEvent {
/**
* 获取事件执行前指定id的属性
*/
getOldAttributes: (id: string) => DynamicObject;
/**
* 获取事件执行到当前时,所有更新过的属性
*/
getUpdatedStates: () => DynamicObject;
/**
* 事件对象的key,一般是相应schema的节点id
*/
key: string;
eventName: string;
/**
* 阻止后续插件的执行
*/
stop: () => void;
/**
* 可修改对后续插件的入参(不包含context),无修改时不需调用
*/
next: (...nArg: any[]) => void;
/**
* 有的事件有返回值
*/
eventReturnValue?: any;
/**
* 对返回值进行clone
*/
cloneReturnValue?: boolean;
}
/**
* 事件上下文(第一位)参数
*/
export interface SifoEventArgs {
mApi: ModelApi;
event: SifoEvent;
}
/**
* 事件监听handler
*/
export type SifoEventListener = (context: SifoEventArgs, ...args: any[]) => any;
interface EventStatus {
getStatus: () => string;
setStatus: (status: string) => void;
}
interface EmitterArgs {
key: string,
eventName: string,
mApi: ModelApi;
getHandlers: () => SifoEventListener[];
eventStart: DefaultFunc;
eventEnd: DefaultFunc;
eventStatus: EventStatus;
}
type DispatchPayload = any;
interface DispatchWatchArgs {
[watchKey: string]: DispatchPayload[];
}
interface PluginKeyMap {
[key: string]: string;
modelPlugins: string;
pagePlugins: string;
componentPlugins: string;
}
export interface DynamicObject {
[key: string]: any;
}
interface ShadowBox {
shadow: DynamicObject;
entity: DynamicObject;
shadowMagic: (exception?: string[]) => void;
}
interface Controller {
reloadPage: ModelApi['reloadPage'];
}
/**
* 模型接口
*/
export interface ModelApi {
[key: string]: any;
/**
* 命名空间
*/
namespace?: string;
/**
* 模型实例Id
*/
instanceId: string;
/**
* 获取externals数据
*/
getExternals: () => any;
/**
* 获取存储在key值下的数据对象,globalData是一个公共数据容器
*/
getGlobalData: (key?: string) => any;
/**
* 存储一个指定key的数据对象
*/
setGlobalData: (key: string, value: any) => void;
/**
* 获取对应id的属性
*/
getAttributes: (id: string) => DynamicObject | undefined;
/**
* 设置指定id节点的 attributes ,refreshImmediately 表示是否立即刷新,默认为true, 批量设置属性时建议传入false,在设置完后调用refresh接口批量刷新
*/
setAttributes: (id: string, attributes: DynamicObject, refreshImmediately?: boolean) => any;
/**
* 更换schema上标识的渲染组件名
*/
replaceComponent: (id: string, componentName: string) => void;
/**
* 获取指定id的渲染组件名
*/
getComponentName: (id: string) => string | undefined;
/**
* 按指定条件查询 schema 节点 id 列表
* @param selector 格式如:"component==Input"、"attributes.rules.required==true"、node => (node.component == 'Input')
* @param direction 遍历方向,默认 loopDown
* @param startId 遍历的起始节点 id,loopDown 时默认从根节点开始
*/
queryNodeIds: (selector: string | Function, direction?: 'loopDown' | 'loopUp', startId?: string) => string[];
/**
* 组件注册监听事件
*/
addEventListener: (id: string, eventName: string, handler: SifoEventListener, prepose?: boolean) => void;
/**
* 组件注销监听事件
*/
removeEventListener: (id: string, eventName: string, handler: SifoEventListener, prepose?: boolean) => void;
/**
* 对指定组件事件是否有进行监听
*/
hasEventListener: (id: string, eventName: string) => boolean;
/**
* 注册观测事件,一般用于观测指定id节点(key参数)的属性变化,也可用于自定义观测
*/
watch: (key: string, handler: SifoEventListener) => void;
/**
* 注销观测
*/
removeWatch: (key: string, handler: SifoEventListener) => void;
/**
* 分发观测事件,只允许对自定义观测进行分发,节点属性变化由setAttributes分发
*/
dispatchWatch: (key: string, ...payloads: DispatchPayload[]) => void;
/**
* 重新加载页面,reloadPage将重跑所有生命周期。仅在afterRender后生效。
*/
reloadPage: (params: ReloadPageParams) => void;
/**
* 强制刷新页面,一般是在批量更新了节点属性后调用
*/
refresh: () => any;
/**
* 获取初始schema
*/
getInitialSchema: () => SchemaNode;
/**
* 获取渲染时schema
*/
getSchema: () => SchemaNode | null;
/**
* 获取渲染时components
*/
getComponents: () => DynamicObject | undefined;
}
export interface PluginEventArgs {
mApi: ModelApi;
event: DynamicObject;
}
/**
* mApi中间件,next是后续方法,isEnd表明当前方法是否是最后一个
*/
export type ModelApiMiddleware = (next: DefaultFunc, isEnd: boolean) => DefaultFunc;
/**
* 插件生命周期方法handler
*/
export type PluginHandler = (args: PluginEventArgs) => void;
/**
* schema实例化前的插件生命周期方法handler
*/
export type PrePluginHandler = (args: object, info?: ModelInformation) => any;
type AnyPluginHandler = PluginHandler | PrePluginHandler;
/**
* 组件插件项
*/
export interface ComponentPluginItem {
// [handlerName: string]: PluginHandler;
/**
* 组件初始化
*/
onComponentInitial?: PluginHandler; // 8
/**
* 页面渲染后, 这时组件一般(不能保证)已经渲染
*/
afterPageRender?: PluginHandler; // 14
}
/**
* 组件插件集
*/
export interface ComponentPluginSet {
[componentId: string]: ComponentPluginItem;
}
/**
* 页面插件
*/
export interface PagePlugin {
// [handlerName: string]: AnyPluginHandler | undefined;
/**
* 对节点动态修改
*/
onNodePreprocess?: PrePluginHandler; // 2 对节点有动态修改
/**
* 页面初始化
*/
onPageInitial?: PluginHandler; // 7
/**
* 渲染前
*/
beforeRender?: PluginHandler; // 9
/**
* 渲染后
*/
afterRender?: PluginHandler; // 13
/**
* 销毁
*/
onDestroy?: PluginHandler; // 16
}
/**
* 模型插件
*/
export interface ModelPlugin {
ID: string;
// [handlerName: string]: AnyPluginHandler | undefined;
// onModelInitial: 'onModelInitial',//1 注:class类型,直接new class
/**
* 对schema预处理
*/
onNodePreprocess?: PrePluginHandler; // 3 schema预处理
/**
* 组件包装
*/
onComponentsWrap?: PrePluginHandler; // 4
/**
* schema实例化
*/
onSchemaInstantiated?: PluginHandler; // 5 schema实例化
/**
* 模型接口创建,仅在此周期内能够修改mApi接口
*/
onModelApiCreated?: PluginHandler; // 6 模型接口创建
/**
* 即将进行渲染
*/
onReadyToRender?: PluginHandler; // 10 即将进行渲染
/**
* 渲染后
*/
afterRender?: PluginHandler; // 12
/**
* 销毁
*/
onDestroy?: PluginHandler; // 17
}
/**
* 模型实例化可选参数
*/
export interface ModelOptions {
/**
* 模型接口mApi外传方法
*/
modelApiRef?: (mApi: ModelApi | null) => void;
/**
* 任意外部信息
*/
externals?: object;
/**
* 组件
*/
components?: object;
/**
* 获取模型插件实例化时的构造函数参数
* @param modelPluginId 模型插件的ID
*/
getModelPluginArgs?: (modelPluginId: string, info: ModelInformation) => any;
}
/**
* 可提供参数的模型插件
*/
interface ModelPluginProvider {
/**
* 返回模型插件的实例构造参数: (info) => { return [arg1, arg2]; }
*/
argsProvider?: (modelPluginId: string, info: ModelInformation) => any;
plugin: ModelPlugin;
}
/**
* SifoModel插件参数
*/
export interface SifoPlugin {
//[key: string]: ModelPlugin | PagePlugin | ComponentPluginSet | undefined;
/**
* 模型插件
*/
modelPlugin?: ModelPlugin | ModelPluginProvider;
/**
* 页面插件
*/
pagePlugin?: PagePlugin;
/**
* 组件插件
*/
componentPlugin?: ComponentPluginSet;
}
export interface ModelInformation {
instanceId: string;
namespace?: string;
externals?: ModelOptions['externals'];
}
export type DefaultFunc = (args?: any) => any;
/**
* 重新加载页面的参数
*/
export interface ReloadPageParams {
/**
* 任意外部信息
*/
externals?: ModelOptions['externals'];
schema?: SchemaNode;
/**
* 插件
*/
plugins?: SifoPlugin[];
/**
* 组件
*/
components?: ModelOptions['components'];
/**
* 获取模型插件实例化时的构造函数参数
* @param modelPluginId 模型插件的ID
*/
getModelPluginArgs?: ModelOptions['getModelPluginArgs'];
}
/**
* schema node
*/
export interface SchemaNode {
[key: string]: any;
/**
* 节点唯一标识,不可重复,插件都是以此id进行节点区分
*/
id?: string;
component?: string;
attributes?: DynamicObject;
children?: SchemaNode[] | null;
}
export default SifoModel;
} | the_stack |
const enqueueJob = (function (): (callback: () => void) => void {
/* tslint:disable-next-line:variable-name */
const MutationObserver = global.MutationObserver || global.WebkitMutationObserver;
if (global.process !== undefined && typeof global.process.nextTick === "function") {
const nextTick = global.process.nextTick;
return (callback: () => void) => {
nextTick(callback);
};
}
else if (MutationObserver !== undefined) {
const pending: (() => void)[] = [];
let currentlyPending = false;
const div = document.createElement("div");
const observer = new MutationObserver(() => {
const processing = pending.splice(0, pending.length);
for (const callback of processing) {
callback();
}
currentlyPending = false;
if (pending.length > 0) {
div.classList.toggle("foo");
currentlyPending = true;
}
});
observer.observe(div, { attributes: true });
return (callback: () => void) => {
pending.push(callback);
if (!currentlyPending) {
div.classList.toggle("foo");
currentlyPending = true;
}
};
}
else {
return (callback: () => void) => setTimeout(callback, 0);
}
})();
/**
* Promise implementation for browsers that don't support it.
*
* @param {function(function(T|!Thenable.<T>), function(*))} executor
*/
class SimplePromise<T> {
/**
* @param {T|!Thenable.<T>} value
* @return {!Promise.<T>}
*/
static resolve<T>(value: T | Thenable<T>): Promise<T> {
if (value instanceof SimplePromise) {
return value;
}
return new Promise<T>(resolve => resolve(value));
}
/**
* @param {*} reason
* @return {!Promise.<T>}
*/
static reject<T>(reason: any): Promise<T> {
return new Promise<T>((/* ujs:unreferenced */ _resolve, reject) => reject(reason));
}
/**
* @param {!Array.<T|!Thenable.<T>>} values
* @return {!Promise.<!Array.<T>>}
*/
static all<T>(values: (T | Thenable<T>)[]): Promise<T[]> {
return new Promise<T[]>((resolve, reject) => {
const result: T[] = [];
let numUnresolved = values.length;
if (numUnresolved === 0) {
resolve(result);
return;
}
values.forEach((value, index) => Promise.resolve(value).then(value => {
result[index] = value;
numUnresolved--;
if (numUnresolved === 0) {
resolve(result);
}
}, reject));
});
}
/**
* @param {!Array.<T|!Thenable.<T>>} values
* @return {!Promise.<T>}
*/
static race<T>(values: (T | Thenable<T>)[]): Promise<T> {
return new Promise<T>((resolve, reject) => {
for (const value of values) {
/* tslint:disable-next-line:no-floating-promises */
Promise.resolve(value).then(resolve, reject);
}
});
}
private _state: SimplePromiseState<T> = { state: "pending" };
private _fulfillReactions: FulfilledPromiseReaction<T, any>[] = [];
private _rejectReactions: RejectedPromiseReaction<any>[] = [];
constructor(executor: (resolve: (resolution: T | Thenable<T>) => void, reject: (reason: any) => void) => void) {
/* tslint:disable-next-line:strict-type-predicates */
if (typeof executor !== "function") {
throw new TypeError(`typeof executor !== "function"`);
}
const { resolve, reject } = this._createResolvingFunctions();
try {
executor(resolve, reject);
}
catch (ex) {
reject(ex);
}
}
/**
* @param {?function(T):(U|!Thenable.<U>)} onFulfilled
* @param {?function(*):(U|!Thenable.<U>)} onRejected
* @return {!Promise.<U>}
*/
then<U>(onFulfilled: ((value: T) => U | Thenable<U>) | undefined, onRejected?: (reason: any) => U | Thenable<U>): Promise<U> {
const resultCapability = new DeferredPromise<U>();
if (typeof onFulfilled !== "function") {
onFulfilled = (value: T) => value as any as U;
}
if (typeof onRejected !== "function") {
onRejected = (reason: any): U => { throw reason; };
}
const fulfillReaction: FulfilledPromiseReaction<T, U> = {
capabilities: resultCapability,
handler: onFulfilled,
};
const rejectReaction: RejectedPromiseReaction<U> = {
capabilities: resultCapability,
handler: onRejected,
};
switch (this._state.state) {
case "pending":
this._fulfillReactions.push(fulfillReaction);
this._rejectReactions.push(rejectReaction);
break;
case "fulfilled":
enqueueFulfilledReactionJob(fulfillReaction, this._state.value);
break;
case "rejected":
enqueueRejectedReactionJob(rejectReaction, this._state.reason);
break;
}
return resultCapability.promise;
}
/**
* @param {function(*):(T|!Thenable.<T>)} onRejected
* @return {!Promise.<T>}
*/
catch(onRejected: (reason: any) => T | Thenable<T>): Promise<T> {
return this.then(undefined, onRejected);
}
/**
* @return {{ resolve(T|!Thenable.<T>), reject(*) }}
*/
private _createResolvingFunctions(): { resolve(resolution: T | Thenable<T>): void; reject(reason: any): void; } {
let alreadyResolved = false;
const resolve = (resolution: T | Thenable<T>): void => {
if (alreadyResolved) {
return;
}
alreadyResolved = true;
if (resolution === this) {
this._reject(new TypeError(`resolution === this`));
return;
}
/* tslint:disable-next-line:strict-type-predicates */
if (resolution === null || (typeof resolution !== "object" && typeof resolution !== "function")) {
this._fulfill(resolution as T);
return;
}
let then: ThenableThen<T>;
try {
then = (resolution as Thenable<T>).then;
}
catch (ex) {
this._reject(ex);
return;
}
/* tslint:disable-next-line:strict-type-predicates */
if (typeof then !== "function") {
this._fulfill(resolution as T);
return;
}
enqueueJob(() => this._resolveWithThenable(resolution as Thenable<T>, then));
};
const reject = (reason: any): void => {
if (alreadyResolved) {
return;
}
alreadyResolved = true;
this._reject(reason);
};
return { resolve, reject };
}
/**
* @param {!Thenable.<T>} thenable
* @param {{function(this:!Thenable.<T>, function(T|!Thenable.<T>), function(*))}} then
*/
private _resolveWithThenable(thenable: Thenable<T>, then: ThenableThen<T>): void {
const { resolve, reject } = this._createResolvingFunctions();
try {
then.call(thenable, resolve, reject);
}
catch (ex) {
reject(ex);
}
}
/**
* @param {T} value
*/
private _fulfill(value: T): void {
const reactions = this._fulfillReactions;
this._state = { state: "fulfilled", value };
this._fulfillReactions = [];
this._rejectReactions = [];
for (const reaction of reactions) {
enqueueFulfilledReactionJob(reaction, value);
}
}
/**
* @param {*} reason
*/
private _reject(reason: any): void {
const reactions = this._rejectReactions;
this._state = { state: "rejected", reason };
this._fulfillReactions = [];
this._rejectReactions = [];
for (const reaction of reactions) {
enqueueRejectedReactionJob(reaction, reason);
}
}
}
/* tslint:disable:variable-name */
/**
* Set to the global implementation of Promise if the environment has one, else set to {@link ./utility/promise.SimplePromise}
*
* Can be set to a value using {@link libjass.configure}
*
* Set it to null to force {@link ./utility/promise.SimplePromise} to be used even if a global Promise is present.
*
* @type {function(new:Promise)}
*/
export let Promise: {
new <T>(init: (resolve: (value: T | Thenable<T>) => void, reject: (reason: any) => void) => void): Promise<T>;
/* tslint:disable-next-line:member-ordering */
prototype: Promise<any>;
resolve<T>(value: T | Thenable<T>): Promise<T>;
reject<T>(reason: any): Promise<T>;
all<T>(values: (T | Thenable<T>)[]): Promise<T[]>;
race<T>(values: (T | Thenable<T>)[]): Promise<T>;
} = global.Promise || SimplePromise;
/* tslint:enable:variable-name */
interface FulfilledPromiseReaction<T, U> {
/** @type {!libjass.DeferredPromise.<U>} */
capabilities: DeferredPromise<U>;
/**
* @param {T} value
* @return {U|!Thenable.<U>}
*/
handler(value: T): U | Thenable<U>;
}
interface RejectedPromiseReaction<U> {
/** @type {!libjass.DeferredPromise.<U>} */
capabilities: DeferredPromise<U>;
/**
* @param {*} reason
* @return {U|!Thenable.<U>}
*/
handler(reason: any): U | Thenable<U>;
}
/**
* The state of the {@link ./utility/promise.SimplePromise}
*/
type SimplePromiseState<T> = { state: "pending" } | { state: "fulfilled"; value: T; } | { state: "rejected"; reason: any; };
/**
* Sets the Promise implementation used by libjass to the provided one. If null, {@link ./utility/promise.SimplePromise} is used.
*
* @param {?function(new:Promise)} value
*/
export function setImplementation(value: typeof Promise | null): void {
if (value !== null) {
Promise = value;
}
else {
Promise = SimplePromise;
}
}
/**
* A deferred promise.
*/
export class DeferredPromise<T> {
/**
* @type {function(T|!Thenable.<T>)}
*/
resolve: (value: T | Thenable<T>) => void;
/**
* @type {function(*)} reason
*/
reject: (reason: any) => void;
private _promise: Promise<T>;
constructor() {
this._promise = new Promise<T>((resolve, reject) => {
Object.defineProperties(this, {
resolve: { value: resolve, enumerable: true },
reject: { value: reject, enumerable: true },
});
});
}
/**
* @type {!Promise.<T>}
*/
get promise(): Promise<T> {
return this._promise;
}
}
/**
* Returns a promise that resolves to the first (in iteration order) promise that fulfills, and rejects if all the promises reject.
*
* @param {!Array.<!Promise.<T>>} promises
* @return {!Promise.<T>}
*/
export function first<T>(promises: Promise<T>[]): Promise<T> {
return first_rec(promises, []);
}
/**
* @param {!Array.<!Promise.<T>>} promises
* @param {!Array.<*>} previousRejections
* @return {!Promise.<T>}
*/
function first_rec<T>(promises: Promise<T>[], previousRejections: any[]): Promise<T> {
if (promises.length === 0) {
return Promise.reject(previousRejections);
}
const [head, ...tail] = promises;
return head.catch(reason => first_rec(tail, previousRejections.concat(reason)));
}
/**
* Returns a promise that resolves to the first (in time order) promise that fulfills, and rejects if all the promises reject.
*
* @param {!Array.<!Promise.<T>>} promises
* @return {!Promise.<T>}
*/
export function any<T>(promises: Promise<T>[]): Promise<T> {
return new Promise<T>((resolve, reject) =>
Promise.all<any>(promises.map(promise => promise.then(resolve, reason => reason))).then(reject));
}
/**
* Returns a promise that runs the given callback when the promise has resolved regardless of whether it fulfilled or rejected.
*
* @param {!Promise.<T>} promise
* @param {function()} body
* @return {!Promise.<T>}
*/
export function lastly<T>(promise: Promise<T>, body: () => void): Promise<T> {
return promise.then<any>(value => {
body();
return value;
}, reason => {
body();
throw reason;
});
}
/**
* @param {!FulfilledPromiseReaction.<T, *>} reaction
* @param {T} value
*/
function enqueueFulfilledReactionJob<T>(reaction: FulfilledPromiseReaction<T, any>, value: T): void {
enqueueJob(() => {
const { capabilities: { resolve, reject }, handler } = reaction;
let handlerResult: any | Thenable<any>;
try {
handlerResult = handler(value);
}
catch (ex) {
reject(ex);
return;
}
resolve(handlerResult);
});
}
/**
* @param {!RejectedPromiseReaction.<*>} reaction
* @param {*} reason
*/
function enqueueRejectedReactionJob(reaction: RejectedPromiseReaction<any>, reason: any): void {
enqueueJob(() => {
const { capabilities: { resolve, reject }, handler } = reaction;
let handlerResult: any | Thenable<any>;
try {
handlerResult = handler(reason);
}
catch (ex) {
reject(ex);
return;
}
resolve(handlerResult);
});
} | the_stack |
import * as Address from "../../generated/joynr/system/RoutingTypes/Address";
import DiscoveryEntry from "../../generated/joynr/types/DiscoveryEntry";
import * as ProviderQos from "../../generated/joynr/types/ProviderQos";
import ProviderScope from "../../generated/joynr/types/ProviderScope";
import Version from "../../generated/joynr/types/Version";
import loggingManager from "../system/LoggingManager";
import { JoynrProvider, JoynrProviderType } from "../types/JoynrProvider";
import * as UtilInternal from "../util/UtilInternal";
import MessageRouter = require("../messaging/routing/MessageRouter");
import ParticipantIdStorage = require("./ParticipantIdStorage");
import PublicationManager = require("../dispatching/subscription/PublicationManager");
import RequestReplyManager = require("../dispatching/RequestReplyManager");
import { DiscoveryStub } from "./interface/DiscoveryStub";
const log = loggingManager.getLogger("joynr.capabilities.CapabilitiesRegistrar");
let defaultExpiryIntervalMs = 6 * 7 * 24 * 60 * 60 * 1000; // 6 Weeks
interface RegistrationSettings {
domain: string;
provider: JoynrProvider;
providerQos: ProviderQos;
expiryDateMs?: number;
loggingContext?: Record<string, any>;
participantId?: string;
awaitGlobalRegistration?: boolean;
}
interface RegistrationSettingsWithGbids extends RegistrationSettings {
gbids?: string[];
}
interface MultipleBackendSettings {
registerToAllBackends: boolean;
gbids?: string[];
}
class CapabilitiesRegistrar {
private started: boolean = true;
private publicationManager: PublicationManager;
private requestReplyManager: RequestReplyManager;
private libjoynrMessagingAddress: Address;
private participantIdStorage: ParticipantIdStorage;
private messageRouter: MessageRouter;
private discoveryStub: DiscoveryStub;
/**
* The Capabilities Registrar
*
* @constructor
*
* @param dependencies
* @param dependencies.discoveryStub connects the inProcessStub to its skeleton
* @param dependencies.messageRouter used to register nextHop for registered provider
* @param dependencies.participantIdStorage connects the inProcessStub to its skeleton
* @param dependencies.libjoynrMessagingAddress address to be used by the cluster controller to send incoming requests to this
* libjoynr's providers
* @param dependencies.requestReplyManager passed on to providerAttribute, providerOperation and providerEvent
* @param dependencies.publicationManager passed on to providerAttribute
*/
public constructor(dependencies: {
discoveryStub: DiscoveryStub;
messageRouter: MessageRouter;
participantIdStorage: ParticipantIdStorage;
libjoynrMessagingAddress: Address;
requestReplyManager: RequestReplyManager;
publicationManager: PublicationManager;
}) {
this.discoveryStub = dependencies.discoveryStub;
this.messageRouter = dependencies.messageRouter;
this.participantIdStorage = dependencies.participantIdStorage;
this.libjoynrMessagingAddress = dependencies.libjoynrMessagingAddress;
this.requestReplyManager = dependencies.requestReplyManager;
this.publicationManager = dependencies.publicationManager;
}
/**
* Internal function used to throw exception in case of CapabilitiesRegistrar
* is not used properly
*/
private checkIfReady(): void {
if (!this.started) {
throw new Error("CapabilitiesRegistrar is already shut down");
}
}
/**
* Registers a provider so that it is publicly available
*
* If registration to local and global scope is requested by 'providerQos' parameter,
* the provider is registered to all GBIDs configured in the cluster controller.
*
* The 'gbids' parameter can be provided to override the GBIDs selection in the cluster
* controller. The global capabilities directory identified by the first selected GBID performs
* the registration.
*
* @param settings the arguments object for this function call
* @param settings.domain
* @param settings.provider
* @param settings.providerQos the Quality of Service parameters for provider registration
* @param [settings.expiryDateMs] date in millis since epoch after which the discovery entry can be purged from all directories.
* Default value is one day.
* @param [settings.loggingContext] optional logging context will be appended to logging messages created in the name of this proxy
* @param [settings.participantId] optional. If not set, a globally unique UUID participantId will be generated, and persisted to
* localStorage. If set, the participantId must be unique in the context of the provider's scope, as set in the ProviderQos;
* The application setting the participantId is responsible for guaranteeing uniqueness.
* @param [settings.awaitGlobalRegistration] optional. If provided and set to true registerProvider will wait until local and global
* registration succeeds or timeout is reached: otherwise registerProvider only waits for local registration.
* @param settings.gbids Optional subset of GBIDs configured in the cluster controller for custom global
* registration.
*
* @returns an A+ promise
*/
public register(settings: RegistrationSettingsWithGbids): Promise<string> {
return this.registerInternal(settings, { registerToAllBackends: false, gbids: settings.gbids });
}
/**
* Registers a provider so that it is publicly available in all backends known to the cluster controller
*
* @param settings the arguments object for this function call
* @param settings.domain
* @param settings.provider
* @param settings.providerQos the Quality of Service parameters for provider registration
* @param [settings.expiryDateMs] date in millis since epoch after which the discovery entry can be purged from all directories.
* Default value is one day.
* @param [settings.loggingContext] optional logging context will be appended to logging messages created in the name of this proxy
* @param [settings.participantId] optional. If not set, a globally unique UUID participantId will be generated, and persisted to
* localStorage. If set, the participantId must be unique in the context of the provider's scope, as set in the ProviderQos;
* The application setting the participantId is responsible for guaranteeing uniqueness.
* @param [settings.awaitGlobalRegistration] optional. If provided and set to true registerProvider will wait until local and global
* registration succeeds or timeout is reached: otherwise registerProvider only waits for local registration.
*
* @returns an A+ promise
* @deprecated Use `register` instead.
*/
public async registerInAllKnownBackends(settings: RegistrationSettings): Promise<string> {
return this.registerInternal(settings, { registerToAllBackends: true });
}
private async registerInternal(
{
domain,
provider,
providerQos,
expiryDateMs,
loggingContext,
participantId,
awaitGlobalRegistration
}: RegistrationSettings,
gbIdSettings: MultipleBackendSettings
): Promise<string> {
this.checkIfReady();
const missingImplementations = provider.checkImplementation();
if (missingImplementations.length > 0) {
throw new Error(
`provider: ${domain}/${provider.interfaceName}.v${
(provider.constructor as JoynrProviderType).MAJOR_VERSION
} is missing: ${missingImplementations.toString()}`
);
}
if (participantId === undefined || participantId === null) {
// retrieve participantId if not passed in
participantId = this.participantIdStorage.getParticipantId(domain, provider);
} else {
// store provided participantId
this.participantIdStorage.setParticipantId(domain, provider, participantId);
}
if (loggingContext !== undefined) {
log.warn("loggingContext is currently not supported");
}
if (awaitGlobalRegistration === undefined) {
awaitGlobalRegistration = false;
}
if (typeof awaitGlobalRegistration !== "boolean") {
const errText = "awaitGlobalRegistration must be boolean";
log.warn(errText);
return Promise.reject(new Error(errText));
}
// register provider at RequestReplyManager
this.requestReplyManager.addRequestCaller(participantId, provider);
// if provider has at least one attribute, add it as publication provider
this.publicationManager.addPublicationProvider(participantId, provider);
// register routing address at routingTable
const isGloballyVisible = providerQos.scope === ProviderScope.GLOBAL;
await this.messageRouter.addNextHop(participantId, this.libjoynrMessagingAddress, isGloballyVisible);
// TODO: Must be later provided by the user or retrieved from somewhere
const defaultPublicKeyId = "";
try {
const discoveryEntry = new DiscoveryEntry({
providerVersion: new Version({
majorVersion: (provider.constructor as JoynrProviderType).MAJOR_VERSION,
minorVersion: (provider.constructor as JoynrProviderType).MINOR_VERSION
}),
domain,
interfaceName: provider.interfaceName,
participantId,
qos: providerQos,
publicKeyId: defaultPublicKeyId,
expiryDateMs: expiryDateMs || Date.now() + defaultExpiryIntervalMs,
lastSeenDateMs: Date.now()
});
if (gbIdSettings.registerToAllBackends) {
await this.discoveryStub.addToAll(discoveryEntry, awaitGlobalRegistration);
} else {
await this.discoveryStub.add(discoveryEntry, awaitGlobalRegistration, gbIdSettings.gbids || []);
}
} catch (e) {
this.messageRouter.removeNextHop(participantId).catch(UtilInternal.emptyFunction);
throw e;
}
log.info(
`Provider registered: participantId: ${participantId}, domain: ${domain}, interfaceName: ${
provider.interfaceName
}, majorVersion: ${(provider.constructor as JoynrProviderType).MAJOR_VERSION}`
);
return participantId;
}
/**
* Registers a provider so that it is publicly available
*
* If registration to local and global scope is requested by 'providerQos' parameter,
* the provider is registered to all GBIDs configured in the cluster controller.
*
* The 'gbids' parameter can be provided to override the GBIDs selection in the cluster
* controller. The global capabilities directory identified by the first selected GBID performs
* the registration.
*
* @param domain
* @param provider
* @param provider.interfaceName
* @param providerQos the Quality of Service parameters for provider registration
* @param [expiryDateMs] date in millis since epoch after which the discovery entry can be purged from all directories.
* Default value is one day.
* @param [loggingContext] optional logging context will be appended to logging messages created in the name of this proxy
* @param [participantId] optional. If not set, a globally unique UUID participantId will be generated, and persisted to localStorage.
* @param [awaitGlobalRegistration] optional. If provided and set to true registerProvider will wait until local and global
* registration succeeds or timeout is reached: otherwise registerProvider only waits for local registration.
* @param gbids: Optional subset of GBIDs configured in the cluster controller for custom global
* registration.
*
* @returns an A+ promise
*/
public async registerProvider(
domain: string,
provider: JoynrProvider,
providerQos: ProviderQos,
expiryDateMs?: number,
loggingContext?: Record<string, any>,
participantId?: string,
awaitGlobalRegistration?: boolean,
gbids?: string[]
): Promise<string> {
return this.registerInternal(
{
domain,
provider,
providerQos,
expiryDateMs,
loggingContext,
participantId,
awaitGlobalRegistration
},
{ registerToAllBackends: false, gbids }
);
}
/**
* Unregister a provider from the joynr communication framework so that it
* can no longer be called or discovered.
*
* If the provider is registered globally (default), i.e. ProviderScope.GLOBAL
* has been set in ProviderQos when registering the provider:
* This function triggers a global remove operation in the local capabilities
* directory of the cluster controller (standalone or embedded within the same runtime)
* and returns. It does not wait for a response from global capabilities directory and
* does not get informed about errors or success. The cluster controller will repeat
* the global remove operation until it succeeds or the cluster controller is shut down.
*
* If the provider is registered only locally, i.e. ProviderScope.LOCAL
* has been set in ProviderQos when registering the provider:
* This function removes the provider from the local capabilities directory
* of the cluster controller (standalone or embedded within the same runtime)
* and waits for the result.
*
* @note: This function does not guarantee a successful execution of provider's removal
* from the global capabilities directory.
*
* @param domain
* @param provider
* @param provider.interfaceName
* @returns an A+ promise
*/
public async unregisterProvider(domain: string, provider: JoynrProvider): Promise<void> {
this.checkIfReady();
// retrieve participantId
const participantId = this.participantIdStorage.getParticipantId(domain, provider);
await this.discoveryStub.remove(participantId);
// unregister routing address at routingTable
await this.messageRouter.removeNextHop(participantId);
// if provider has at least one attribute, remove it as publication
// provider
this.publicationManager.removePublicationProvider(participantId, provider);
// unregister provider at RequestReplyManager
this.requestReplyManager.removeRequestCaller(participantId);
log.info(
`Provider unregistered: participantId: ${participantId}, domain: ${domain}, interfaceName: ${
provider.interfaceName
}, majorVersion: ${(provider.constructor as JoynrProviderType).MAJOR_VERSION}`
);
}
/**
* Shutdown the capabilities registrar
*/
public shutdown(): void {
this.started = false;
}
public static setDefaultExpiryIntervalMs(delay: number): void {
defaultExpiryIntervalMs = delay;
}
}
export = CapabilitiesRegistrar; | the_stack |
"use strict";
import { Server } from "./server";
import { User, Message } from "./user";
import {
Colors,
NameColorPair,
Stopwatch,
UserColorArray,
Utils,
} from "./utils";
//import { DEBUGMODE } from "../app";
export abstract class Game {
protected endChat: MessageRoom = new MessageRoom();
//the time players are given at the end to discuss the game before they are kicked
protected endTime: number = 60000;
//the list of message rooms, used for communication between players,
//adds the ability to mute players etc.
private _messageRooms: Array<MessageRoom> = [];
private _users: Array<User> = [];
private _registeredPlayerCount: number = 0;
//min and max number of players - controls when the game chooses to start
private readonly _minPlayerCount: number;
private readonly _maxPlayerCount: number;
//true until the point where players are all kicked (so includes end chat phase)
private _inPlay: boolean = false;
//a reference to the parent server
private readonly _server: Server;
private readonly startClock: Stopwatch = new Stopwatch();
//time given to players to join the game once min is exceeded
private _startWait = 60000;
private holdVote: boolean = false;
//used to hand out username colors to players
private colorPool = UserColorArray.slice();
//what the game mode is
private _gameType: string;
private _resetStartTime: boolean = false;
private _inEndChat: boolean = false;
//the name the game creator gave the game
private _name: string;
private _uid: string;
//if no one is in the game for this long, the game is closed by the server
private idleTime: number = 60000 * 5;
//timer that keeps track of game inactivity
private idleTimer: Stopwatch = new Stopwatch();
//game data printed when the game starts
private readonly author: string;
private readonly title: string;
private readonly license: string;
public constructor(
server: Server,
minPlayerCount: number,
maxPlayerCount: number,
gameType: string,
name: string,
uid: string,
title: string,
author: string,
license: string,
) {
//debug mode will start game faster
//if (DEBUGMODE) {
//this._startWait = 10000;
//}
this._uid = uid;
this._server = server;
this._minPlayerCount = minPlayerCount;
this._maxPlayerCount = maxPlayerCount;
this._gameType = gameType;
this._name = name;
this.title = title;
this.author = author;
this.license = license;
//run update functions periodically
setInterval(this.pregameLobbyUpdate.bind(this), 500);
setInterval(this.update.bind(this), 500);
}
public get maxPlayerCount() {
return this._maxPlayerCount;
}
public get minPlayerCount() {
return this._minPlayerCount;
}
public get name() {
return this._name;
}
public get inEndChat() {
return this._inEndChat;
}
public get uid() {
return this._uid;
}
public get users() {
return this._users;
}
//update is supplied by concrete child class
protected update() {}
//returns array of usernames and their colors, to put in the lobby chat
get usernameColorPairs(): Array<NameColorPair> {
let usernameColorPairs = [];
for (let i = 0; i < this._users.length; i++) {
usernameColorPairs.push(<NameColorPair>{
username: this._users[i].username,
color: this._users[i].color,
});
}
return usernameColorPairs;
}
public get gameType() {
return this._gameType;
}
get startWait() {
return this._startWait;
}
get inPlay() {
return this._inPlay;
}
get playerCount() {
return this._registeredPlayerCount;
}
//returns how many more players are needed to start
get minimumPlayersNeeded() {
if (this._inPlay) {
return 0;
} else {
return this._minPlayerCount - this._registeredPlayerCount;
}
}
//returns how many players are wanted
get playersWanted() {
if (this._inPlay) {
return 0;
} else {
return this._maxPlayerCount - this._registeredPlayerCount;
}
}
public getUser(id: string): User | undefined {
for (let i = 0; i < this._users.length; i++) {
if (this._users[i].id == id) {
return this._users[i];
}
}
console.log("Error: Game.getUser: No user found with given id");
return undefined;
}
public isUser(id: string): boolean {
for (let i = 0; i < this._users.length; i++) {
if (this._users[i].id == id) {
return true;
}
}
return false;
}
public setAllTime(time: number, warnTime: number) {
for (let i = 0; i < this._users.length; i++) {
this._users[i].setTime(time, warnTime);
}
}
private setAllTitle(title: string) {
for (let i = 0; i < this._users.length; i++) {
this._users[i].title = title;
}
}
public markAsDead(name: string) {
for (let i = 0; i < this.users.length; i++) {
this.users[i].markAsDead(name);
}
}
protected cancelVoteSelection() {
for (let i = 0; i < this.users.length; i++) {
this.users[i].cancelVoteEffect();
}
}
private pregameLobbyUpdate() {
if (!this.inPlay) {
//remove inactive games
if (this._users.length != 0) {
this.idleTimer.restart();
this.idleTimer.stop();
} else if (this.idleTimer.time > this.idleTime) {
this._server.removeGame(this);
} else {
this.idleTimer.start();
}
//if have max number of players, start the game immediately
if (this._registeredPlayerCount >= this._maxPlayerCount) {
this.start();
this.setAllTitle("OpenWerewolf:In play");
//if have minimum number of players
} else if (this._registeredPlayerCount >= this._minPlayerCount) {
this._resetStartTime = true;
//if startClock has been ticking for startWait time, start:
if (this.startClock.time > this.startWait) {
this.start();
this.setAllTitle("OpenWerewolf: In play");
//if a majority has typed /start, start:
} else if (!this.holdVote) {
let voteCount = 0;
for (let i = 0; i < this._users.length; i++) {
if (this._users[i].startVote) {
voteCount++;
}
}
if (voteCount >= this._users.length / 2) {
this.start();
this.setAllTitle("OpenWerewolf: In play");
} else {
this.setAllTitle("Starting...");
}
}
//TODO: if everyone has typed /wait, wait a further 30 seconds up to a limit of 3 minutes:
} else {
this.startClock.restart();
this.startClock.start();
if (this._resetStartTime) {
this.setAllTime(0, 0);
console.log("restarted");
this._resetStartTime = false;
this.setAllTitle("OpenWerewolf (" + this._users.length + ")");
}
}
}
}
public addUser(user: User) {
this.endChat.addUser(user);
this.endChat.muteAll();
for (let i = 0; i < this._users.length; i++) {
this._users[i].sound("NEWPLAYER");
}
user.color = this.colorPool[0];
user.headerSend([
{ text: "Welcome, ", color: Colors.white },
{ text: user.username, color: user.color },
]);
this.colorPool.splice(0, 1);
user.startVote = false;
this._users.push(user);
this.setAllTitle("OpenWerewolf (" + this._users.length + ")");
this._registeredPlayerCount++;
this._server.listPlayerInLobby(user.username, user.color, this);
//If the number of players is between minimum and maximum count, inform them of the wait remaining before game starts
if (
this._users.length > this._minPlayerCount &&
this._users.length < this._maxPlayerCount
) {
user.send(
"The game will start in " +
Math.floor(
(this.startWait - this.startClock.time) / 1000,
).toString() +
" seconds",
);
user.send('Type "/start" to start the game immediately');
user.setTime(this.startWait - this.startClock.time, 10000);
}
}
public broadcast(
msg: string | Message,
textColor?: Colors,
backgroundColor?: Colors,
) {
for (let i = 0; i < this._users.length; i++) {
this._users[i].send(msg, textColor, backgroundColor);
}
}
public abstract receive(user: User, msg: string): void;
public disconnect(user: User): void {
this.lineThroughPlayer(user.username, "grey");
}
//remove a user from the game
public kick(user: User) {
for (let i = 0; i < this._messageRooms.length; i++) {
this._messageRooms[i].removeUser(user);
this.endChat.removeUser(user);
}
for (let i = 0; i < this._users.length; i++) {
this._users[i].sound("LOSTPLAYER");
}
this._server.unlistPlayerInLobby(user.username, this);
let index = this._users.indexOf(user);
if (index != -1) {
this._registeredPlayerCount--;
this._users.splice(index, 1);
}
this.colorPool.push(user.color);
this.setAllTitle("OpenWerewolf (" + this._users.length + ")");
user.title = "OpenWerewolf";
this.broadcast(user.username + " has disconnected");
}
protected headerBroadcast(array: Array<{ text: string; color?: Colors }>) {
for (let i = 0; i < this._users.length; i++) {
this._users[i].headerSend(array);
}
}
public abstract resendData(user: User): void;
protected beforeStart() {
for (let i = 0; i < this._users.length; i++) {
this._users[i].sound("NEWGAME");
this._users[i].emit("newGame");
}
this._inPlay = true;
this._server.markGameStatusInLobby(this, "IN PLAY");
this.broadcast("*** NEW GAME ***", Colors.brightGreen);
this.broadcast(this.title + " by " + this.author);
this.broadcast("License: " + this.license);
this.broadcast(
"You can create your own games! Take a look at the github repository.",
);
this.headerBroadcast([
{ text: "*** NEW GAME ***", color: Colors.brightGreen },
]);
//send all players to user
for (let user of this.users) {
user.emit("allPlayers", this.users.map(elem => elem.username));
}
}
protected afterEnd() {
//Clear all message rooms of players
for (let i = 0; i < this._messageRooms.length; i++) {
for (let j = 0; j < this._users.length; j++) {
console.log("active " + this._users[j].username);
this._messageRooms[i].removeUser(this._users[j]);
}
}
this._inEndChat = true;
this.endChat.unmuteAll();
for (let i = 0; i < this._users.length; i++) {
this._users[i].emit("endChat");
}
this.setAllTime(this.endTime, 10000);
setTimeout(() => {
this.setAllTitle("OpenWerewolf");
//emit event that causes players to restart the client
for (let i = 0; i < this._users.length; i++) {
this._users[i].emit("restart");
}
this._inPlay = false;
for (let i = 0; i < this._users.length; i++) {
this._users[i].resetAfterGame();
this.endChat.removeUser(this._users[i]);
}
this._users = [];
this._registeredPlayerCount = 0;
this.colorPool = UserColorArray.slice();
this._server.markGameStatusInLobby(this, "OPEN");
this._inEndChat = false;
this._server.removeGame(this);
}, this.endTime);
}
protected addMessageRoom(room: MessageRoom) {
this._messageRooms.push(room);
}
protected abstract start(): void;
protected abstract end(): void;
protected broadcastPlayerList() {
let playersString = "";
for (let i = 0; i < this._users.length; i++) {
if (i != 0) {
playersString += ", ";
}
playersString += this._users[i].username;
}
this.broadcast("Players: " + playersString + ".");
}
protected broadcastRoleList(list: Array<string>) {
let string = "";
for (let i = 0; i < list.length; i++) {
if (i != 0) {
string += ", ";
}
string += list[i];
}
this.broadcast("Roles (in order of when they act): " + string + ".");
}
public lineThroughPlayer(username: string, color: string) {
for (let i = 0; i < this._users.length; i++) {
this._users[i].lineThroughUser(username, color);
}
}
//to be overridden in child classes as necessary
public customAdminReceive(user: User, msg: string): void {}
//generic admin commands
public adminReceive(user: User, msg: string): void {
if (user.admin == true && msg[0] == "!") {
if (!this.inPlay) {
if (Utils.isCommand(msg, "!stop")) {
this.startClock.stop();
user.send("Countdown stopped", undefined, Colors.green);
} else if (Utils.isCommand(msg, "!start")) {
if (this._registeredPlayerCount >= this._minPlayerCount) {
this.start();
} else {
user.send("Not enough players to start game", Colors.brightRed);
}
} else if (Utils.isCommand(msg, "!resume")) {
this.startClock.start();
user.send("Countdown resumed", undefined, Colors.green);
} else if (Utils.isCommand(msg, "!restart")) {
this.startClock.restart();
user.send("Countdown restarted", undefined, Colors.green);
} else if (Utils.isCommand(msg, "!time")) {
user.send(this.startClock.time.toString());
} else if (Utils.isCommand(msg, "!hold")) {
user.send(
"The vote to start has been halted.",
undefined,
Colors.green,
);
this.holdVote = true;
} else if (Utils.isCommand(msg, "!release")) {
user.send(
"The vote to start has been resumed",
undefined,
Colors.green,
);
this.holdVote = false;
} else if (Utils.isCommand(msg, "!help")) {
user.send(
"!stop, !start, !resume, !restart, !time, !hold, !release, !yell, !help",
undefined,
Colors.green,
);
user.send(
"Use !gamehelp for game-specific commands.",
undefined,
Colors.green,
);
}
}
if (Utils.isCommand(msg, "!yell")) {
this.broadcast("ADMIN:" + msg.slice(5), Colors.brightGreen);
}
this.customAdminReceive(user, msg);
}
}
}
/**
*
* Adds 'muted' and 'deafened' properties to User so that it can be used in a MessageRoom.
* Each MessageRoom will have a different MessageRoomMember for the same User.
*/
class MessageRoomMember {
private _muted: boolean = false;
private _deafened: boolean = false;
private _permanentlyMuted: boolean = false;
private _permanentlyDeafened: boolean = false;
private _member: User;
constructor(member: User) {
this._member = member;
}
public permanentlyMute() {
this._permanentlyMuted = true;
this._muted = true;
}
public permanentlyDeafen() {
this._permanentlyDeafened = true;
this._deafened = true;
}
public get muted(): boolean {
return this._muted;
}
public get deafened() {
return this._deafened;
}
public mute() {
this._muted = true;
}
public unmute() {
if (!this._permanentlyMuted) {
this._muted = false;
}
}
public deafen() {
this._deafened = true;
}
public undeafen() {
if (!this._permanentlyDeafened) {
this._deafened = false;
}
}
get id() {
return this._member.id;
}
public send(
message: string | Message,
textColor?: Colors,
backgroundColor?: Colors,
): void {
this._member.send(message, textColor, backgroundColor);
}
}
export class MessageRoom {
private _members: Array<MessageRoomMember> = [];
public getMemberById(id: string): MessageRoomMember | undefined {
for (let i = 0; i < this._members.length; i++) {
if (this._members[i].id == id) {
return this._members[i];
}
}
console.log(
"Error: MessageRoom.getMemberById: No message room member found with given id",
);
return undefined;
}
public receive(
sender: User,
msg: string | Message,
textColor?: Colors,
backgroundColor?: Colors,
) {
//if id passed in, find the sender within the message room
let messageRoomSender = this.getMemberById(sender.id);
if (messageRoomSender instanceof MessageRoomMember) {
if (!messageRoomSender.muted) {
for (let i = 0; i < this._members.length; i++) {
if (!this._members[i].deafened) {
this._members[i].send(msg, textColor, backgroundColor);
}
}
}
}
}
public broadcast(
msg: string | Message,
textColor?: Colors,
backgroundColor?: Colors,
) {
for (let i = 0; i < this._members.length; i++) {
if (!this._members[i].deafened) {
this._members[i].send(msg, textColor, backgroundColor);
}
}
}
public addUser(user: User) {
this._members.push(new MessageRoomMember(user));
}
public removeUser(user: User) {
let member = this.getMemberById(user.id);
if (member instanceof MessageRoomMember) {
let indexOf = this._members.indexOf(member);
if (indexOf != -1) {
this._members.splice(indexOf, 1);
}
}
}
public mute(user: User) {
let member = this.getMemberById(user.id);
if (member instanceof MessageRoomMember) {
member.mute();
}
}
public deafen(user: User) {
let member = this.getMemberById(user.id);
if (member instanceof MessageRoomMember) {
member.deafen();
}
}
public unmute(user: User) {
let member = this.getMemberById(user.id);
if (member instanceof MessageRoomMember) {
member.unmute();
}
}
public undeafen(user: User) {
let member = this.getMemberById(user.id);
if (member instanceof MessageRoomMember) {
member.undeafen();
}
}
public muteAll() {
this._members.forEach(member => {
member.mute();
});
}
public deafenAll() {
this._members.forEach(member => {
member.deafen();
});
}
public unmuteAll() {
this._members.forEach(member => {
member.unmute();
});
}
public undeafenAll() {
this._members.forEach(member => {
member.undeafen();
});
}
} | the_stack |
import { EntityController } from '../../../src/decorators/entityController';
import { GET } from '../../../src/decorators/requestMethods';
import { PreHandler } from '../../../src/decorators/hooks';
import { bootstrap } from '../../../src/bootstrap';
import { Inject } from '../../../src/decorators/inject';
import { FastifyToken } from '../../../src/symbols';
import entityControllerMethods from '../../../src/decorators/entityController/methods';
import fastify, { FastifyInstance } from 'fastify';
import ModelMock, * as ModelMockMethods from '../../support/ModelMock';
@EntityController({}, '/entity')
class EntityControllerTest {
@Inject(FastifyToken)
instance: FastifyInstance;
@GET('/custom', {
schema: {
querystring: {
flag: { type: 'boolean' }
}
}
})
async getCustom(): Promise<void> {
return;
}
@PreHandler
async preHandlerHook(): Promise<void> {
return;
}
}
@EntityController(class EntityOne {})
class EntityControllerRoot {}
describe('@EntityController decorator', () => {
const spies: Record<string, jest.SpyInstance> = {};
let server: FastifyInstance;
beforeAll(async () => {
spies.getCustom = jest.spyOn(EntityControllerTest.prototype, 'getCustom');
spies.preHandlerHook = jest.spyOn(EntityControllerTest.prototype, 'preHandlerHook');
spies.find = jest.spyOn(entityControllerMethods, 'find');
spies.findOne = jest.spyOn(entityControllerMethods, 'findOne');
spies.create = jest.spyOn(entityControllerMethods, 'create');
spies.patch = jest.spyOn(entityControllerMethods, 'patch');
spies.patchOne = jest.spyOn(entityControllerMethods, 'patchOne');
spies.update = jest.spyOn(entityControllerMethods, 'update');
spies.updateOne = jest.spyOn(entityControllerMethods, 'updateOne');
spies.remove = jest.spyOn(entityControllerMethods, 'remove');
spies.removeOne = jest.spyOn(entityControllerMethods, 'removeOne');
});
beforeEach(() => {
server = fastify();
server.decorate('BaseModel', ModelMock);
});
afterEach(() => {
server.close();
ModelMock.mockClear();
Object.values(spies).forEach(spy => spy.mockClear());
Object.values(ModelMockMethods).forEach(mock => mock.mockClear());
});
describe('EntityController register', () => {
let bootstrapResult;
beforeEach(async () => {
bootstrapResult = await bootstrap(server, { controllers: [EntityControllerTest, EntityControllerRoot] });
});
test('Should register with an empty "route" option', async () => {
// arrange
const data = [{ id: 1, name: 'Jhon Doe' }, { id: 2, name: 'Lukas' }];
ModelMockMethods.find.mockResolvedValue(data);
ModelMockMethods.total.mockResolvedValue(data.length);
// act
const result = await server.inject({ method: 'GET', url: '/' });
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(JSON.parse(result.body)).toMatchObject({ total: data.length, limit: 20, skip: 0, data });
});
test('Should register custom endpoint', async () => {
// arrange
spies.getCustom.mockResolvedValue([]);
// act
const result = await server.inject({ method: 'GET', url: '/entity/custom', query: { flag: 'true' } });
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(result.body).toBe('[]');
expect(spies.getCustom).toBeCalledTimes(1);
expect(spies.getCustom.mock.calls[0]).toHaveLength(2);
expect(spies.getCustom.mock.calls[0][0].query.flag).toBe(true);
expect(spies.getCustom.mock.calls[0][0].params).toEqual({});
expect(spies.getCustom.mock.calls[0][0].body).toBeNull();
});
test('Should register controller hook', async () => {
// act
const customResult = await server.inject({ method: 'GET', url: '/entity/custom' });
const generatedResult = await server.inject({ method: 'GET', url: '/entity/' });
// assert
expect(customResult.statusCode).toBe(200);
expect(generatedResult.statusCode).toBe(200);
expect(spies.preHandlerHook).toHaveBeenCalledTimes(2);
expect(spies.preHandlerHook.mock.calls[0]).toHaveLength(3);
expect(spies.preHandlerHook.mock.calls[1]).toHaveLength(3);
});
test('Should inject app instance as controller property', () => {
const controllerInstance = bootstrapResult.controllers[0];
expect(controllerInstance).toHaveProperty('instance');
// TODO: better way to check fastify instance (kind of instanceof)
});
test('Should add controller model instance as controller property', () => {
const controllerInstance = bootstrapResult.controllers[0];
expect(controllerInstance).toHaveProperty('model');
// TODO: better way to check mocked model instance (kind of instanceof)
});
test('Should use qs queryparser', async () => {
await server.inject({ method: 'GET', url: '/entity/?$where[title]=How are you&$where[id][$lt]=10&$where[age][$gte]=18&$where[age][$lte]=65&$where[$or][0][name]=Danila&$where[$or][1][lastname][$in][]=Demidovich&$where[$or][1][lastname][$in][]=Fadeev' });
expect(spies.find).toBeCalledTimes(1);
expect(spies.find.mock.calls[0][0].query).toMatchObject({
$where: {
title: 'How are you',
id: { $lt: 10 },
age: { $gte: '18', $lte: '65' },
$or: [{
name: 'Danila'
}, {
lastname: {
$in: ['Demidovich', 'Fadeev']
}
}]
}
});
});
});
describe('Basic entity controller methods', () => {
beforeEach(async () => {
await bootstrap(server, { controllers: [EntityControllerTest] });
});
describe('Find (@GET) method', () => {
test('Should register findAll route', async () => {
// act
const result = await server.inject({ method: 'GET', url: '/entity/' });
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(spies.find).toBeCalledTimes(1);
});
});
describe('FindOne (@GET) method', () => {
test('Should register findOne route', async () => {
// arrange
const data = { id: 1, name: 'Jhon Doe' };
ModelMockMethods.find.mockResolvedValue([data]);
// act
const result = await server.inject({ method: 'GET', url: '/entity/1' });
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(JSON.parse(result.body)).toMatchObject(data);
expect(spies.findOne).toBeCalledTimes(1);
expect(ModelMockMethods.find).toBeCalledTimes(1);
expect(ModelMockMethods.find).toHaveBeenCalledWith({ $where: { id: '1' } });
});
test('Should throw 404 Not Fount error', async () => {
// arrange
ModelMockMethods.find.mockResolvedValue([]);
// act
const result = await server.inject({ method: 'GET', url: '/entity/356' });
// assert
expect(result.statusCode).toBe(404);
expect(result.statusMessage).toBe('Not Found');
expect(result.body).toBe(JSON.stringify({ statusCode: 404, error: 'Not Found', message: 'undefined #356 is not found' }));
expect(spies.findOne).toBeCalledTimes(1);
expect(ModelMockMethods.find).toBeCalledTimes(1);
expect(ModelMockMethods.find).toHaveBeenCalledWith({ $where: { id: '356' } });
});
});
describe('Create (@POST) method', () => {
test('Should register create route', async () => {
// arrange
ModelMockMethods.create.mockResolvedValue({ identifiers: [3] });
ModelMockMethods.find.mockReturnValue([{ id: 3, name: 'NEW name' }])
// act
const result = await server.inject({ method: 'POST', url: '/entity', body: { name: 'NEW name' } } as any);
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(JSON.parse(result.body)).toMatchObject([{ id: 3, name: 'NEW name' }]);
expect(spies.create).toBeCalledTimes(1);
expect(ModelMockMethods.create).toBeCalledTimes(1);
expect(ModelMockMethods.create).toHaveBeenCalledWith({ name: 'NEW name' });
});
});
describe('PatchOne (@PATCH) method', () => {
test('Should register patchOne route', async () => {
// arrange
ModelMockMethods.patch.mockResolvedValue({ affected: 1 });
ModelMockMethods.find.mockReturnValue([{ id: 12, name: 'PATCHED' }])
// act
const result = await server.inject({ method: 'PATCH', url: '/entity/12', body: { name: 'PATCHED' } } as any);
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(JSON.parse(result.body)).toMatchObject({ id: 12, name: 'PATCHED' });
expect(spies.patchOne).toBeCalledTimes(1);
expect(ModelMockMethods.patch).toBeCalledTimes(1);
expect(ModelMockMethods.patch).toHaveBeenCalledWith({ id: '12' }, { name: 'PATCHED' }); // TODO 12 is number
});
});
describe('Patch (@PATCH) method', () => {
test('Should register patch route', async () => {
// arrange
const data = [{ id: 1, name: 'PATCHED' }, { id: 2, name: 'PATCHED' }, { id: 3, name: 'PATCHED' }, { id: 4, name: 'PATCHED' }];
ModelMockMethods.patch.mockResolvedValue({ affected: 4 });
ModelMockMethods.find.mockReturnValue(data)
// act
const result = await server.inject({ method: 'PATCH', url: '/entity?id[$in]=1&id[$in]=2&id[$in]=3&id[$in]=4', body: { name: 'PATCHED' } } as any);
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(JSON.parse(result.body)).toMatchObject({ affected: 4, data });
expect(spies.patch).toBeCalledTimes(1);
expect(ModelMockMethods.patch).toBeCalledTimes(1);
expect(ModelMockMethods.patch).toHaveBeenCalledWith({ id: { $in: [1, 2, 3, 4] } }, { name: 'PATCHED' });
});
});
describe('UpdateOne (@PUT) method', () => {
test('Should register updateOne route', async () => {
// arrange
ModelMockMethods.update.mockResolvedValue({ affected: 1 });
ModelMockMethods.find.mockReturnValue([{ id: 22, name: 'UPDATED' }])
// act
const result = await server.inject({ method: 'PUT', url: '/entity/22', body: { id: 22, name: 'UPDATED' } } as any);
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(JSON.parse(result.body)).toMatchObject({ id: 22, name: 'UPDATED' });
expect(spies.updateOne).toBeCalledTimes(1);
expect(ModelMockMethods.update).toBeCalledTimes(1);
expect(ModelMockMethods.update).toHaveBeenCalledWith({ id: '22' }, { id: 22, name: 'UPDATED' }); // TODO 22 is number
});
});
describe('Update (@PUT) method', () => {
test('Should register update route', async () => {
// arrange
const data = [{ id: 3, name: 'UPDATED' }, { id: 72, name: 'UPDATED' }];
ModelMockMethods.update.mockResolvedValue({ affected: 2 });
ModelMockMethods.find.mockReturnValue(data)
// act
const result = await server.inject({ method: 'PUT', url: '/entity?age[$lte]=20', body: { name: 'UPDATED' } } as any);
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(JSON.parse(result.body)).toMatchObject({ affected: 2, data });
expect(spies.update).toBeCalledTimes(1);
expect(ModelMockMethods.update).toBeCalledTimes(1);
expect(ModelMockMethods.update).toHaveBeenCalledWith({ age: { $lte: '20' } }, { name: 'UPDATED' }); // TODO 20 is number here
});
});
describe('RemoveOne (@DELETE) method', () => {
test('Should register removeOne route', async () => {
// arrange
ModelMockMethods.remove.mockResolvedValue({ affected: 1 });
ModelMockMethods.find.mockReturnValue([{ id: 123, name: 'REMOVED' }])
// act
const result = await server.inject({ method: 'DELETE', url: '/entity/123' });
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(JSON.parse(result.body)).toMatchObject({ id: 123, name: 'REMOVED' });
expect(spies.removeOne).toBeCalledTimes(1);
expect(ModelMockMethods.remove).toBeCalledTimes(1);
expect(ModelMockMethods.remove).toHaveBeenCalledWith({ id: '123' }); // TODO 123 is number
});
});
describe('Remove (@DELETE) method', () => {
test('Should register remove route', async () => {
// arrange
const data = [{ id: 1, name: 'REMOVED' }, { id: 2, name: 'REMOVED' }];
ModelMockMethods.remove.mockResolvedValue({ affected: 2 });
ModelMockMethods.find.mockReturnValue(data)
// act
const result = await server.inject({ method: 'DELETE', url: '/entity?name[$ilike]=%_ends' });
// assert
expect(result.statusCode).toBe(200);
expect(result.statusMessage).toBe('OK');
expect(JSON.parse(result.body)).toMatchObject({ affected: 2, data });
expect(spies.remove).toBeCalledTimes(1);
expect(ModelMockMethods.remove).toBeCalledTimes(1);
expect(ModelMockMethods.remove).toHaveBeenCalledWith({ name: { $ilike: '%_ends' } });
});
});
});
describe('Configuration', () => {
beforeEach(() => {
ModelMockMethods.find.mockResolvedValue([{ id: 1, name: 'Jhon Doe' }]);
ModelMockMethods.total.mockResolvedValue(1);
ModelMockMethods.create.mockResolvedValue({ identifiers: [1] });
ModelMockMethods.patch.mockResolvedValue({ affected: 1 });
ModelMockMethods.update.mockResolvedValue({ affected: 1 });
ModelMockMethods.remove.mockResolvedValue({ affected: 1 });
});
test.todo('Should define controller config property');
test('Should disable multi methods', async () => {
// act
await bootstrap(server, {
controllers: [EntityControllerTest],
defaults: { allowMulti: false }
});
// assert
const getResponse = await server.inject({ method: 'GET', url: '/entity/' });
expect(getResponse.statusCode).toBe(405);
expect(getResponse.statusMessage).toBe('Method Not Allowed');
expect(JSON.parse(getResponse.body).message).toBe('Method GET is not allowed here');
const patchResponse = await server.inject({ method: 'PATCH', url: '/entity/' });
expect(patchResponse.statusCode).toBe(405);
expect(patchResponse.statusMessage).toBe('Method Not Allowed');
expect(JSON.parse(patchResponse.body).message).toBe('Method PATCH is not allowed here');
const updateResponse = await server.inject({ method: 'PUT', url: '/entity/' });
expect(updateResponse.statusCode).toBe(405);
expect(updateResponse.statusMessage).toBe('Method Not Allowed');
expect(JSON.parse(updateResponse.body).message).toBe('Method PUT is not allowed here');
const removeResponse = await server.inject({ method: 'DELETE', url: '/entity/' });
expect(removeResponse.statusCode).toBe(405);
expect(removeResponse.statusMessage).toBe('Method Not Allowed');
expect(JSON.parse(removeResponse.body).message).toBe('Method DELETE is not allowed here');
const getOneResponse = await server.inject({ method: 'GET', url: '/entity/1' });
expect(getOneResponse.statusCode).toBe(200);
expect(getOneResponse.statusMessage).toBe('OK');
const patchOneResponse = await server.inject({ method: 'PATCH', url: 'entity/1', body: {} } as any);
expect(patchOneResponse.statusCode).toBe(200);
expect(getOneResponse.statusMessage).toBe('OK');
const createResponse = await server.inject({ method: 'POST', url: 'entity', body: { name: 'NEW' } } as any);
expect(createResponse.statusCode).toBe(200);
expect(createResponse.statusMessage).toBe('OK');
const updateOneResponse = await server.inject({ method: 'PUT', url: 'entity/1', body: { name: 'UPDATED' } } as any);
expect(updateOneResponse.statusCode).toBe(200);
expect(updateOneResponse.statusMessage).toBe('OK');
const deleteOneResponse = await server.inject({ method: 'DELETE', url: 'entity/1' });
expect(deleteOneResponse.statusCode).toBe(200);
expect(deleteOneResponse.statusMessage).toBe('OK');
});
test('Should disable not allowed methods', async () => {
// arrange
const restricted = [
{ method: 'GET', url: '/entity/1' },
{ method: 'PATCH', url: '/entity/', body: {} },
{ method: 'PATCH', url: '/entity/1', body: {} },
{ method: 'PUT', url: '/entity/', body: {} },
{ method: 'PUT', url: '/entity/1', body: {} },
{ method: 'DELETE', url: '/entity/' },
];
const allowed = [
{ method: 'GET', url: '/entity/' },
{ method: 'POST', url: '/entity/', body: { name: 'FASTIFY-RESTY-TESTING' } },
{ method: 'DELETE', url: '/entity/1' }
];
// act
await bootstrap(server, {
controllers: [EntityControllerTest],
defaults: { methods: ['find', 'create', 'removeOne'] }
});
const restrictedResponses = await Promise.all(
restricted.map(opts => server.inject({ method: opts.method as any, url: opts.url, body: opts.body } as any))
);
const allowedResponses = await Promise.all(
allowed.map(opts => server.inject({ method: opts.method as any, url: opts.url, body: opts.body } as any))
);
// assert
restrictedResponses.forEach(response => {
expect(response).toHaveProperty('statusCode', 405);
expect(response).toHaveProperty('statusMessage', 'Method Not Allowed');
});
allowedResponses.forEach(response => {
expect(response).toHaveProperty('statusCode', 200);
expect(response).toHaveProperty('statusMessage', 'OK');
});
});
test('Should use custom primary id name', async () => {
// act
await bootstrap(server, {
controllers: [EntityControllerTest],
defaults: { id: '_id' }
});
await server.inject({ method: 'GET', url: '/entity/29' });
await server.inject({ method: 'DELETE', url: '/entity/3102' });
await server.inject({ method: 'PATCH', url: '/entity/189', body: {} } as any);
// arrange
expect(ModelMockMethods.find).toBeCalledWith({ $where: { _id: '29' }});
expect(ModelMockMethods.remove).toBeCalledWith({ _id: '3102' });
expect(ModelMockMethods.patch).toBeCalledWith({ _id: '189' }, {});
});
describe('Pagination configuration', () => {
test.todo('Should use default pagination');
test.todo('Should disable pagination from the configuration');
});
});
}); | the_stack |
import { EventEmitter } from 'events';
import { Log } from '../utils/log';
import AbrLevel from './abr-level';
import { AbrManifest } from './abr-manifest';
import { IAbrAlgorithm, RealtimeStatus } from '../types/abr';
import { SpeedTest, SpeedTestContext, SpeedTestResult } from "../utils/speed-test";
type AdaptiveConfig = {
stableBufferDiffThresholdSecond: number;
stableBufferIntervalMs: number;
speedTestTimeoutMs: number;
generateSpeedGapMs: number;
bufferCheckIntervalMs: number,
smoothedSpeedUtilizationRatio: number;
smallSpeedToBitrateRatio: number;
enoughSpeedToBitrateRatio: number;
bufferLowerLimitSecond: number;
recentBufferedSize: number;
smoothedSpeedRatio: number;
isSpeedFullyUsed: boolean;
};
const tag = 'algorithm-simple';
const CONFIG: AdaptiveConfig = {
stableBufferDiffThresholdSecond: 0.15,
stableBufferIntervalMs: 2000,
speedTestTimeoutMs: 500,
generateSpeedGapMs: 3000,
bufferCheckIntervalMs: 500,
smoothedSpeedUtilizationRatio: 0.8,
smallSpeedToBitrateRatio: 0.4,
enoughSpeedToBitrateRatio: 0.9,
bufferLowerLimitSecond: 0.6,
recentBufferedSize: 16,
smoothedSpeedRatio: 0.9,
isSpeedFullyUsed: true,
};
/**
* 自适应码率算法入口
*/
class AbrAlgorithmSimple extends EventEmitter implements IAbrAlgorithm {
private _conf!: AdaptiveConfig;
private _pastBuffer!: number[];
private _levels!: AbrLevel[];
private _current: number = 0; // 当前正在加载的流index
private _next: number = 0; // 下一个切换的流index
private _stableBufferStartTime: number = performance.now();
private _speedTester: SpeedTest = new SpeedTest();
private _generatedSpeed: number = 0;
private _lastCheckBuffer: number = 0;
private _lastSpeed: number = 0;
private _timer: any;
constructor() {
super();
}
/**
* 初始化,并写入初始码率
* @param manifest 流信息
* @param config 算法配置
*/
public init(manifest: AbrManifest, status?: RealtimeStatus, config?: any): void {
this._conf = Object.assign({}, CONFIG);
Object.assign(this._conf, config);
Log.i(tag, 'init', manifest, config, this._conf);
this._levels = manifest.levels.slice(0);
this._next = manifest.default;
this._pastBuffer = [0.1];
if (status) {
this._timer = setInterval(() => { this._checkBuffer(status); }, this._conf.bufferCheckIntervalMs);
}
}
private _updateStableBuffer(buffered: number) {
const diff = buffered - this._lastCheckBuffer;
const diffRatio = diff / buffered;
const now = performance.now();
if (diff < -this._conf.stableBufferDiffThresholdSecond || diffRatio < -0.2) {
Log.v(tag, `bufferDiffDown: ${diff.toFixed(2)}s, diffRatio: ${diffRatio.toFixed(2)}`);
this._stableBufferStartTime = Math.max(now, this._stableBufferStartTime);
}
if (diff > this._conf.stableBufferDiffThresholdSecond
&& now - this._stableBufferStartTime + this._conf.bufferCheckIntervalMs > this._conf.stableBufferIntervalMs) {
this._stableBufferStartTime = Math.max(
now - this._conf.bufferCheckIntervalMs * 2,
this._stableBufferStartTime + this._conf.bufferCheckIntervalMs * 2
);
Log.v(tag, `bufferDiffUp: ${diff.toFixed(2)}s`);
}
this._lastCheckBuffer = buffered;
return now - this._stableBufferStartTime > this._conf.stableBufferIntervalMs;
}
private _isSpeedFullyUsed() {
return this._conf.isSpeedFullyUsed;
}
/**
* 周期检查buffer水平和瞬时带宽,判断是否开启测速
* @param status 获取buffer和下载信息
*/
private _checkBuffer(status: RealtimeStatus) {
const buffered = status.bufferedSec();
const isBufferStable = this._updateStableBuffer(buffered);
if (this._isSpeedFullyUsed()) {
if (isBufferStable && this._current + 1 < this._levels.length) {
this._generatedSpeed = this._levels[this._current + 1].bitrate;
} else {
this._generatedSpeed = 0;
}
} else if (isBufferStable && this._current + 1 < this._levels.length) {
this._startTesting(status);
this._stableBufferStartTime = performance.now() + this._conf.generateSpeedGapMs;
}
this._pastBuffer.push(buffered);
if (this._pastBuffer.length > this._conf.recentBufferedSize) {
this._pastBuffer.shift();
}
}
/**
* 基于下一档码率,开启测速,并更新_speedTestResult
* @param status 获取buffer和下载信息
*/
private _startTesting(status: RealtimeStatus) {
Log.v(tag, `start speed testing on index: ${this._current + 1}`);
const lastDownloadSize = status.downloadSize();
const testedBitrate = this._levels[this._current + 1].bitrate;
this._speedTester.start(
{ url: this._levels[this._current + 1].url, timeout: this._conf.speedTestTimeoutMs },
{
onEnd: (context: SpeedTestContext, result: SpeedTestResult) => {
const originalDownloadSize = status.downloadSize() - lastDownloadSize;
if (result.succeeded && result.duration > 0 && result.firstPackageDuration > 0) {
const testedSpeed = (originalDownloadSize + result.loaded) * 8 / result.duration;
Log.v(tag, `testSpeed: ${testedSpeed.toFixed(0)}`);
if (testedSpeed >= testedBitrate) {
this._generatedSpeed = testedBitrate;
}
}
Log.v(tag, `succeeded: ${result.succeeded}, firstPackageDuration: ${result.firstPackageDuration}, originalDownloadSize: ${originalDownloadSize}, downloadSize: ${result.loaded}, downloadTime: ${result.duration}`)
}
}
);
}
/**
* 设置码率列表中的清晰度是否可用
* @param list 码率index列表
*/
public setAvailableBitrates(list: number[]): void { }
/**
* 获取下一个清晰度
* @returns {number} 下个清晰度index
*/
public get nextLevel(): number {
Log.v(tag, `nextLevel: ${this._next}`);
return this._next;
}
/**
* 收到关键帧
* @param buffered buffer长度(秒)
* @param size 下载长度
* @param time 下载耗时(秒)
*/
public onGOP(buffered: number, size: number, time: number): void {
// Byte/s -> kbps: {x} * 1000 * 8 / 1024;
let speed = (size / Math.max(time, 0.05)) * 8 / 1024;
Log.v(tag, `buffered: ${buffered.toFixed(2)}, size: ${size}, time: ${time.toFixed(2)}`)
this._next = this._nextRateIndex(speed, buffered);
}
/**
* 当开始加载新流
* @param index 清晰度index
*/
public onLevelLoad(index: number): void {
this._current = Math.max(0, index);
}
public destroy(): void {
this._speedTester.destroy();
clearInterval(this._timer);
}
private _quantization(speed: number): number {
let index = 0;
for (let i = this._levels.length - 1; i >= 0; i--) {
if (speed >= this._levels[i].bitrate) {
index = i;
break;
}
}
return index;
}
/**
* 计算下一个使用的码率
* @param speed 下载速度 kbps
* @param buffered 当前buffer ms
*/
private _nextRateIndex(speed: number, buffered: number): number {
let index = this._nextRateBySpeedAndBuffered(speed, buffered);
if (index != this._current) {
this._stableBufferStartTime = performance.now() + this._conf.generateSpeedGapMs;
}
if (index < this._current) {
this._speedTester.cancel();
this._generatedSpeed = 0;
this._lastSpeed = speed;
this._pastBuffer = [buffered];
} else {
this._lastSpeed = this._getSmoothedSpeed(speed);
}
return index;
}
/**
* 获取平滑带宽
* @param speed 下载速度 kbps
*/
private _getSmoothedSpeed(speed: number) {
if (this._lastSpeed > 0) {
return speed * (1 - this._conf.smoothedSpeedRatio) + this._lastSpeed * this._conf.smoothedSpeedRatio;
}
return speed;
}
private _getPredictedBuffer(buffered: number) {
const pastBuffer = Math.max(...this._pastBuffer);
return buffered + (buffered - pastBuffer);
}
private _getBufferSpeed(buffered: number) {
const pastBuffer = Math.max(...this._pastBuffer);
const bufferSpeedRatio = 1 + (buffered - pastBuffer) / pastBuffer;
return bufferSpeedRatio * this._levels[this._current].bitrate;
}
private _isSpeedTooSmall(speed: number) {
return speed / this._levels[this._current].bitrate < this._conf.smallSpeedToBitrateRatio;
}
private _isSpeedEnough(speed: number) {
return speed / this._levels[this._current].bitrate > this._conf.enoughSpeedToBitrateRatio;
}
/**
* 根据下载速度和buffer长度计算下一个码率
* @param speed 下载速度 kbps
* @param buffered 当前buffer ms
*/
private _nextRateBySpeedAndBuffered(
speed: number,
buffered: number
): number {
const bufferSpeed = this._getBufferSpeed(buffered);
const smoothedSpeed = this._getSmoothedSpeed(speed);
Log.v(tag, `gopSpeed: ${speed.toFixed(0)}, smoothedSpeed: ${smoothedSpeed.toFixed(0)}`);
const predictedBuffered = this._getPredictedBuffer(buffered);
Log.v(tag, `bufferSpeed: ${bufferSpeed.toFixed(0)}, predictedBuffered: ${predictedBuffered.toFixed(1)}`);
let nextIndex = this._current;
if (predictedBuffered < this._conf.bufferLowerLimitSecond || this._isSpeedTooSmall(bufferSpeed)) {
nextIndex = Math.min(this._current, this._quantization(bufferSpeed));
} else if (this._isSpeedEnough(bufferSpeed)) {
if (this._generatedSpeed > 0) {
Log.i(tag, `generatedSpeed used`);
nextIndex = this._quantization(this._generatedSpeed);
this._generatedSpeed = 0;
} else {
nextIndex = this._quantization(smoothedSpeed * this._conf.smoothedSpeedUtilizationRatio);
}
nextIndex = Math.min(this._current + 1, Math.max(nextIndex, this._current));
}
return nextIndex;
}
}
export default AbrAlgorithmSimple; | the_stack |
import createCancelToken, { CancelToken } from '@avocode/cancel-token'
import { fetch, get, getStream, post, postMultipart } from './utils/fetch'
import { sleep } from './utils/sleep'
import cplus from 'cplus'
import PQueue from 'p-queue'
import { ApiDesign } from './api-design'
import { ApiDesignExport } from './api-design-export'
import { OpenDesignApiError } from './open-design-api-error'
import type { ReadStream } from 'fs'
import type { ArtboardId } from '@opendesign/octopus-reader'
import type { components } from 'open-design-api-types'
import type { IOpenDesignApi } from './types/ifaces'
export type DesignExportId = components['schemas']['DesignExportId']
export type DesignExportTargetFormatEnum = components['schemas']['DesignExportTargetFormatEnum']
export type Design = components['schemas']['Design']
export type DesignId = components['schemas']['DesignId']
export type DesignImportFormatEnum = components['schemas']['DesignImportFormatEnum']
export type DesignSummary = components['schemas']['DesignSummary']
export type DesignVersionId = components['schemas']['DesignVersionId']
export type OctopusDocument = components['schemas']['OctopusDocument']
export class OpenDesignApi implements IOpenDesignApi {
private _apiRoot: string
private _token: string
private _console: Console
private _destroyTokenController = createCancelToken()
private _requestQueue = new PQueue({ concurrency: 10 })
constructor(params: {
apiRoot: string
token: string
console?: Console | null
}) {
this._apiRoot = params.apiRoot
this._token = params.token
this._console = params.console || cplus.create()
}
getApiRoot(): string {
return this._apiRoot
}
_getAuthInfo(): { token: string } {
return { token: this._token }
}
destroy(): void {
this._destroyTokenController.cancel('The API has been destroyed.')
}
async getDesignList(options: {
cancelToken?: CancelToken | null
}): Promise<Array<ApiDesign>> {
const cancelToken = createCancelToken.race([
options.cancelToken,
this._destroyTokenController.token,
])
const res = await this._requestQueue.add(() =>
get(this._apiRoot, '/designs', {}, this._getAuthInfo(), {
console: this._console,
...options,
cancelToken,
})
)
if (res.statusCode !== 200) {
throw new OpenDesignApiError(res, 'Cannot fetch design list')
}
const designInfoList =
'designs' in res.body ? (res.body['designs'] as Array<Design>) : []
return designInfoList.map((designInfo) => {
return new ApiDesign(designInfo, {
openDesignApi: this,
})
})
}
async getDesignVersionList(
designId: DesignId,
options: {
cancelToken?: CancelToken | null
}
): Promise<Array<ApiDesign>> {
const cancelToken = createCancelToken.race([
options.cancelToken,
this._destroyTokenController.token,
])
const res = await this._requestQueue.add(() =>
get(
this._apiRoot,
'/designs/{design_id}/versions',
{ 'design_id': designId },
this._getAuthInfo(),
{
console: this._console,
...options,
cancelToken,
}
)
)
if (res.statusCode !== 200) {
throw new OpenDesignApiError(res, 'Cannot fetch design version list')
}
const designInfoList =
'design_versions' in res.body
? (res.body['design_versions'] as Array<Design>)
: []
return designInfoList.map((designInfo) => {
return new ApiDesign(designInfo, {
openDesignApi: this,
})
})
}
async getDesignById(
designId: DesignId,
options: {
designVersionId?: DesignVersionId | null
cancelToken?: CancelToken | null
} = {}
): Promise<ApiDesign> {
const cancelToken = createCancelToken.race([
options.cancelToken,
this._destroyTokenController.token,
])
const res = await this._requestQueue.add(() =>
options.designVersionId
? get(
this._apiRoot,
'/designs/{design_id}/versions/{version_id}',
{
'design_id': designId,
'version_id': options.designVersionId,
},
this._getAuthInfo(),
{
console: this._console,
...options,
cancelToken,
}
)
: get(
this._apiRoot,
'/designs/{design_id}',
{
'design_id': designId,
},
this._getAuthInfo(),
{
console: this._console,
...options,
cancelToken,
}
)
)
if (
res.statusCode === 401 ||
// @ts-expect-error 403 is not included in the spec but checking it just in case.
res.statusCode === 403
) {
this._console.error(
'OpenDesignApi#getDesignById()',
{ designId },
res.statusCode,
res.body
)
throw new OpenDesignApiError(
res,
'Cannot fetch design due to missing permissions'
)
}
const body = res.body
const design = 'status' in body ? body : null
if (!design) {
this._console.error(
'OpenDesignApi#getDesignById()',
{ designId },
res.statusCode,
res.body
)
throw new OpenDesignApiError(res, 'Cannot fetch design')
}
if (design['status'] === 'failed') {
throw new OpenDesignApiError(res, 'The design processing failed')
}
if (
res.statusCode === 202 ||
design['status'] !== 'done' ||
!('completed_at' in design)
) {
await sleep(1000)
cancelToken.throwIfCancelled()
return this.getDesignById(designId, options)
}
const apiDesign = new ApiDesign(design, {
openDesignApi: this,
})
return apiDesign
}
async getDesignSummary(
designId: DesignId,
options: {
designVersionId?: DesignVersionId | null
cancelToken?: CancelToken | null
} = {}
): Promise<DesignSummary> {
const cancelToken = createCancelToken.race([
options.cancelToken,
this._destroyTokenController.token,
])
const res = await this._requestQueue.add(() =>
options.designVersionId
? get(
this._apiRoot,
'/designs/{design_id}/versions/{version_id}/summary',
{
'design_id': designId,
'version_id': options.designVersionId,
},
this._getAuthInfo(),
{
console: this._console,
...options,
cancelToken,
}
)
: get(
this._apiRoot,
'/designs/{design_id}/summary',
{
'design_id': designId,
},
this._getAuthInfo(),
{
console: this._console,
...options,
cancelToken,
}
)
)
if (
res.statusCode === 401 ||
// @ts-expect-error 403 is not included in the spec but checking it just in case.
res.statusCode === 403
) {
this._console.error(
'OpenDesignApi#getDesignSummary()',
{ designId },
res.statusCode,
res.body
)
throw new OpenDesignApiError(
res,
'Cannot fetch design due to missing permissions'
)
}
const body = res.body
const designSummary = 'status' in body ? body : null
if (!designSummary) {
this._console.error(
'OpenDesignApi#getDesignSummary()',
{ designId },
res.statusCode,
res.body
)
throw new OpenDesignApiError(res, 'Cannot fetch design')
}
if (designSummary['status'] === 'failed') {
throw new OpenDesignApiError(res, 'The design processing failed')
}
if (
res.statusCode === 202 ||
designSummary['status'] !== 'done' ||
!('artboards' in designSummary)
) {
await sleep(1000)
cancelToken.throwIfCancelled()
return this.getDesignSummary(designId, options)
}
return designSummary
}
async importDesignFile(
designFileStream: ReadStream,
options: {
designId?: DesignId | null
format?: DesignImportFormatEnum
cancelToken?: CancelToken | null
} = {}
): Promise<ApiDesign> {
const cancelToken = createCancelToken.race([
options.cancelToken,
this._destroyTokenController.token,
])
const res = await this._requestQueue.add(() =>
options.designId
? postMultipart(
this._apiRoot,
'/designs/{design_id}/versions/upload',
{ 'design_id': options.designId },
{
'file': designFileStream,
...(options.format ? { 'format': options.format } : {}),
},
this._getAuthInfo(),
{
console: this._console,
cancelToken,
}
)
: postMultipart(
this._apiRoot,
'/designs/upload',
{},
{
'file': designFileStream,
...(options.format ? { 'format': options.format } : {}),
},
this._getAuthInfo(),
{
console: this._console,
cancelToken,
}
)
)
if (res.statusCode !== 201) {
this._console.error(
'OpenDesignApi#importDesignFile()',
res.statusCode,
res.body
)
throw new OpenDesignApiError(res, 'Cannot import design')
}
const design = res.body['design']
// NOTE: Waits for the design to become fully processed.
return this.getDesignById(design['id'], {
designVersionId: design['version_id'],
})
}
async importDesignLink(
url: string,
options: {
designId?: DesignId | null
format?: DesignImportFormatEnum
cancelToken?: CancelToken | null
} = {}
): Promise<ApiDesign> {
const cancelToken = createCancelToken.race([
options.cancelToken,
this._destroyTokenController.token,
])
const res = await this._requestQueue.add(() =>
options.designId
? post(
this._apiRoot,
'/designs/{design_id}/versions/link',
{ 'design_id': options.designId },
{
'url': url,
...(options.format ? { 'format': options.format } : {}),
},
this._getAuthInfo(),
{
console: this._console,
cancelToken,
}
)
: post(
this._apiRoot,
'/designs/link',
{},
{
'url': url,
...(options.format ? { 'format': options.format } : {}),
},
this._getAuthInfo(),
{
console: this._console,
cancelToken,
}
)
)
if (res.statusCode !== 201) {
this._console.error(
'OpenDesignApi#importDesignLink()',
res.statusCode,
res.body
)
throw new OpenDesignApiError(res, 'Cannot import design')
}
const design = res.body['design']
// NOTE: Waits for the design to become fully processed.
return this.getDesignById(design['id'], {
designVersionId: design['version_id'],
})
}
async importFigmaDesignLink(params: {
designId?: DesignId | null
figmaFileKey: string
figmaToken?: string | null
figmaIds?: Array<string> | null
name?: string | null
cancelToken?: CancelToken | null
}): Promise<ApiDesign> {
const cancelToken = createCancelToken.race([
params.cancelToken,
this._destroyTokenController.token,
])
const res = await this._requestQueue.add(() =>
params.designId
? post(
this._apiRoot,
'/designs/{design_id}/versions/figma-link',
{ 'design_id': params.designId },
{
'figma_filekey': params.figmaFileKey,
...(params.figmaToken
? { 'figma_token': params.figmaToken }
: {}),
...(params.figmaIds ? { 'figma_ids': params.figmaIds } : {}),
...(params.name ? { 'design_name': params.name } : {}),
},
this._getAuthInfo(),
{
console: this._console,
cancelToken,
}
)
: post(
this._apiRoot,
'/designs/figma-link',
{},
{
'figma_filekey': params.figmaFileKey,
...(params.figmaToken
? { 'figma_token': params.figmaToken }
: {}),
...(params.figmaIds ? { 'figma_ids': params.figmaIds } : {}),
...(params.name ? { 'design_name': params.name } : {}),
},
this._getAuthInfo(),
{
console: this._console,
cancelToken,
}
)
)
const figmaTokenErrorData =
res.statusCode === 409 ? res.body['error'] : null
if (
figmaTokenErrorData &&
figmaTokenErrorData['code'] === 'FigmaTokenNotProvided'
) {
this._console.warn(
`Figma is not connected; you can connect your Figma account at ${figmaTokenErrorData['settings_url']}`
)
}
if (res.statusCode !== 201) {
this._console.error(
'OpenDesignApi#importFigmaDesignLink()',
res.statusCode,
res.body
)
throw new OpenDesignApiError(res, 'Cannot import design')
}
const design = res.body['design']
// NOTE: Waits for the design to become fully processed.
return this.getDesignById(design['id'], {
designVersionId: design['version_id'],
})
}
async importFigmaDesignLinkWithExports(params: {
figmaFileKey: string
figmaToken?: string | null
figmaIds?: Array<string> | null
name?: string | null
exports: Array<{ format: DesignExportTargetFormatEnum }>
cancelToken?: CancelToken | null
}): Promise<{ design: ApiDesign; exports: Array<ApiDesignExport> }> {
const cancelToken = createCancelToken.race([
params.cancelToken,
this._destroyTokenController.token,
])
const res = await this._requestQueue.add(() =>
post(
this._apiRoot,
'/designs/figma-link',
{},
{
'figma_filekey': params.figmaFileKey,
'exports': params.exports,
...(params.figmaToken ? { 'figma_token': params.figmaToken } : {}),
...(params.figmaIds ? { 'figma_ids': params.figmaIds } : {}),
...(params.name ? { 'design_name': params.name } : {}),
},
this._getAuthInfo(),
{
console: this._console,
cancelToken,
}
)
)
const figmaTokenErrorData =
res.statusCode === 409 ? res.body['error'] : null
if (
figmaTokenErrorData &&
figmaTokenErrorData['code'] === 'FigmaTokenNotProvided'
) {
this._console.warn(
`Figma is not connected; you can connect your Figma account at ${figmaTokenErrorData['settings_url']}`
)
}
if (res.statusCode !== 201) {
this._console.error(
'OpenDesignApi#importFigmaDesignLinkWithExports()',
res.statusCode,
res.body
)
throw new OpenDesignApiError(res, 'Cannot import design')
}
const design = res.body['design']
return {
// NOTE: Waits for the design to become fully processed.
design: await this.getDesignById(design['id'], {
designVersionId: design['version_id'],
}),
exports: res.body['exports'].map((designExportData) => {
return new ApiDesignExport(designExportData, {
designId: design['id'],
openDesignApi: this,
})
}),
}
}
async getDesignArtboardContent(
designId: DesignId,
artboardId: ArtboardId,
options: {
designVersionId?: DesignVersionId | null
cancelToken?: CancelToken | null
} = {}
): Promise<OctopusDocument> {
const cancelToken = createCancelToken.race([
options.cancelToken,
this._destroyTokenController.token,
])
const res = await this._requestQueue.add(() =>
options.designVersionId
? get(
this._apiRoot,
'/designs/{design_id}/versions/{version_id}/artboards/{artboard_id}/content',
{
'design_id': designId,
'version_id': options.designVersionId,
'artboard_id': artboardId,
},
this._getAuthInfo(),
{
console: this._console,
...options,
cancelToken,
}
)
: get(
this._apiRoot,
'/designs/{design_id}/artboards/{artboard_id}/content',
{ 'design_id': designId, 'artboard_id': artboardId },
this._getAuthInfo(),
{
console: this._console,
...options,
cancelToken,
}
)
)
if (res.statusCode !== 200 && res.statusCode !== 202) {
this._console.error(
'OpenDesignApi#getDesignArtboardContent()',
{ designId },
res.statusCode,
res.body
)
throw new OpenDesignApiError(res, 'Cannot fetch artboard content')
}
if (res.statusCode === 202) {
await sleep(1000)
cancelToken.throwIfCancelled()
return this.getDesignArtboardContent(designId, artboardId, options)
}
return res.body
}
async getDesignArtboardContentJsonStream(
designId: DesignId,
artboardId: ArtboardId,
options: {
designVersionId?: DesignVersionId | null
cancelToken?: CancelToken | null
} = {}
): Promise<NodeJS.ReadableStream> {
const cancelToken = createCancelToken.race([
options.cancelToken,
this._destroyTokenController.token,
])
const res = await this._requestQueue.add(() =>
options.designVersionId
? getStream(
this._apiRoot,
'/designs/{design_id}/versions/{version_id}/artboards/{artboard_id}/content',
{
'design_id': designId,
'version_id': options.designVersionId,
'artboard_id': artboardId,
},
this._getAuthInfo(),
{
console: this._console,
...options,
cancelToken,
}
)
: getStream(
this._apiRoot,
'/designs/{design_id}/artboards/{artboard_id}/content',
{ 'design_id': designId, 'artboard_id': artboardId },
this._getAuthInfo(),
{
console: this._console,
...options,
cancelToken,
}
)
)
if (res.statusCode !== 200 && res.statusCode !== 202) {
this._console.error(
'OpenDesignApi#getDesignArtboardContentJsonStream()',
{ designId },
res
)
throw new OpenDesignApiError(res, 'Cannot fetch artboard content')
}
if (res.statusCode === 202) {
await sleep(1000)
cancelToken?.throwIfCancelled()
return this.getDesignArtboardContentJsonStream(
designId,
artboardId,
options
)
}
return res.stream
}
async exportDesign(
designId: DesignId,
params: {
format: DesignExportTargetFormatEnum
cancelToken?: CancelToken | null
}
): Promise<ApiDesignExport> {
const cancelToken = createCancelToken.race([
params.cancelToken,
this._destroyTokenController.token,
])
const res = await this._requestQueue.add(() =>
post(
this._apiRoot,
'/designs/{design_id}/exports',
{ 'design_id': designId },
{ 'format': params.format },
this._getAuthInfo(),
{
console: this._console,
cancelToken,
}
)
)
if (res.statusCode !== 201) {
this._console.error(
'OpenDesignApi#exportDesign()',
{ designId, ...params },
res
)
throw new OpenDesignApiError(res, 'Cannot export the design')
}
if (res.body['status'] === 'failed') {
throw new OpenDesignApiError(res, 'Design export failed')
}
return new ApiDesignExport(res.body, {
designId,
openDesignApi: this,
})
}
async getDesignExportById(
designId: DesignId,
designExportId: DesignExportId,
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<ApiDesignExport> {
const cancelToken = createCancelToken.race([
options.cancelToken,
this._destroyTokenController.token,
])
const res = await this._requestQueue.add(() =>
get(
this._apiRoot,
'/designs/{design_id}/exports/{export_id}',
{ 'design_id': designId, 'export_id': designExportId },
this._getAuthInfo(),
{
console: this._console,
...options,
cancelToken,
}
)
)
if (res.statusCode !== 200) {
this._console.error(
'OpenDesignApi#getDesignExportById()',
{ designId },
res
)
throw new OpenDesignApiError(res, 'Cannot fetch design export info')
}
if (res.body['status'] === 'failed') {
throw new OpenDesignApiError(res, 'Design export failed')
}
return new ApiDesignExport(res.body, {
designId,
openDesignApi: this,
})
}
async getDesignExportResultStream(
designId: DesignId,
designExportId: DesignExportId,
options: {
designVersionId?: DesignVersionId | null
cancelToken?: CancelToken | null
} = {}
): Promise<NodeJS.ReadableStream> {
const designExport = await this.getDesignExportById(
designId,
designExportId,
options
)
return designExport.getResultStream()
}
async getDesignBitmapAssetStream(
designId: DesignId,
bitmapKey: string,
options: {
designVersionId?: DesignVersionId | null
cancelToken?: CancelToken | null
} = {}
): Promise<NodeJS.ReadableStream> {
const absolute = /^https?:\/\//.test(bitmapKey)
if (!absolute) {
throw new Error('Relative asset paths are not supported')
}
const cancelToken = createCancelToken.race([
options.cancelToken,
this._destroyTokenController.token,
])
const res = await this._requestQueue.add(() =>
fetch(bitmapKey, {
cancelToken,
})
)
if (res.status !== 200 || !res.body) {
this._console.debug('OpenDesignApi#getDesignBitmapAssetStream()', {
bitmapKey,
statusCode: res.status,
})
throw new Error('Asset not available')
}
return res.body
}
} | the_stack |
import 'chrome://resources/cr_elements/cr_drawer/cr_drawer.js';
import 'chrome://resources/cr_elements/cr_toolbar/cr_toolbar.js';
import 'chrome://resources/cr_elements/cr_toolbar/cr_toolbar_search_field.js';
import 'chrome://resources/cr_elements/cr_page_host_style_css.js';
import 'chrome://resources/cr_elements/icons.m.js';
import 'chrome://resources/cr_elements/shared_vars_css.m.js';
import 'chrome://resources/polymer/v3_0/paper-styles/color.js';
import '../icons.js';
import '../settings_main/settings_main.js';
import '../settings_menu/settings_menu.js';
import '../settings_shared_css.js';
import '../settings_vars_css.js';
import {CrContainerShadowMixin, CrContainerShadowMixinInterface} from 'chrome://resources/cr_elements/cr_container_shadow_mixin.js';
import {CrDrawerElement} from 'chrome://resources/cr_elements/cr_drawer/cr_drawer.js';
import {CrToolbarElement} from 'chrome://resources/cr_elements/cr_toolbar/cr_toolbar.js';
import {CrToolbarSearchFieldElement} from 'chrome://resources/cr_elements/cr_toolbar/cr_toolbar_search_field.js';
import {FindShortcutMixin, FindShortcutMixinInterface} from 'chrome://resources/cr_elements/find_shortcut_mixin.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {isChromeOS} from 'chrome://resources/js/cr.m.js';
import {listenOnce} from 'chrome://resources/js/util.m.js';
import {Debouncer, DomIf, html, PolymerElement, timeOut} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {resetGlobalScrollTargetForTesting, setGlobalScrollTarget} from '../global_scroll_target_mixin.js';
import {loadTimeData} from '../i18n_setup.js';
import {PageVisibility, pageVisibility} from '../page_visibility.js';
import {SettingsPrefsElement} from '../prefs/prefs.js';
import {routes} from '../route.js';
import {Route, RouteObserverMixin, RouteObserverMixinInterface, Router} from '../router.js';
import {SettingsMainElement} from '../settings_main/settings_main.js';
import {SettingsMenuElement} from '../settings_menu/settings_menu.js';
declare global {
interface HTMLElementEventMap {
'scroll-to-top': CustomEvent<{top: number, callback: () => void}>;
'scroll-to-bottom': CustomEvent<{bottom: number, callback: () => void}>;
'refresh-pref': CustomEvent<string>;
}
interface Window {
CrPolicyStrings: {[key: string]: string},
}
}
export interface SettingsUiElement {
$: {
container: HTMLElement,
drawer: CrDrawerElement,
drawerTemplate: DomIf,
leftMenu: SettingsMenuElement,
main: SettingsMainElement,
toolbar: CrToolbarElement,
prefs: SettingsPrefsElement,
};
}
const SettingsUiElementBase = RouteObserverMixin(CrContainerShadowMixin(
FindShortcutMixin(PolymerElement))) as {
new (): PolymerElement & RouteObserverMixinInterface &
FindShortcutMixinInterface & CrContainerShadowMixinInterface
};
export class SettingsUiElement extends SettingsUiElementBase {
static get is() {
return 'settings-ui';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* Preferences state.
*/
prefs: Object,
advancedOpenedInMain_: {
type: Boolean,
value: false,
notify: true,
observer: 'onAdvancedOpenedInMainChanged_',
},
advancedOpenedInMenu_: {
type: Boolean,
value: false,
notify: true,
observer: 'onAdvancedOpenedInMenuChanged_',
},
toolbarSpinnerActive_: {
type: Boolean,
value: false,
},
narrow_: {
type: Boolean,
observer: 'onNarrowChanged_',
},
pageVisibility_: {type: Object, value: pageVisibility},
lastSearchQuery_: {
type: String,
value: '',
},
};
}
private advancedOpenedInMain_: boolean;
private advancedOpenedInMenu_: boolean;
private toolbarSpinnerActive_: boolean;
private narrow_: boolean;
private pageVisibility_: PageVisibility;
private lastSearchQuery_: string;
private debouncer_: Debouncer|null = null;
constructor() {
super();
Router.getInstance().initializeRouteFromUrl();
}
ready() {
super.ready();
// Lazy-create the drawer the first time it is opened or swiped into view.
listenOnce(this.$.drawer, 'cr-drawer-opening', () => {
this.$.drawerTemplate.if = true;
});
window.addEventListener('popstate', () => {
this.$.drawer.cancel();
});
window.CrPolicyStrings = {
controlledSettingExtension:
loadTimeData.getString('controlledSettingExtension'),
controlledSettingExtensionWithoutName:
loadTimeData.getString('controlledSettingExtensionWithoutName'),
controlledSettingPolicy:
loadTimeData.getString('controlledSettingPolicy'),
controlledSettingRecommendedMatches:
loadTimeData.getString('controlledSettingRecommendedMatches'),
controlledSettingRecommendedDiffers:
loadTimeData.getString('controlledSettingRecommendedDiffers'),
// <if expr="chromeos">
controlledSettingShared:
loadTimeData.getString('controlledSettingShared'),
controlledSettingWithOwner:
loadTimeData.getString('controlledSettingWithOwner'),
controlledSettingNoOwner:
loadTimeData.getString('controlledSettingNoOwner'),
controlledSettingParent:
loadTimeData.getString('controlledSettingParent'),
controlledSettingChildRestriction:
loadTimeData.getString('controlledSettingChildRestriction'),
// </if>
};
this.addEventListener('show-container', () => {
this.$.container.style.visibility = 'visible';
});
this.addEventListener('hide-container', () => {
this.$.container.style.visibility = 'hidden';
});
this.addEventListener('refresh-pref', this.onRefreshPref_.bind(this));
}
connectedCallback() {
super.connectedCallback();
document.documentElement.classList.remove('loading');
setTimeout(function() {
chrome.send(
'metricsHandler:recordTime',
['Settings.TimeUntilInteractive', window.performance.now()]);
});
// Preload bold Roboto so it doesn't load and flicker the first time used.
// https://github.com/microsoft/TypeScript/issues/13569
(document as any).fonts.load('bold 12px Roboto');
setGlobalScrollTarget(this.$.container);
const scrollToTop = (top: number) => new Promise<void>(resolve => {
if (this.$.container.scrollTop === top) {
resolve();
return;
}
// When transitioning back to main page from a subpage on ChromeOS,
// using 'smooth' scroll here results in the scroll changing to whatever
// is last value of |top|. This happens even after setting the scroll
// position the UI or programmatically.
const behavior = isChromeOS ? 'auto' : 'smooth';
this.$.container.scrollTo({top: top, behavior: behavior});
const onScroll = () => {
this.debouncer_ =
Debouncer.debounce(this.debouncer_, timeOut.after(75), () => {
this.$.container.removeEventListener('scroll', onScroll);
resolve();
});
};
this.$.container.addEventListener('scroll', onScroll);
});
this.addEventListener(
'scroll-to-top',
(e: CustomEvent<{top: number, callback: () => void}>) => {
scrollToTop(e.detail.top).then(e.detail.callback);
});
this.addEventListener(
'scroll-to-bottom',
(e: CustomEvent<{bottom: number, callback: () => void}>) => {
scrollToTop(e.detail.bottom - this.$.container.clientHeight)
.then(e.detail.callback);
});
}
disconnectedCallback() {
super.disconnectedCallback();
Router.getInstance().resetRouteForTesting();
resetGlobalScrollTargetForTesting();
}
currentRouteChanged(route: Route) {
if (document.documentElement.hasAttribute('enable-branding-update')) {
if (route.depth <= 1) {
// Main page uses scroll position to determine whether a shadow should
// be shown.
this.enableShadowBehavior(true);
} else if (!route.isNavigableDialog) {
// Sub-pages always show the top shadow, regardless of scroll position.
this.enableShadowBehavior(false);
this.showDropShadows();
}
}
const urlSearchQuery =
Router.getInstance().getQueryParameters().get('search') || '';
if (urlSearchQuery === this.lastSearchQuery_) {
return;
}
this.lastSearchQuery_ = urlSearchQuery;
const toolbar =
this.shadowRoot!.querySelector<CrToolbarElement>('cr-toolbar')!;
const searchField = toolbar.getSearchField();
// If the search was initiated by directly entering a search URL, need to
// sync the URL parameter to the textbox.
if (urlSearchQuery !== searchField.getValue()) {
// Setting the search box value without triggering a 'search-changed'
// event, to prevent an unnecessary duplicate entry in |window.history|.
searchField.setValue(urlSearchQuery, true /* noEvent */);
}
this.$.main.searchContents(urlSearchQuery);
}
// Override FindShortcutMixin methods.
handleFindShortcut(modalContextOpen: boolean) {
if (modalContextOpen) {
return false;
}
this.shadowRoot!.querySelector<CrToolbarElement>('cr-toolbar')!
.getSearchField()
.showAndFocus();
return true;
}
// Override FindShortcutMixin methods.
searchInputHasFocus() {
return this.shadowRoot!.querySelector<CrToolbarElement>('cr-toolbar')!
.getSearchField()
.isSearchFocused();
}
private onRefreshPref_(e: CustomEvent<string>) {
return this.$.prefs.refresh(e.detail);
}
/**
* Handles the 'search-changed' event fired from the toolbar.
*/
private onSearchChanged_(e: CustomEvent<string>) {
const query = e.detail;
Router.getInstance().navigateTo(
routes.BASIC,
query.length > 0 ?
new URLSearchParams('search=' + encodeURIComponent(query)) :
undefined,
/* removeSearch */ true);
}
/**
* Called when a section is selected.
*/
private onIronActivate_() {
this.$.drawer.close();
}
private onMenuButtonTap_() {
this.$.drawer.toggle();
}
/**
* When this is called, The drawer animation is finished, and the dialog no
* longer has focus. The selected section will gain focus if one was
* selected. Otherwise, the drawer was closed due being canceled, and the
* main settings container is given focus. That way the arrow keys can be
* used to scroll the container, and pressing tab focuses a component in
* settings.
*/
private onMenuClose_() {
if (!this.$.drawer.wasCanceled()) {
// If a navigation happened, MainPageMixin#currentRouteChanged
// handles focusing the corresponding section.
return;
}
// Add tab index so that the container can be focused.
this.$.container.setAttribute('tabindex', '-1');
this.$.container.focus();
listenOnce(this.$.container, ['blur', 'pointerdown'], () => {
this.$.container.removeAttribute('tabindex');
});
}
private onAdvancedOpenedInMainChanged_() {
if (this.advancedOpenedInMain_) {
this.advancedOpenedInMenu_ = true;
}
}
private onAdvancedOpenedInMenuChanged_() {
if (this.advancedOpenedInMenu_) {
this.advancedOpenedInMain_ = true;
}
}
private onNarrowChanged_() {
if (this.$.drawer.open && !this.narrow_) {
this.$.drawer.close();
}
const focusedElement = this.shadowRoot!.activeElement;
if (this.narrow_ && focusedElement === this.$.leftMenu) {
// If changed from non-narrow to narrow and the focus was on the left
// menu, move focus to the button that opens the drawer menu.
this.$.toolbar.focusMenuButton();
} else if (!this.narrow_ && this.$.toolbar.isMenuFocused()) {
// If changed from narrow to non-narrow and the focus was on the button
// that opens the drawer menu, move focus to the left menu.
this.$.leftMenu.focusFirstItem();
} else if (
!this.narrow_ &&
focusedElement === this.shadowRoot!.querySelector('#drawerMenu')) {
// If changed from narrow to non-narrow and the focus was in the drawer
// menu, wait for the drawer to close and then move focus on the left
// menu. The drawer has a dialog element in it so moving focus to an
// element outside the dialog while it is open will not work.
const boundCloseListener = () => {
this.$.leftMenu.focusFirstItem();
this.$.drawer.removeEventListener('close', boundCloseListener);
};
this.$.drawer.addEventListener('close', boundCloseListener);
}
}
/**
* Only used in tests.
*/
getAdvancedOpenedInMainForTest(): boolean {
return this.advancedOpenedInMain_;
}
/**
* Only used in tests.
*/
getAdvancedOpenedInMenuForTest(): boolean {
return this.advancedOpenedInMenu_;
}
}
customElements.define(SettingsUiElement.is, SettingsUiElement); | the_stack |
import React from "react";
import {IContext, ScrollConsumer, ScrollProvider} from "@stickyroll/context";
import {Tracker} from "@stickyroll/tracker";
import {classNames, hashCode} from "@stickyroll/utils";
import {version} from "../package.json";
/**
* @typedef {function} TRender<T>
* @param {IContext} context
* @returns {T}
*/
export type TRender<T> = (context: IContext) => T;
/**
* @typedef {TRender<any>} TRenderer
* @param {IContext} context
* @returns {any}
*/
export type TRenderer = TRender<any>;
/**
* @typedef {TRender<any>} TChild
* @param {IContext} context
* @returns {any}
*/
export type TChild = TRender<any>;
/**
* @typedef {function} TPageHandler
* @param {number} page
* @returns {void}
*/
export type TPageHandler = (page: number) => void;
/**
* @typedef {function} TAsyncPageHandler
* @param {number} page
* @returns {Promise<void>}
*/
export type TAsyncPageHandler = (page: number) => Promise<void>;
/**
* @typedef {function} TProgressHandler
* @returns {void}
*/
export type TProgressHandler = () => void;
/**
* @typedef {function} TAsyncProgressHandler
* @returns {Promise<void>}
*/
export type TAsyncProgressHandler = () => Promise<void>;
/**
* @typedef {object} IFrameDefaultProps
* @property {number} factor
*/
export interface IFrameDefaultProps {
factor: number;
}
/**
* @typedef {object} IFrameProps
* @extends {IFrameDefaultProps}
* @property {string} [anchors]
* @property {TChild} [children]
* @property {string} [className]
* @property {number} [factor]
* @property {TProgressHandler | TAsyncProgressHandler} [onEnd]
* @property {TPageHandler | TAsyncPageHandler} [onPage]
* @property {TProgressHandler | TAsyncProgressHandler} [onStart]
* @property {number|Array<any>} pages
* @property {TRenderer} [render]
* @property {number} [throttle]
*/
export interface IFrameProps {
anchors?: string;
children?: TChild;
className?: string;
factor?: number;
onEnd?: TProgressHandler | TAsyncProgressHandler;
onPage?: TPageHandler | TAsyncPageHandler;
onStart?: TProgressHandler | TAsyncProgressHandler;
pages: number | Array<any>;
render?: TRenderer;
throttle?: number;
}
/**
* @typedef {object} IFrameState
* @property {number} page
* @property {number} scrollOffset
* @property {number} scrollY
*/
export interface IFrameState {
page: number;
scrollOffset: number;
scrollY: number;
}
export interface ISelectors {
wrapper: string;
overlay: string;
target: string;
targets: string;
skip: string;
}
/**
* Styles for the core frame
*/
const styles: ISelectors = {
overlay: `
height: 100vh;
position: -webkit-sticky;
position: sticky;
top: 0;
width: 100%;
`,
skip: `
position: absolute;
top: 100%;
`,
target: `
display: block;
height: 100vh;
`,
targets: `
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
`,
wrapper: `
position: relative;
margin: 0;
`
};
/**
* Hashed classNames for styling
*/
const hashSelectors: ISelectors = {
wrapper: hashCode(`/* stickyroll-version: ${version} */\n${styles.wrapper}`),
overlay: hashCode(`/* stickyroll-version: ${version} */\n${styles.overlay}`),
targets: hashCode(`/* stickyroll-version: ${version} */\n${styles.targets}`),
target: hashCode(`/* stickyroll-version: ${version} */\n${styles.target}`),
skip: hashCode(`/* stickyroll-version: ${version} */\n${styles.skip}`)
};
/**
* Hashed and prefixed classNames for styling
* (currently not in use, keep for future scope safety)
*/
const hashNSSelectors: ISelectors = {
wrapper: `sr-${hashCode(hashSelectors.wrapper)}`,
overlay: `sr-${hashCode(hashSelectors.overlay)}`,
targets: `sr-${hashCode(hashSelectors.targets)}`,
target: `sr-${hashCode(hashSelectors.target)}`,
skip: `sr-${hashCode(hashSelectors.skip)}`
};
/**
* Hashed and hash-prefixed classNames combined
*/
export const hashClassNames: ISelectors = {
wrapper: classNames(hashNSSelectors.wrapper, hashSelectors.wrapper),
overlay: classNames(hashNSSelectors.overlay, hashSelectors.overlay),
targets: classNames(hashNSSelectors.targets, hashSelectors.targets),
target: classNames(hashNSSelectors.target, hashSelectors.target),
skip: classNames(hashNSSelectors.skip, hashSelectors.skip)
};
/**
* Core styling required to display the component correctly
*/
export const CORE_STYLE: string = `
.${hashSelectors.wrapper}{${styles.wrapper}}
.${hashSelectors.overlay}{${styles.overlay}}
.${hashSelectors.targets}{${styles.targets}}
.${hashSelectors.target}{${styles.target}}
.${hashSelectors.skip}{${styles.skip}}
.${hashSelectors.wrapper}{${styles.wrapper}}
`
.replace(/\s+/g, "")
.replace(/;}/g, "}");
/**
* The style tag needed to display the component correctly
*/
export const CORE_STYLE_TAG: string = `<style data-stickyroll data-stickyroll-version="${version}">${CORE_STYLE}</style>`;
export type InjectCoreStyle = () => void;
/**
* Injects core styles for Stickyroll. This is the client side version.
* Stickyroll will inject these styles to ensure the correct behavior.
* @constructor
*/
const INJECT_CORE_STYLE: InjectCoreStyle = () => {
const existingStyle = document.head.querySelector("[data-stickyroll]");
if (Boolean(existingStyle)) {
const styleVersion = existingStyle.getAttribute("data-stickyroll-version");
if (styleVersion === version) {
document.head.appendChild(existingStyle);
return;
}
}
const style = document.createElement("style");
style.setAttribute("data-stickyroll", "");
style.setAttribute("data-stickyroll-version", `${version}`);
style.innerHTML = CORE_STYLE;
document.head.appendChild(style);
};
export class Frame extends React.Component<IFrameProps, IFrameState> {
/**
* @public
* @type {IFrameState}
*/
public state: IFrameState = {
page: 0,
scrollOffset: 0,
scrollY: 0
};
/**
* @private
* @type {React.RefObject<HTMLDivElement>}
*/
private tracker: React.RefObject<HTMLDivElement> = React.createRef();
/**
* @public
* @type {IFrameDefaultProps}
*/
public static get defaultProps(): IFrameDefaultProps {
return {
factor: 1
};
}
/**
* Write the current scrollPosition to the internal state when the component is mounted.
* This will allow getting the correct page and progress after mounting.
* @public
*/
public componentDidMount() {
Frame.injectStyle();
this.setState({
scrollY: window.scrollY
});
}
/* istanbul ignore next */
/**
* Call the onPage handler if it is defined every time the page changes.
* No initial call!
* @public
*/
public componentDidUpdate(oldProps, oldState) {
const {page, scrollOffset} = this.state;
if (oldState.page !== page) {
this.props.onPage && this.props.onPage(this.state.page);
}
if (oldState.scrollOffset !== scrollOffset) {
const zero = scrollOffset === 0;
const one = scrollOffset === 1;
const start = zero && page === 0;
const end = one && page === this.pageCount - 1;
if (start && this.props.onStart) {
this.props.onStart();
} else if (end && this.props.onEnd) {
this.props.onEnd();
}
}
}
/**
* Rendering can be configured in two different ways.
* 1. Using `children`:
* * uses context
* * supports context based plugins
* 2. Using `render`:
* * better performance
*
* The differences are based on the use of context. To allow context based plugins it is advised
* to use a child function. To improve performance the render property can be used (Plugins can still be used but
* must be configured manually)
* @public
*/
public render() {
const {render, children, anchors} = this.props;
// Test for either the render property or children to be defined as function.
// Render wins over children if both are defined. If neither is defined as function, a TypeError is thrown.
if (typeof render !== "function" && typeof children !== "function") {
throw new TypeError(`Either children or render needs to be defined as a function`);
}
const {page} = this.state;
const Wrapper = this.Wrapper;
// Convert the scrollOffset from percent to a timeline [0,1]
const progress = this.state.scrollOffset;
// const {innerHeight} = window;
// const clippedProgress = Math.round(progress * innerHeight) / innerHeight;
// Switch between context free and context based versions
switch (typeof render) {
case "function":
// Context free
return (
<Wrapper>
{render({
anchors,
page: page + 1,
pageIndex: page,
pages: this.pageCount,
progress
})}
</Wrapper>
);
// Context based
default:
return (
<ScrollProvider
value={{
anchors,
page: page + 1,
pageIndex: page,
pages: this.pageCount,
progress
}}>
<Wrapper>
<ScrollConsumer>{children}</ScrollConsumer>
</Wrapper>
</ScrollProvider>
);
}
}
public static injectStyle() {
INJECT_CORE_STYLE();
}
public static getStyleTag() {
return CORE_STYLE_TAG;
}
public static getStyle() {
return CORE_STYLE;
}
private get pageCount(): number {
const {pages} = this.props;
return Array.isArray(pages) ? (pages as Array<any>).length : (pages as number);
}
/**
* A Wrapper around the content to ensure the correct behavior during interaction.
* Renders a sticky container, an event-tracker and optionally anchor targets to allow deep-links.
* @constructor
* @private
* @type {React.FunctionComponent}
* @param props
* @return {ReactElement<any> | null}
*/
private Wrapper: React.FunctionComponent = ({children}) => (
<React.Fragment>
<Tracker onUpdate={this.handleUpdate} throttle={this.props.throttle} />
<div
className={classNames(hashClassNames.wrapper, this.props.className)}
ref={this.tracker}
style={this.wrapperStyle}>
{this.anchors}
<div className={hashClassNames.overlay}>{children}</div>
</div>
</React.Fragment>
);
/* istanbul ignore next */
/**
* Scroll handler to parse the page and progress from the scroll position.
* @private
* @param {number} scrollY
* @returns {void}
*/
private handleUpdate = (scrollY: number): void => {
if (!this.tracker || !this.tracker.current) {
return;
}
let page: number = 0;
let scrollOffset: number = 0;
const {top, bottom}: ClientRect = this.tracker.current.getBoundingClientRect();
const {factor} = this.props;
const {innerHeight = 0}: Window = window;
const touchedTop: boolean = top <= 0;
const touchedEnd: boolean = bottom <= innerHeight;
if (touchedTop && !touchedEnd) {
page = Math.max(
0,
Math.min(this.pageCount - 1, Math.floor((top * (-1 / factor)) / innerHeight))
);
scrollOffset = Math.max(
0,
Math.min(1, ((top * -1) % (innerHeight * factor)) / innerHeight / factor)
);
} else if (touchedEnd) {
page = this.pageCount - 1;
scrollOffset = 1;
}
this.setState({
page,
scrollOffset,
scrollY
});
};
/**
* @type {React.CSSProperties}
*/
private get wrapperStyle(): React.CSSProperties {
const {factor} = this.props;
const vh = this.pageCount * 100 * factor + 100;
return {
height: `${vh}vh`
};
}
/**
* If anchors are defined, a collection of spans with the correct IDs are provided.
* This allows to link or jump to a section or even skip the entire content.
* @type {React.ReactElement<HTMLDivElement> | null}
*/
private get anchors(): React.ReactElement<HTMLDivElement> | null {
const {anchors} = this.props;
if (!(typeof anchors === "string")) {
return null;
}
const {factor} = this.props;
const glue = anchors.length ? "/" : "";
const targets = Array(this.pageCount)
.fill(Boolean)
.map((x, i) => (
<span
id={`${anchors}${glue}${i + 1}`}
key={`${anchors}:${i + 1}`}
className={hashClassNames.target}
style={{
height: `${100 * factor}vh`
}}
/>
));
return (
<div className={hashClassNames.targets}>
{targets}
<span
id={`${anchors}${glue}${this.pageCount + 1}`}
className={hashClassNames.target}
/>
<span id={`${anchors}${glue}skip`} className={hashClassNames.skip} />
</div>
);
}
} | the_stack |
import {
expect as cdkExpect,
countResources,
haveResourceLike,
objectLike,
arrayWith,
countResourcesLike,
ABSENT,
} from '@aws-cdk/assert';
import {
BlockDeviceVolume, EbsDeviceVolumeType,
} from '@aws-cdk/aws-autoscaling';
import {
GenericWindowsImage,
InstanceClass,
InstanceSize,
InstanceType,
SubnetType,
Vpc,
} from '@aws-cdk/aws-ec2';
import {
ContainerImage,
} from '@aws-cdk/aws-ecs';
import { ManagedPolicy } from '@aws-cdk/aws-iam';
import { PrivateHostedZone } from '@aws-cdk/aws-route53';
import {
App,
Duration,
Expiration,
Fn,
Stack,
} from '@aws-cdk/core';
import { X509CertificatePem } from '../../core';
import { tagFields } from '../../core/lib/runtime-info';
import {
ConfigureSpotEventPlugin,
IRenderQueue,
IVersion,
RenderQueue,
Repository,
SpotEventPluginDisplayInstanceStatus,
SpotEventPluginLoggingLevel,
SpotEventPluginPreJobTaskMode,
SpotEventPluginSettings,
SpotEventPluginState,
SpotFleetResourceType,
VersionQuery,
} from '../lib';
import {
SpotEventPluginFleet,
} from '../lib/spot-event-plugin-fleet';
describe('ConfigureSpotEventPlugin', () => {
let stack: Stack;
let vpc: Vpc;
let region: string;
let renderQueue: IRenderQueue;
let version: IVersion;
let app: App;
let fleet: SpotEventPluginFleet;
let groupName: string;
const workerMachineImage = new GenericWindowsImage({
'us-east-1': 'ami-any',
});
beforeEach(() => {
region = 'us-east-1';
app = new App();
stack = new Stack(app, 'stack', {
env: {
region,
},
});
vpc = new Vpc(stack, 'Vpc');
version = new VersionQuery(stack, 'Version');
renderQueue = new RenderQueue(stack, 'RQ', {
vpc,
images: { remoteConnectionServer: ContainerImage.fromAsset(__dirname) },
repository: new Repository(stack, 'Repository', {
vpc,
version,
secretsManagementSettings: { enabled: false },
}),
trafficEncryption: { externalTLS: { enabled: false } },
version,
});
groupName = 'group_name1';
fleet = new SpotEventPluginFleet(stack, 'SpotFleet', {
vpc,
renderQueue: renderQueue,
deadlineGroups: [
groupName,
],
instanceTypes: [
InstanceType.of(InstanceClass.T2, InstanceSize.SMALL),
],
workerMachineImage,
maxCapacity: 1,
});
});
describe('creates a custom resource', () => {
test('with default spot event plugin properties', () => {
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleet,
],
});
// THEN
cdkExpect(stack).to(haveResourceLike('Custom::RFDK_ConfigureSpotEventPlugin', objectLike({
spotPluginConfigurations: objectLike({
AWSInstanceStatus: 'Disabled',
DeleteInterruptedSlaves: false,
DeleteTerminatedSlaves: false,
IdleShutdown: 10,
Logging: 'Standard',
PreJobTaskMode: 'Conservative',
Region: Stack.of(renderQueue).region,
ResourceTracker: true,
StaggerInstances: 50,
State: 'Global Enabled',
StrictHardCap: false,
}),
})));
});
test('with custom spot event plugin properties', () => {
// GIVEN
const configuration: SpotEventPluginSettings = {
awsInstanceStatus: SpotEventPluginDisplayInstanceStatus.EXTRA_INFO_0,
deleteEC2SpotInterruptedWorkers: true,
deleteSEPTerminatedWorkers: true,
idleShutdown: Duration.minutes(20),
loggingLevel: SpotEventPluginLoggingLevel.VERBOSE,
preJobTaskMode: SpotEventPluginPreJobTaskMode.NORMAL,
region: 'us-west-2',
enableResourceTracker: false,
maximumInstancesStartedPerCycle: 10,
state: SpotEventPluginState.DISABLED,
strictHardCap: true,
};
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleet,
],
configuration,
});
// THEN
cdkExpect(stack).to(haveResourceLike('Custom::RFDK_ConfigureSpotEventPlugin', objectLike({
spotPluginConfigurations: objectLike({
AWSInstanceStatus: 'ExtraInfo0',
DeleteInterruptedSlaves: true,
DeleteTerminatedSlaves: true,
IdleShutdown: 20,
Logging: 'Verbose',
PreJobTaskMode: 'Normal',
Region: 'us-west-2',
ResourceTracker: false,
StaggerInstances: 10,
State: 'Disabled',
StrictHardCap: true,
}),
})));
});
test('without spot fleets', () => {
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
});
// THEN
cdkExpect(stack).to(haveResourceLike('Custom::RFDK_ConfigureSpotEventPlugin', {
spotFleetRequestConfigurations: ABSENT,
}));
});
test('provides RQ connection parameters to custom resource', () => {
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleet,
],
});
// THEN
cdkExpect(stack).to(haveResourceLike('Custom::RFDK_ConfigureSpotEventPlugin', objectLike({
connection: objectLike({
hostname: stack.resolve(renderQueue.endpoint.hostname),
port: stack.resolve(renderQueue.endpoint.portAsString()),
protocol: stack.resolve(renderQueue.endpoint.applicationProtocol.toString()),
}),
})));
});
test('with default spot fleet request configuration', () => {
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleet,
],
});
const rfdkTag = tagFields(fleet);
// THEN
cdkExpect(stack).to(haveResourceLike('Custom::RFDK_ConfigureSpotEventPlugin', objectLike({
spotFleetRequestConfigurations: objectLike({
[groupName]: objectLike({
AllocationStrategy: fleet.allocationStrategy.toString(),
IamFleetRole: stack.resolve(fleet.fleetRole.roleArn),
LaunchSpecifications: arrayWith(
objectLike({
IamInstanceProfile: {
Arn: stack.resolve(fleet.instanceProfile.attrArn),
},
ImageId: fleet.imageId,
SecurityGroups: arrayWith(
objectLike({
GroupId: stack.resolve(fleet.securityGroups[0].securityGroupId),
}),
),
SubnetId: stack.resolve(Fn.join('', [vpc.privateSubnets[0].subnetId, ',', vpc.privateSubnets[1].subnetId])),
TagSpecifications: arrayWith(
objectLike({
ResourceType: 'instance',
Tags: arrayWith(
objectLike({
Key: rfdkTag.name,
Value: rfdkTag.value,
}),
),
}),
),
UserData: stack.resolve(Fn.base64(fleet.userData.render())),
InstanceType: fleet.instanceTypes[0].toString(),
}),
),
ReplaceUnhealthyInstances: true,
TargetCapacity: fleet.maxCapacity,
TerminateInstancesWithExpiration: true,
Type: 'maintain',
TagSpecifications: arrayWith(
objectLike({
ResourceType: 'spot-fleet-request',
Tags: arrayWith(
objectLike({
Key: rfdkTag.name,
Value: rfdkTag.value,
}),
),
}),
),
}),
}),
})));
});
test('adds policies to the render queue', () => {
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleet,
],
});
// THEN
cdkExpect(stack).to(countResourcesLike('AWS::IAM::Role', 1, {
ManagedPolicyArns: arrayWith(
stack.resolve(ManagedPolicy.fromAwsManagedPolicyName('AWSThinkboxDeadlineSpotEventPluginAdminPolicy').managedPolicyArn),
stack.resolve(ManagedPolicy.fromAwsManagedPolicyName('AWSThinkboxDeadlineResourceTrackerAdminPolicy').managedPolicyArn),
),
}));
cdkExpect(stack).to(haveResourceLike('AWS::IAM::Policy', {
PolicyDocument: {
Statement: [
{
Action: 'iam:PassRole',
Condition: {
StringLike: {
'iam:PassedToService': 'ec2.amazonaws.com',
},
},
Effect: 'Allow',
Resource: [
stack.resolve(fleet.fleetRole.roleArn),
stack.resolve(fleet.fleetInstanceRole.roleArn),
],
},
{
Action: 'ec2:CreateTags',
Effect: 'Allow',
Resource: 'arn:aws:ec2:*:*:spot-fleet-request/*',
},
],
},
Roles: [{
Ref: 'RQRCSTaskTaskRole00DC9B43',
}],
}));
});
test('adds resource tracker policy even if rt disabled', () => {
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleet,
],
configuration: {
enableResourceTracker: false,
},
});
// THEN
cdkExpect(stack).to(haveResourceLike('AWS::IAM::Role', {
ManagedPolicyArns: arrayWith(
stack.resolve(ManagedPolicy.fromAwsManagedPolicyName('AWSThinkboxDeadlineResourceTrackerAdminPolicy').managedPolicyArn),
),
}));
});
test.each([
undefined,
[],
])('without spot fleet', (noFleets: any) => {
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: noFleets,
});
// THEN
cdkExpect(stack).to(haveResourceLike('Custom::RFDK_ConfigureSpotEventPlugin', objectLike({
spotFleetRequestConfigurations: ABSENT,
})));
cdkExpect(stack).notTo(haveResourceLike('AWS::IAM::Role', {
ManagedPolicyArns: arrayWith(
stack.resolve(ManagedPolicy.fromAwsManagedPolicyName('AWSThinkboxDeadlineSpotEventPluginAdminPolicy').managedPolicyArn),
stack.resolve(ManagedPolicy.fromAwsManagedPolicyName('AWSThinkboxDeadlineResourceTrackerAdminPolicy').managedPolicyArn),
),
}));
cdkExpect(stack).notTo(haveResourceLike('AWS::IAM::Policy', {
PolicyDocument: {
Statement: [
{
Action: 'iam:PassRole',
Condition: {
StringLike: {
'iam:PassedToService': 'ec2.amazonaws.com',
},
},
Effect: 'Allow',
Resource: [
stack.resolve(fleet.fleetRole.roleArn),
stack.resolve(fleet.fleetInstanceRole.roleArn),
],
},
{
Action: 'ec2:CreateTags',
Effect: 'Allow',
Resource: 'arn:aws:ec2:*:*:spot-fleet-request/*',
},
],
},
Roles: [{
Ref: 'RQRCSTaskTaskRole00DC9B43',
}],
}));
});
test('fleet with validUntil', () => {
// GIVEN
const validUntil = Expiration.atDate(new Date(2022, 11, 17));
const fleetWithCustomProps = new SpotEventPluginFleet(stack, 'SpotEventPluginFleet', {
vpc,
renderQueue,
deadlineGroups: [
groupName,
],
instanceTypes: [
InstanceType.of(InstanceClass.T3, InstanceSize.LARGE),
],
workerMachineImage,
maxCapacity: 1,
validUntil,
});
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleetWithCustomProps,
],
});
// THEN
cdkExpect(stack).to(haveResourceLike('Custom::RFDK_ConfigureSpotEventPlugin', objectLike({
spotFleetRequestConfigurations: objectLike({
[groupName]: objectLike({
ValidUntil: validUntil.date.toISOString(),
}),
}),
})));
});
test('fleet with block devices', () => {
// GIVEN
const deviceName = '/dev/xvda';
const volumeSize = 50;
const encrypted = true;
const deleteOnTermination = true;
const iops = 100;
const volumeType = EbsDeviceVolumeType.STANDARD;
const fleetWithCustomProps = new SpotEventPluginFleet(stack, 'SpotEventPluginFleet', {
vpc,
renderQueue,
deadlineGroups: [
groupName,
],
instanceTypes: [
InstanceType.of(InstanceClass.T3, InstanceSize.LARGE),
],
workerMachineImage,
maxCapacity: 1,
blockDevices: [{
deviceName,
volume: BlockDeviceVolume.ebs(volumeSize, {
encrypted,
deleteOnTermination,
iops,
volumeType,
}),
}],
});
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleetWithCustomProps,
],
});
// THEN
cdkExpect(stack).to(haveResourceLike('Custom::RFDK_ConfigureSpotEventPlugin', objectLike({
spotFleetRequestConfigurations: objectLike({
[groupName]: objectLike({
LaunchSpecifications: arrayWith(objectLike({
BlockDeviceMappings: arrayWith(objectLike({
DeviceName: deviceName,
Ebs: objectLike({
DeleteOnTermination: deleteOnTermination,
Iops: iops,
VolumeSize: volumeSize,
VolumeType: volumeType,
Encrypted: encrypted,
}),
})),
})),
}),
}),
})));
});
test('fleet with block devices with custom volume', () => {
// GIVEN
const deviceName = '/dev/xvda';
const virtualName = 'name';
const snapshotId = 'snapshotId';
const volumeSize = 50;
const deleteOnTermination = true;
const iops = 100;
const volumeType = EbsDeviceVolumeType.STANDARD;
const fleetWithCustomProps = new SpotEventPluginFleet(stack, 'SpotEventPluginFleet', {
vpc,
renderQueue,
deadlineGroups: [
groupName,
],
instanceTypes: [
InstanceType.of(InstanceClass.T3, InstanceSize.LARGE),
],
workerMachineImage,
maxCapacity: 1,
blockDevices: [{
deviceName: deviceName,
volume: {
ebsDevice: {
deleteOnTermination,
iops,
volumeSize,
volumeType,
snapshotId,
},
virtualName,
},
}],
});
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleetWithCustomProps,
],
});
// THEN
cdkExpect(stack).to(haveResourceLike('Custom::RFDK_ConfigureSpotEventPlugin', objectLike({
spotFleetRequestConfigurations: objectLike({
[groupName]: objectLike({
LaunchSpecifications: arrayWith(objectLike({
BlockDeviceMappings: arrayWith(objectLike({
DeviceName: deviceName,
Ebs: objectLike({
SnapshotId: snapshotId,
DeleteOnTermination: deleteOnTermination,
Iops: iops,
VolumeSize: volumeSize,
VolumeType: volumeType,
Encrypted: ABSENT,
}),
VirtualName: virtualName,
})),
})),
}),
}),
})));
});
test('fleet with block devices with no device', () => {
// GIVEN
const deviceName = '/dev/xvda';
const volume = BlockDeviceVolume.noDevice();
const fleetWithCustomProps = new SpotEventPluginFleet(stack, 'SpotEventPluginFleet', {
vpc,
renderQueue,
deadlineGroups: [
groupName,
],
instanceTypes: [
InstanceType.of(InstanceClass.T3, InstanceSize.LARGE),
],
workerMachineImage,
maxCapacity: 1,
blockDevices: [{
deviceName: deviceName,
volume,
}],
});
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleetWithCustomProps,
],
});
// THEN
cdkExpect(stack).to(haveResourceLike('Custom::RFDK_ConfigureSpotEventPlugin', objectLike({
spotFleetRequestConfigurations: objectLike({
[groupName]: objectLike({
LaunchSpecifications: arrayWith(objectLike({
BlockDeviceMappings: arrayWith(objectLike({
DeviceName: deviceName,
NoDevice: '',
})),
})),
}),
}),
})));
});
test('fleet with deprecated mappingEnabled', () => {
// GIVEN
const deviceName = '/dev/xvda';
const mappingEnabled = false;
const fleetWithCustomProps = new SpotEventPluginFleet(stack, 'SpotEventPluginFleet', {
vpc,
renderQueue,
deadlineGroups: [
groupName,
],
instanceTypes: [
InstanceType.of(InstanceClass.T3, InstanceSize.LARGE),
],
workerMachineImage,
maxCapacity: 1,
blockDevices: [{
deviceName: deviceName,
volume: BlockDeviceVolume.ebs(50),
mappingEnabled,
}],
});
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleetWithCustomProps,
],
});
// THEN
cdkExpect(stack).to(haveResourceLike('Custom::RFDK_ConfigureSpotEventPlugin', objectLike({
spotFleetRequestConfigurations: objectLike({
[groupName]: objectLike({
LaunchSpecifications: arrayWith(objectLike({
BlockDeviceMappings: arrayWith(objectLike({
DeviceName: deviceName,
NoDevice: '',
})),
})),
}),
}),
})));
});
});
test('only one object allowed per render queue', () => {
// GIVEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleet,
],
});
// WHEN
function createConfigureSpotEventPlugin() {
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin2', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleet,
],
});
}
// THEN
expect(createConfigureSpotEventPlugin).toThrowError(/Only one ConfigureSpotEventPlugin construct is allowed per render queue./);
});
test('can create multiple objects with different render queues', () => {
// GIVEN
const renderQueue2 = new RenderQueue(stack, 'RQ2', {
vpc,
images: { remoteConnectionServer: ContainerImage.fromAsset(__dirname) },
repository: new Repository(stack, 'Repository2', {
vpc,
version,
secretsManagementSettings: { enabled: false },
}),
trafficEncryption: { externalTLS: { enabled: false } },
version,
});
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleet,
],
});
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin2', {
vpc,
renderQueue: renderQueue2,
spotFleets: [
fleet,
],
});
// THEN
cdkExpect(stack).to(countResources('Custom::RFDK_ConfigureSpotEventPlugin', 2));
});
test('throws with not supported render queue', () => {
// GIVEN
const invalidRenderQueue = {
};
// WHEN
function createConfigureSpotEventPlugin() {
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin2', {
vpc,
renderQueue: invalidRenderQueue as IRenderQueue,
spotFleets: [
fleet,
],
});
}
// THEN
expect(createConfigureSpotEventPlugin).toThrowError(/The provided render queue is not an instance of RenderQueue class. Some functionality is not supported./);
});
test('tagSpecifications returns undefined if fleet does not have tags', () => {
// GIVEN
const mockFleet = {
tags: {
hasTags: jest.fn().mockReturnValue(false),
},
};
const mockedFleet = (mockFleet as unknown) as SpotEventPluginFleet;
const config = new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleet,
],
});
// WHEN
// eslint-disable-next-line dot-notation
const result = stack.resolve(config['tagSpecifications'](mockedFleet, SpotFleetResourceType.INSTANCE));
// THEN
expect(result).toBeUndefined();
});
describe('with TLS', () => {
let renderQueueWithTls: IRenderQueue;
let caCert: X509CertificatePem;
beforeEach(() => {
const host = 'renderqueue';
const zoneName = 'deadline-test.internal';
caCert = new X509CertificatePem(stack, 'RootCA', {
subject: {
cn: 'SampleRootCA',
},
});
renderQueueWithTls = new RenderQueue(stack, 'RQ with TLS', {
vpc,
images: { remoteConnectionServer: ContainerImage.fromAsset(__dirname) },
repository: new Repository(stack, 'Repository2', {
vpc,
version,
}),
version,
hostname: {
zone: new PrivateHostedZone(stack, 'DnsZone', {
vpc,
zoneName: zoneName,
}),
hostname: host,
},
trafficEncryption: {
externalTLS: {
rfdkCertificate: new X509CertificatePem(stack, 'RQCert', {
subject: {
cn: `${host}.${zoneName}`,
},
signingCertificate: caCert,
}),
},
},
});
});
test('Lambda role can get the ca secret', () => {
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueueWithTls,
spotFleets: [
fleet,
],
});
// THEN
cdkExpect(stack).to(haveResourceLike('AWS::IAM::Policy', {
PolicyDocument: {
Statement: [
{
Action: [
'secretsmanager:GetSecretValue',
'secretsmanager:DescribeSecret',
],
Effect: 'Allow',
Resource: stack.resolve((renderQueueWithTls as RenderQueue).certChain!.secretArn),
},
],
},
Roles: [
{
Ref: 'ConfigureSpotEventPluginConfiguratorServiceRole341B4735',
},
],
}));
});
test('creates a custom resource with connection', () => {
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueueWithTls,
spotFleets: [
fleet,
],
});
// THEN
cdkExpect(stack).to(haveResourceLike('Custom::RFDK_ConfigureSpotEventPlugin', objectLike({
connection: objectLike({
hostname: stack.resolve(renderQueueWithTls.endpoint.hostname),
port: stack.resolve(renderQueueWithTls.endpoint.portAsString()),
protocol: stack.resolve(renderQueueWithTls.endpoint.applicationProtocol.toString()),
caCertificateArn: stack.resolve((renderQueueWithTls as RenderQueue).certChain!.secretArn),
}),
})));
});
});
test('throws with the same group name', () => {
// WHEN
function createConfigureSpotEventPlugin() {
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleet,
fleet,
],
});
}
// THEN
expect(createConfigureSpotEventPlugin).toThrowError(`Bad Group Name: ${groupName}. Group names in Spot Fleet Request Configurations should be unique.`);
});
test('uses selected subnets', () => {
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
vpcSubnets: { subnets: [ vpc.privateSubnets[0] ] },
renderQueue: renderQueue,
spotFleets: [
fleet,
],
});
// THEN
cdkExpect(stack).to(haveResourceLike('AWS::Lambda::Function', {
Handler: 'configure-spot-event-plugin.configureSEP',
VpcConfig: {
SubnetIds: [
stack.resolve(vpc.privateSubnets[0].subnetId),
],
},
}));
});
describe('throws with wrong deadline version', () => {
test.each([
['10.1.9'],
['10.1.10'],
])('%s', (versionString: string) => {
// GIVEN
const newStack = new Stack(app, 'NewStack');
version = new VersionQuery(newStack, 'OldVersion', {
version: versionString,
});
renderQueue = new RenderQueue(newStack, 'OldRenderQueue', {
vpc,
images: { remoteConnectionServer: ContainerImage.fromAsset(__dirname) },
repository: new Repository(newStack, 'Repository', {
vpc,
version,
secretsManagementSettings: { enabled: false },
}),
trafficEncryption: { externalTLS: { enabled: false } },
version,
});
// WHEN
function createConfigureSpotEventPlugin() {
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleet,
],
});
}
// THEN
expect(createConfigureSpotEventPlugin).toThrowError(`Minimum supported Deadline version for ConfigureSpotEventPlugin is 10.1.12.0. Received: ${versionString}.`);
});
});
test('does not throw with min deadline version', () => {
// GIVEN
const versionString = '10.1.12';
const newStack = new Stack(app, 'NewStack');
version = new VersionQuery(newStack, 'OldVersion', {
version: versionString,
});
renderQueue = new RenderQueue(newStack, 'OldRenderQueue', {
vpc,
images: { remoteConnectionServer: ContainerImage.fromAsset(__dirname) },
repository: new Repository(newStack, 'Repository', {
vpc,
version,
secretsManagementSettings: { enabled: false },
}),
trafficEncryption: { externalTLS: { enabled: false } },
version,
});
// WHEN
function createConfigureSpotEventPlugin() {
new ConfigureSpotEventPlugin(newStack, 'ConfigureSpotEventPlugin', {
vpc,
renderQueue: renderQueue,
spotFleets: [
fleet,
],
});
}
// THEN
expect(createConfigureSpotEventPlugin).not.toThrow();
});
describe('secrets management enabled', () => {
beforeEach(() => {
region = 'us-east-1';
app = new App();
stack = new Stack(app, 'stack', {
env: {
region,
},
});
vpc = new Vpc(stack, 'Vpc');
version = new VersionQuery(stack, 'Version');
renderQueue = new RenderQueue(stack, 'RQ', {
vpc,
images: { remoteConnectionServer: ContainerImage.fromAsset(__dirname) },
repository: new Repository(stack, 'Repository', {
vpc,
version,
}),
version,
});
groupName = 'group_name1';
});
test('a fleet without vpcSubnets specified => warns about dedicated subnets', () => {
// GIVEN
fleet = new SpotEventPluginFleet(stack, 'SpotFleet', {
vpc,
renderQueue: renderQueue,
deadlineGroups: [
groupName,
],
instanceTypes: [
InstanceType.of(InstanceClass.T2, InstanceSize.SMALL),
],
workerMachineImage,
maxCapacity: 1,
});
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
renderQueue,
vpc,
spotFleets: [fleet],
});
// THEN
expect(fleet.node.metadataEntry).toContainEqual(expect.objectContaining({
type: 'aws:cdk:warning',
data: 'Deadline Secrets Management is enabled on the Repository and VPC subnets have not been supplied. Using dedicated subnets is recommended. See https://github.com/aws/aws-rfdk/blobs/release/packages/aws-rfdk/lib/deadline/README.md#using-dedicated-subnets-for-deadline-components',
}));
});
test('a fleet with vpcSubnets specified => does not warn about dedicated subnets', () => {
// GIVEN
fleet = new SpotEventPluginFleet(stack, 'SpotFleetWithSubnets', {
vpc,
vpcSubnets: {
subnetType: SubnetType.PRIVATE,
},
renderQueue: renderQueue,
deadlineGroups: [
groupName,
],
instanceTypes: [
InstanceType.of(InstanceClass.T2, InstanceSize.SMALL),
],
workerMachineImage,
maxCapacity: 1,
});
// WHEN
new ConfigureSpotEventPlugin(stack, 'ConfigureSpotEventPlugin', {
renderQueue,
vpc,
spotFleets: [fleet],
});
// THEN
expect(fleet.node.metadataEntry).not.toContainEqual(expect.objectContaining({
type: 'aws:cdk:warning',
data: expect.stringMatching(/dedicated subnet/i),
}));
});
});
}); | the_stack |
declare module 'displayCtrl' {
global {
namespace displayCtrl {
type CtrlClassType<T extends ICtrl = any> = {
readonly typeKey?: string;
readonly ress?: string[] | any[];
new (dpCtrlMgr?: IMgr): T;
};
type CtrlLoadedCb = (isOk: boolean) => void;
type CtrlInsMap<keyType extends keyof any = any> = {
[P in keyType]: ICtrl;
};
type CtrlShowCfgs = {
[key: string]: IShowConfig[];
};
type CtrlClassMap = {
[key: string]: CtrlClassType<ICtrl>;
};
type CtrlInsCb<T = unknown> = (ctrl: T extends displayCtrl.ICtrl ? T : displayCtrl.ICtrl) => void;
interface IResLoadConfig {
/**页面key */
key: string;
/**资源数组 */
ress?: string | any[];
/**完成回调 */
complete: VoidFunction;
/**错误回调 */
error: VoidFunction;
/**加载透传数据 */
onLoadData?: any;
}
/**
* 资源处理器
*/
interface IResHandler {
/**
* 加载资源
* @param config
*/
loadRes?(config: displayCtrl.IResLoadConfig): void;
/**
* 释放资源
* @param ctrlIns
*/
releaseRes?(ctrlIns?: ICtrl): void;
}
interface ILoadConfig {
/**页面类型key */
typeKey?: string | any;
/**强制重新加载 */
forceLoad?: boolean;
/**加载后onLoad参数 */
onLoadData?: any;
/**加载完成回调,返回实例为空则加载失败,返回实例则成功 */
loadCb?: CtrlInsCb;
}
interface ILoadHandler extends ILoadConfig {
loadCount: number;
}
/**
* 创建配置
*/
interface ICreateConfig<InitDataTypeMapType = any, ShowDataTypeMapType = any, TypeKey extends keyof any = any> extends ILoadConfig {
/**是否自动显示 */
isAutoShow?: boolean;
/**透传初始化数据 */
onInitData?: InitDataTypeMapType[ToAnyIndexKey<TypeKey, InitDataTypeMapType>];
/**显示透传数据 */
onShowData?: ShowDataTypeMapType[ToAnyIndexKey<TypeKey, ShowDataTypeMapType>];
/**创建回调 */
createCb?: CtrlInsCb;
}
/**
* 将索引类型转换为任意类型的索引类型
*/
type ToAnyIndexKey<IndexKey, AnyType> = IndexKey extends keyof AnyType ? IndexKey : keyof AnyType;
interface IInitConfig<TypeKey extends keyof any = any, InitDataTypeMapType = any> {
typeKey?: TypeKey;
onInitData?: InitDataTypeMapType[ToAnyIndexKey<TypeKey, InitDataTypeMapType>];
}
/**
* 显示配置
*/
interface IShowConfig<TypeKey extends keyof any = any, InitDataTypeMapType = any, ShowDataTypeMapType = any> {
typeKey?: TypeKey;
/**
* 透传初始化数据
*/
onInitData?: InitDataTypeMapType[ToAnyIndexKey<TypeKey, InitDataTypeMapType>];
/**
* 强制重新加载
*/
forceLoad?: boolean;
/**
* 显示数据
*/
onShowData?: ShowDataTypeMapType[ToAnyIndexKey<TypeKey, ShowDataTypeMapType>];
/**在调用控制器实例onShow后回调 */
showedCb?: CtrlInsCb;
/**控制器显示完成后回调 */
showEndCb?: VoidFunction;
/**显示被取消了 */
onCancel?: VoidFunction;
/**加载后onLoad参数 */
onLoadData?: any;
/**加载完成回调,返回实例为空则加载失败,返回实例则成功 */
loadCb?: CtrlInsCb;
}
type ReturnCtrlType<T> = T extends displayCtrl.ICtrl ? T : displayCtrl.ICtrl;
interface ICtrl<NodeType = any> {
key?: string | any;
/**正在加载 */
isLoading?: boolean;
/**已经加载 */
isLoaded?: boolean;
/**已经初始化 */
isInited?: boolean;
/**已经显示 */
isShowed?: boolean;
/**需要显示 */
needShow?: boolean;
/**需要加载 */
needLoad?: boolean;
/**正在显示 */
isShowing?: boolean;
/**
* 透传给加载处理的数据,
* 会和调用显示接口showDpc中传来的onLoadData合并,
* 以接口传入的为主
* Object.assign(ins.onLoadData,cfg.onLoadData);
* */
onLoadData?: any;
/**获取资源 */
getRess?(): string[] | any[];
/**
* 初始化
* @param initData 初始化数据
*/
onInit(config?: displayCtrl.IInitConfig): void;
/**
* 当显示时
* @param showData 显示数据
*/
onShow(config?: displayCtrl.IShowConfig): void;
/**
* 当更新时
* @param updateData 更新数据
* @param endCb 结束回调
*/
onUpdate(updateData: any): void;
/**
* 获取控制器
*/
getFace<T>(): ReturnCtrlType<T>;
/**
* 当隐藏时
*/
onHide(): void;
/**
* 强制隐藏
*/
forceHide(): void;
/**
* 当销毁时
* @param destroyRes
*/
onDestroy(destroyRes?: boolean): void;
/**
* 获取显示节点
*/
getNode(): NodeType;
}
interface IMgr<CtrlKeyMapType = any, InitDataTypeMapType = any, ShowDataTypeMapType = any, UpdateDataTypeMapType = any> {
/**控制器key字典 */
keys: CtrlKeyMapType;
/**
* 控制器单例字典
*/
sigCtrlCache: CtrlInsMap;
/**
* 初始化
* @param resHandler 资源处理
*/
init(resHandler?: IResHandler): void;
/**
* 批量注册控制器类
* @param classMap
*/
registTypes(classes: CtrlClassMap | CtrlClassType[]): void;
/**
* 注册控制器类
* @param ctrlClass
* @param typeKey 如果ctrlClass这个类里没有静态属性typeKey则取传入的typeKey
*/
regist(ctrlClass: CtrlClassType, typeKey?: keyof CtrlKeyMapType): void;
/**
* 是否注册了
* @param typeKey
*/
isRegisted<keyType extends keyof CtrlKeyMapType>(typeKey: keyType): boolean;
/**
* 获取注册类的资源信息
* 读取类的静态变量 ress
* @param typeKey
*/
getDpcRessInClass<keyType extends keyof CtrlKeyMapType>(typeKey: keyType): string[] | any[];
/**
* 获取单例UI的资源数组
* @param typeKey
*/
getSigDpcRess<keyType extends keyof CtrlKeyMapType>(typeKey: keyType): string[] | any[];
/**
* 获取/生成单例显示控制器示例
* @param typeKey 类型key
*/
getSigDpcIns<T, keyType extends keyof CtrlKeyMapType = any>(typeKey: keyType): displayCtrl.ReturnCtrlType<T>;
/**
* 加载Dpc
* @param typeKey 注册时的typeKey
* @param loadCfg 透传数据和回调
*/
loadSigDpc<T, keyType extends keyof CtrlKeyMapType = any>(typeKey: keyType, loadCfg?: displayCtrl.ILoadConfig): displayCtrl.ReturnCtrlType<T>;
/**
* 初始化显示控制器
* @param typeKey 注册类时的 typeKey
* @param initCfg displayCtrl.IInitConfig
*/
initSigDpc<T, keyType extends keyof CtrlKeyMapType = any>(typeKey: keyType, initCfg?: displayCtrl.IInitConfig<keyType, InitDataTypeMapType>): displayCtrl.ReturnCtrlType<T>;
/**
* 显示单例显示控制器
* @param typeKey 类key或者显示配置IShowConfig
* @param onShowData 显示透传数据
* @param showedCb 显示完成回调(onShow调用之后)
* @param onInitData 初始化透传数据
* @param forceLoad 是否强制重新加载
* @param onCancel 当取消显示时
*/
showDpc<T, keyType extends keyof CtrlKeyMapType = any>(typeKey: keyType | displayCtrl.IShowConfig<keyType, InitDataTypeMapType, ShowDataTypeMapType>, onShowData?: ShowDataTypeMapType[displayCtrl.ToAnyIndexKey<keyType, ShowDataTypeMapType>], showedCb?: displayCtrl.CtrlInsCb<T>, onInitData?: InitDataTypeMapType[displayCtrl.ToAnyIndexKey<keyType, InitDataTypeMapType>], forceLoad?: boolean, onLoadData?: any, loadCb?: displayCtrl.CtrlInsCb, onCancel?: VoidFunction): displayCtrl.ReturnCtrlType<T>;
/**
* 更新控制器
* @param key UIkey
* @param updateData 更新数据
*/
updateDpc<keyType extends keyof CtrlKeyMapType>(key: keyType, updateData?: UpdateDataTypeMapType[ToAnyIndexKey<keyType, UpdateDataTypeMapType>]): void;
/**
* 隐藏单例控制器
* @param key
*/
hideDpc<keyType extends keyof CtrlKeyMapType>(key: keyType): void;
/**
* 销毁单例控制器
* @param key
* @param destroyRes 销毁资源
*/
destroyDpc<keyType extends keyof CtrlKeyMapType>(key: keyType, destroyRes?: boolean): void;
/**
* 实例化显示控制器
* @param typeKey 类型key
*/
insDpc<T, keyType extends keyof CtrlKeyMapType = any>(typeKey: keyType): ReturnCtrlType<T>;
/**
* 加载显示控制器
* @param ins
* @param loadCfg
*/
loadDpcByIns(ins: displayCtrl.ICtrl, loadCfg?: ILoadConfig): void;
/**
* 初始化显示控制器
* @param ins
* @param initData
*/
initDpcByIns<keyType extends keyof CtrlKeyMapType>(ins: displayCtrl.ICtrl, initCfg?: displayCtrl.IInitConfig<keyType, InitDataTypeMapType>): void;
/**
* 显示 显示控制器
* @param ins
* @param showCfg
*/
showDpcByIns<keyType extends keyof CtrlKeyMapType>(ins: displayCtrl.ICtrl, showCfg?: displayCtrl.IShowConfig<keyType, InitDataTypeMapType, ShowDataTypeMapType>): void;
/**
* 通过实例隐藏
* @param ins
*/
hideDpcByIns<T extends displayCtrl.ICtrl>(ins: T): void;
/**
* 通过实例销毁
* @param ins
* @param destroyRes 是否销毁资源
*/
destroyDpcByIns<T extends displayCtrl.ICtrl>(ins: T, destroyRes?: boolean, endCb?: VoidFunction): void;
/**
* 获取单例控制器是否正在
* @param key
*/
isLoading<keyType extends keyof CtrlKeyMapType>(key: keyType): boolean;
/**
* 获取单例控制器是否加载了
* @param key
*/
isLoaded<keyType extends keyof CtrlKeyMapType>(key: keyType): boolean;
/**
* 获取单例控制器是否初始化了
* @param key
*/
isInited<keyType extends keyof CtrlKeyMapType>(key: keyType): boolean;
/**
* 获取单例控制器是否显示
* @param key
*/
isShowed<keyType extends keyof CtrlKeyMapType>(key: keyType): boolean;
/**
* 获取控制器类
* @param typeKey
*/
getCtrlClass<keyType extends keyof CtrlKeyMapType>(typeKey: keyType): CtrlClassType<ICtrl>;
}
}
}
}
declare module 'displayCtrl' {
/**
* DisplayControllerMgr
* 显示控制类管理器基类
*/
class DpcMgr<CtrlKeyMapType = any, InitDataTypeMapType = any, ShowDataTypeMapType = any, UpdateDataTypeMapType = any> implements displayCtrl.IMgr<CtrlKeyMapType, InitDataTypeMapType, ShowDataTypeMapType, UpdateDataTypeMapType> {
keys: CtrlKeyMapType;
/**
* 单例缓存字典 key:ctrlKey,value:egf.IDpCtrl
*/
protected _sigCtrlCache: displayCtrl.CtrlInsMap;
protected _sigCtrlShowCfgMap: {
[P in keyof CtrlKeyMapType]: displayCtrl.IShowConfig;
};
protected _resHandler: displayCtrl.IResHandler;
/**
* 控制器类字典
*/
protected _ctrlClassMap: {
[P in keyof CtrlKeyMapType]: displayCtrl.CtrlClassType<displayCtrl.ICtrl>;
};
get sigCtrlCache(): displayCtrl.CtrlInsMap;
getCtrlClass<keyType extends keyof CtrlKeyMapType>(typeKey: keyType): { [P in keyof CtrlKeyMapType]: displayCtrl.CtrlClassType<displayCtrl.ICtrl<any>>; }[keyType];
init(resHandler?: displayCtrl.IResHandler): void;
registTypes(classes: displayCtrl.CtrlClassMap | displayCtrl.CtrlClassType[]): void;
regist(ctrlClass: displayCtrl.CtrlClassType, typeKey?: keyof CtrlKeyMapType): void;
isRegisted<keyType extends keyof CtrlKeyMapType>(typeKey: keyType): boolean;
getDpcRessInClass<keyType extends keyof CtrlKeyMapType>(typeKey: keyType): any[] | string[];
getSigDpcRess<keyType extends keyof CtrlKeyMapType>(typeKey: keyType): string[];
loadSigDpc<T, keyType extends keyof CtrlKeyMapType = any>(typeKey: keyType, loadCfg?: displayCtrl.ILoadConfig): displayCtrl.ReturnCtrlType<T>;
getSigDpcIns<T, keyType extends keyof CtrlKeyMapType = any>(typeKey: keyType): displayCtrl.ReturnCtrlType<T>;
initSigDpc<T = any, keyType extends keyof CtrlKeyMapType = any>(typeKey: keyType, initCfg?: displayCtrl.IInitConfig<keyType, InitDataTypeMapType>): displayCtrl.ReturnCtrlType<T>;
showDpc<T, keyType extends keyof CtrlKeyMapType = any>(typeKey: keyType | displayCtrl.IShowConfig<keyType, InitDataTypeMapType, ShowDataTypeMapType>, onShowData?: ShowDataTypeMapType[displayCtrl.ToAnyIndexKey<keyType, ShowDataTypeMapType>], showedCb?: displayCtrl.CtrlInsCb<T>, onInitData?: InitDataTypeMapType[displayCtrl.ToAnyIndexKey<keyType, InitDataTypeMapType>], forceLoad?: boolean, onLoadData?: any, loadCb?: displayCtrl.CtrlInsCb, showEndCb?: VoidFunction, onCancel?: VoidFunction): displayCtrl.ReturnCtrlType<T>;
updateDpc<keyType extends keyof CtrlKeyMapType>(key: keyType, updateData?: UpdateDataTypeMapType[displayCtrl.ToAnyIndexKey<keyType, UpdateDataTypeMapType>]): void;
hideDpc<keyType extends keyof CtrlKeyMapType>(key: keyType): void;
destroyDpc<keyType extends keyof CtrlKeyMapType>(key: keyType, destroyRes?: boolean): void;
isLoading<keyType extends keyof CtrlKeyMapType>(key: keyType): boolean;
isLoaded<keyType extends keyof CtrlKeyMapType>(key: keyType): boolean;
isInited<keyType extends keyof CtrlKeyMapType>(key: keyType): boolean;
isShowed<keyType extends keyof CtrlKeyMapType>(key: keyType): boolean;
insDpc<T, keyType extends keyof CtrlKeyMapType = any>(typeKey: keyType): displayCtrl.ReturnCtrlType<T>;
loadDpcByIns(ins: displayCtrl.ICtrl, loadCfg?: displayCtrl.ILoadConfig): void;
initDpcByIns<keyType extends keyof CtrlKeyMapType>(ins: displayCtrl.ICtrl, initCfg?: displayCtrl.IInitConfig<keyType, InitDataTypeMapType>): void;
showDpcByIns<keyType extends keyof CtrlKeyMapType>(ins: displayCtrl.ICtrl, showCfg?: displayCtrl.IShowConfig<keyType, InitDataTypeMapType, ShowDataTypeMapType>): void;
hideDpcByIns<T extends displayCtrl.ICtrl = any>(dpcIns: T): void;
destroyDpcByIns(dpcIns: displayCtrl.ICtrl, destroyRes?: boolean): void;
protected _loadRess(ctrlIns: displayCtrl.ICtrl, loadCfg?: displayCtrl.ILoadConfig): void;
}
}
declare module 'displayCtrl' {
}
declare namespace displayCtrl {
type DpcMgr<CtrlKeyMapType = any, InitDataTypeMapType = any, ShowDataTypeMapType = any, UpdateDataTypeMapType = any> = import('displayCtrl').DpcMgr<CtrlKeyMapType, InitDataTypeMapType, ShowDataTypeMapType, UpdateDataTypeMapType>;
}
declare const displayCtrl:typeof import("displayCtrl"); | the_stack |
import {
buildForm,
buildSection,
Form,
FormModes,
buildDataProviderItem,
buildExternalDataProvider,
buildCustomField,
buildSubSection,
buildMultiField,
buildSubmitField,
DefaultEvents,
} from '@island.is/application/core'
import { DataProviderTypes } from '@island.is/application/templates/children-residence-change'
import Logo from '@island.is/application/templates/family-matters-core/assets/Logo'
import { selectDurationInputs } from '../fields/Duration'
import { confirmContractIds } from '../fields/Overview'
import { contactInfoIds } from '../fields/ContactInfo'
import * as m from '../lib/messages'
import { ExternalData } from '@island.is/application/templates/family-matters-core/types'
import { hasChildren } from '../lib/utils'
const soleCustodyField = () => {
return buildCustomField({
id: 'errorModal',
component: 'SoleCustodyModal',
title: '',
condition: (_, externalData) => {
return ((externalData as unknown) as ExternalData)?.nationalRegistry?.data?.children?.every(
(child) => !child.otherParent,
)
},
})
}
const noChildrenFoundField = () => {
return buildCustomField({
id: 'errorModal',
component: 'NoChildrenErrorModal',
title: '',
condition: (_, externalData) => {
return !hasChildren((externalData as unknown) as ExternalData)
},
})
}
// TODO: Added by Kolibri - 2021-07-05 - Revisit mockdata implementation to prevent
// Continue and Back button from being displayed on production
// const shouldUseMocks = (answers: Answers): boolean => {
// if (answers.useMocks && answers.useMocks === 'yes') {
// return true
// }
// return false
// }
// const shouldRenderMockDataSubSection = !isRunningOnEnvironment('production')
export const ChildrenResidenceChangeForm: Form = buildForm({
id: 'ChildrenResidenceChangeFormDraft',
title: m.application.name,
logo: Logo,
mode: FormModes.APPLYING,
children: [
// buildSection({
// id: 'mockData',
// title: 'Mock data',
// condition: () => shouldRenderMockDataSubSection,
// children: [
// buildSubSection({
// id: 'useMocks',
// title: 'Nota gervigögn?',
// children: [
// buildRadioField({
// id: 'useMocks',
// title: 'Nota gervigögn',
// options: [
// {
// value: 'yes',
// label: 'Já',
// },
// {
// value: 'no',
// label: 'Nei',
// },
// ],
// }),
// ],
// }),
// buildSubSection({
// id: 'applicantMock',
// title: 'Umsækjandi',
// condition: (answers) =>
// shouldUseMocks((answers as unknown) as Answers),
// children: [
// buildCustomField({
// id: 'mockData.applicant',
// title: 'Mock Umsækjandi',
// component: 'ApplicantMock',
// }),
// ],
// }),
// buildSubSection({
// id: 'parentMock',
// title: 'Foreldrar',
// condition: (answers) =>
// shouldUseMocks((answers as unknown) as Answers),
// children: [
// buildCustomField({
// id: 'mockData.parents',
// title: 'Mock Foreldrar',
// component: 'ParentMock',
// }),
// ],
// }),
// buildSubSection({
// id: 'childrenMock',
// title: 'Börn',
// condition: (answers) =>
// shouldUseMocks((answers as unknown) as Answers),
// children: [
// buildCustomField({
// id: 'mockData.children',
// title: 'Mock Börn',
// component: 'ChildrenMock',
// }),
// ],
// }),
// ],
// }),
buildSection({
id: 'backgroundInformation',
title: m.section.backgroundInformation,
children: [
buildSubSection({
id: 'externalData',
title: m.externalData.general.sectionTitle,
// condition: (answers) =>
// !shouldUseMocks((answers as unknown) as Answers),
children: [
buildExternalDataProvider({
title: m.externalData.general.pageTitle,
id: 'approveExternalData',
subTitle: m.externalData.general.subTitle,
description: m.externalData.general.description,
checkboxLabel: m.externalData.general.checkboxLabel,
dataProviders: [
buildDataProviderItem({
id: 'nationalRegistry',
type: DataProviderTypes.NationalRegistry,
title: m.externalData.applicant.title,
subTitle: m.externalData.applicant.subTitle,
}),
buildDataProviderItem({
id: '',
type: '',
title: m.externalData.children.title,
subTitle: m.externalData.children.subTitle,
}),
buildDataProviderItem({
id: 'userProfile',
type: DataProviderTypes.UserProfile,
title: '',
subTitle: '',
}),
],
}),
noChildrenFoundField(),
soleCustodyField(),
],
}),
// buildSubSection({
// id: 'externalData',
// title: m.externalData.general.sectionTitle,
// condition: (answers) =>
// shouldUseMocks((answers as unknown) as Answers),
// children: [
// buildExternalDataProvider({
// title: m.externalData.general.pageTitle,
// id: 'approveExternalData',
// subTitle: m.externalData.general.subTitle,
// description: m.externalData.general.description,
// checkboxLabel: m.externalData.general.checkboxLabel,
// dataProviders: [
// buildDataProviderItem({
// id: 'nationalRegistry',
// type: DataProviderTypes.MockNationalRegistry,
// title: m.externalData.applicant.title,
// subTitle: m.externalData.applicant.subTitle,
// }),
// buildDataProviderItem({
// id: '',
// type: '',
// title: m.externalData.children.title,
// subTitle: m.externalData.children.subTitle,
// }),
// buildDataProviderItem({
// id: 'userProfile',
// type: DataProviderTypes.UserProfile,
// title: '',
// subTitle: '',
// }),
// ],
// }),
// noChildrenFoundField(),
// soleCustodyField(),
// ],
// }),
buildSubSection({
id: 'selectChildInCustody',
title: m.selectChildren.general.sectionTitle,
children: [
buildCustomField({
id: 'selectedChildren',
title: m.selectChildren.general.pageTitle,
component: 'SelectChildren',
}),
],
}),
buildSubSection({
id: 'contact',
title: m.contactInfo.general.sectionTitle,
children: [
buildCustomField({
id: 'contactInfo',
title: m.contactInfo.general.pageTitle,
childInputIds: contactInfoIds,
component: 'ContactInfo',
}),
],
}),
],
}),
buildSection({
id: 'arrangement',
title: m.section.arrangement,
children: [
buildSubSection({
id: 'residenceChangeReason',
title: m.reason.general.sectionTitle,
children: [
buildCustomField({
id: 'residenceChangeReason',
title: m.reason.general.pageTitle,
component: 'Reason',
}),
],
}),
buildSubSection({
id: 'confirmResidenceChangeInfo',
title: m.newResidence.general.sectionTitle,
children: [
buildCustomField({
id: 'confirmResidenceChangeInfo',
title: m.newResidence.general.pageTitle,
component: 'ChangeInformation',
}),
],
}),
buildSubSection({
id: 'duration',
title: m.duration.general.sectionTitle,
children: [
buildCustomField({
id: 'selectDuration',
title: m.duration.general.pageTitle,
childInputIds: selectDurationInputs,
component: 'Duration',
}),
],
}),
],
}),
buildSection({
id: 'approveTerms',
title: m.section.effect,
children: [
buildSubSection({
id: 'approveTerms',
title: m.terms.general.sectionTitle,
children: [
buildCustomField({
id: 'approveTerms',
title: m.terms.general.pageTitle,
component: 'Terms',
}),
],
}),
buildSubSection({
id: 'approveChildSupportTerms',
title: m.childSupport.general.sectionTitle,
children: [
buildCustomField({
id: 'approveChildSupportTerms',
title: m.childSupport.general.pageTitle,
component: 'ChildSupport',
}),
],
}),
],
}),
buildSection({
id: 'overview',
title: m.section.overview,
children: [
buildMultiField({
id: 'confirmContract',
title: m.contract.general.pageTitle,
children: [
buildCustomField({
id: 'confirmContract',
title: m.contract.general.pageTitle,
childInputIds: confirmContractIds,
component: 'Overview',
}),
buildSubmitField({
id: 'assign',
title: '',
actions: [
{
event: DefaultEvents.ASSIGN,
name: m.application.signature,
type: 'sign',
},
],
}),
],
}),
],
}),
buildSection({
id: 'submitted',
title: m.section.received,
children: [
buildCustomField({
id: 'residenceChangeConfirmation',
title: m.confirmation.general.pageTitle,
component: 'Confirmation',
}),
],
}),
],
}) | the_stack |
"use strict";
import "katex";
import * as renderMathInElement from "katex/dist/contrib/auto-render";
import "katex/dist/katex.min.css";
import { AABB, Point } from "./intersect";
function reflect(velocity: Point, normal: Point, out: Point) {
const dot = velocity.x * normal.x + velocity.y * normal.y;
const ux = normal.x * dot;
const uy = normal.y * dot;
const wx = velocity.x - ux;
const wy = velocity.y - uy;
out.x = wx - ux;
out.y = wy - uy;
}
class Example {
public context: CanvasRenderingContext2D;
public width: number;
public height: number;
public origin: Point;
public infiniteLength: number;
constructor(
context: CanvasRenderingContext2D,
width: number,
height: number
) {
this.context = context;
this.width = width;
this.height = height;
this.origin = new Point(this.width * 0.5, this.height * 0.5);
this.infiniteLength = Math.sqrt(
this.width * this.width + this.height * this.height
);
}
public drawAABB(box: AABB, color: string = "#fff", thickness: number = 1) {
const x1 = Math.floor(this.origin.x + box.pos.x - box.half.x);
const y1 = Math.floor(this.origin.y + box.pos.y - box.half.y);
const x2 = Math.floor(this.origin.x + box.pos.x + box.half.x);
const y2 = Math.floor(this.origin.y + box.pos.y + box.half.y);
this.context.beginPath();
this.context.moveTo(x1, y1);
this.context.lineTo(x2, y1);
this.context.lineTo(x2, y2);
this.context.lineTo(x1, y2);
this.context.lineTo(x1, y1);
this.context.closePath();
this.context.lineWidth = thickness;
this.context.strokeStyle = color;
this.context.stroke();
}
public drawCircle(
circle: { pos: Point; radius: number },
color: string = "#fff",
thickness: number = 1
) {
const x = Math.floor(this.origin.x + circle.pos.x);
const y = Math.floor(this.origin.y + circle.pos.y);
this.context.beginPath();
this.context.arc(x, y, circle.radius, 0, 2 * Math.PI, true);
this.context.closePath();
this.context.lineWidth = thickness;
this.context.strokeStyle = color;
this.context.stroke();
}
public drawPoint(
point: Point,
color: string = "#fff",
text: string = "",
thickness: number = 1
) {
const x = Math.floor(this.origin.x + point.x - thickness / 2);
const y = Math.floor(this.origin.y + point.y - thickness / 2);
this.context.lineWidth = thickness;
this.context.fillStyle = color;
this.context.strokeStyle = color;
this.context.fillRect(x, y, thickness, thickness);
this.context.strokeRect(x, y, thickness, thickness);
if (text) {
this.context.fillText(text, x + thickness * 4, y + thickness * 2);
}
}
public drawRay(
pos: Point,
dir: Point,
length: number,
color: string = "#fff",
arrow: boolean = true,
thickness: number = 1
) {
const pos2 = new Point(pos.x + dir.x * length, pos.y + dir.y * length);
this.drawSegment(pos, pos2, color, thickness);
if (arrow) {
pos = pos2.clone();
pos2.x = pos.x - dir.x * 4 + dir.y * 4;
pos2.y = pos.y - dir.y * 4 - dir.x * 4;
this.drawSegment(pos, pos2, color, thickness);
pos2.x = pos.x - dir.x * 4 - dir.y * 4;
pos2.y = pos.y - dir.y * 4 + dir.x * 4;
this.drawSegment(pos, pos2, color, thickness);
}
}
public drawSegment(
point1: Point,
point2: Point,
color: string = "#fff",
thickness: number = 1
) {
const x1 = Math.floor(this.origin.x + point1.x);
const y1 = Math.floor(this.origin.y + point1.y);
const x2 = Math.floor(this.origin.x + point2.x);
const y2 = Math.floor(this.origin.y + point2.y);
this.context.beginPath();
this.context.moveTo(x1, y1);
this.context.lineTo(x2, y2);
this.context.closePath();
this.context.lineWidth = thickness;
this.context.strokeStyle = color;
this.context.stroke();
}
public tick(elapsed: number) {
this.context.fillStyle = "#000";
this.context.fillRect(0, 0, this.width, this.height);
}
}
class AABBPointExample extends Example {
public angle: number;
public pos: Point;
public box: AABB;
constructor(
context: CanvasRenderingContext2D,
width: number,
height: number
) {
super(context, width, height);
this.angle = 0;
this.pos = new Point();
this.box = new AABB(new Point(0, 0), new Point(16, 16));
}
public tick(elapsed: number) {
super.tick(elapsed);
this.angle += 0.5 * Math.PI * elapsed;
this.pos.x = Math.cos(this.angle * 0.4) * 32;
this.pos.y = Math.sin(this.angle) * 12;
const hit = this.box.intersectPoint(this.pos);
this.drawAABB(this.box, "#666");
if (hit) {
this.drawPoint(this.pos, "#f00");
this.drawPoint(hit.pos, "#ff0");
} else {
this.drawPoint(this.pos, "#0f0");
}
}
}
class AABBSegmentExample extends Example {
public angle: number;
public box: AABB;
constructor(
context: CanvasRenderingContext2D,
width: number,
height: number
) {
super(context, width, height);
this.angle = 0;
this.box = new AABB(new Point(0, 0), new Point(16, 16));
}
public tick(elapsed: number) {
super.tick(elapsed);
this.angle += 0.5 * Math.PI * elapsed;
const pos1 = new Point(
Math.cos(this.angle) * 64,
Math.sin(this.angle) * 64
);
const pos2 = new Point(
Math.sin(this.angle) * 32,
Math.cos(this.angle) * 32
);
const delta = new Point(pos2.x - pos1.x, pos2.y - pos1.y);
const hit = this.box.intersectSegment(pos1, delta);
const dir = delta.clone();
const length = dir.normalize();
this.drawAABB(this.box, "#666");
if (hit) {
this.drawRay(pos1, dir, length, "#f00");
this.drawSegment(pos1, hit.pos, "#ff0");
this.drawPoint(hit.pos, "#ff0");
this.drawRay(hit.pos, hit.normal, 6, "#ff0", false);
} else {
this.drawRay(pos1, dir, length, "#0f0");
}
}
}
class AABBAABBExample extends Example {
public angle: number;
public box1: AABB;
public box2: AABB;
constructor(
context: CanvasRenderingContext2D,
width: number,
height: number
) {
super(context, width, height);
this.angle = 0;
this.box1 = new AABB(new Point(0, 0), new Point(64, 16));
this.box2 = new AABB(new Point(0, 0), new Point(16, 16));
}
public tick(elapsed: number) {
super.tick(elapsed);
this.angle += 0.2 * Math.PI * elapsed;
this.box2.pos.x = Math.cos(this.angle) * 96;
this.box2.pos.y = Math.sin(this.angle * 2.4) * 24;
const hit = this.box1.intersectAABB(this.box2);
this.drawAABB(this.box1, "#666");
if (hit) {
this.drawAABB(this.box2, "#f00");
this.box2.pos.x += hit.delta.x;
this.box2.pos.y += hit.delta.y;
this.drawAABB(this.box2, "#ff0");
this.drawPoint(hit.pos, "#ff0");
this.drawRay(hit.pos, hit.normal, 4, "#ff0", false);
} else {
this.drawAABB(this.box2, "#0f0");
}
}
}
class AABBSweptAABBExample extends Example {
public angle: number;
public staticBox: AABB;
public sweepBoxes: AABB[];
public sweepDeltas: Point[];
public tempBox: AABB;
constructor(
context: CanvasRenderingContext2D,
width: number,
height: number
) {
super(context, width, height);
this.angle = 0;
this.staticBox = new AABB(new Point(0, 0), new Point(112, 16));
this.sweepBoxes = [
new AABB(new Point(-152, 24), new Point(16, 16)),
new AABB(new Point(128, -48), new Point(16, 16))
];
this.sweepDeltas = [new Point(64, -12), new Point(-32, 96)];
this.tempBox = new AABB(new Point(0, 0), new Point(16, 16));
}
public tick(elapsed: number) {
super.tick(elapsed);
this.angle += 0.5 * Math.PI * elapsed;
this.drawAABB(this.staticBox, "#666");
const factor = (Math.cos(this.angle) + 1) * 0.5 || 1e-8;
this.sweepBoxes.forEach((box, i) => {
const delta = this.sweepDeltas[i].clone();
delta.x *= factor;
delta.y *= factor;
const sweep = this.staticBox.sweepAABB(box, delta);
const dir = delta.clone();
const length = dir.normalize();
this.drawAABB(box, "#666");
if (sweep.hit) {
// Draw a red box at the point where it was trying to move to
this.drawRay(box.pos, dir, length, "#f00");
this.tempBox.pos.x = box.pos.x + delta.x;
this.tempBox.pos.y = box.pos.y + delta.y;
this.drawAABB(this.tempBox, "#f00");
// Draw a yellow box at the point it actually got to
this.tempBox.pos.x = sweep.pos.x;
this.tempBox.pos.y = sweep.pos.y;
this.drawAABB(this.tempBox, "#ff0");
this.drawPoint(sweep.hit.pos, "#ff0");
this.drawRay(sweep.hit.pos, sweep.hit.normal, 4, "#ff0", false);
} else {
this.tempBox.pos.x = sweep.pos.x;
this.tempBox.pos.y = sweep.pos.y;
this.drawAABB(this.tempBox, "#0f0");
this.drawRay(box.pos, dir, length, "#0f0");
}
});
}
}
class MultipleAABBSweptAABBExample extends Example {
public delta: Point;
public velocity: Point;
public movingBox: AABB;
public staticBoxes: AABB[];
constructor(
context: CanvasRenderingContext2D,
width: number,
height: number
) {
super(context, width, height);
this.delta = new Point();
this.velocity = new Point(48, 48);
this.movingBox = new AABB(new Point(0, 0), new Point(8, 8));
this.staticBoxes = [
new AABB(new Point(-96, 0), new Point(8, 48)),
new AABB(new Point(96, 0), new Point(8, 48)),
new AABB(new Point(0, -56), new Point(104, 8)),
new AABB(new Point(0, 56), new Point(104, 8))
];
}
public tick(elapsed: number) {
super.tick(elapsed);
this.delta.x = this.velocity.x * elapsed;
this.delta.y = this.velocity.y * elapsed;
const sweep = this.movingBox.sweepInto(this.staticBoxes, this.delta);
if (sweep.hit) {
// This should really attempt to slide along the hit normal, and use up
// the rest of the velocity, but that"s a bit much for this example
reflect(this.velocity, sweep.hit.normal, this.velocity);
}
this.staticBoxes.forEach(staticBox => {
if (sweep.hit && sweep.hit.collider === staticBox) {
this.drawAABB(staticBox, "#aaa");
} else {
this.drawAABB(staticBox, "#666");
}
});
this.movingBox.pos = sweep.pos;
this.drawAABB(this.movingBox, sweep.hit ? "#ff0" : "#0f0");
}
}
function ready(callback: () => void) {
if (document.readyState === "complete") {
setTimeout(callback, 1);
return;
}
document.addEventListener(
"DOMContentLoaded",
function handler() {
document.removeEventListener("DOMContentLoaded", handler, false);
callback();
},
false
);
}
ready(() => {
// This call is weird because @types/katex doesn't declare this properly.
(renderMathInElement as any)(document.body);
const exampleIds: { [key: string]: any } = {
"aabb-vs-aabb": AABBAABBExample,
"aabb-vs-point": AABBPointExample,
"aabb-vs-segment": AABBSegmentExample,
"aabb-vs-swept-aabb": AABBSweptAABBExample,
"sweeping-an-aabb-through-multiple-objects": MultipleAABBSweptAABBExample
};
const examples: Example[] = [];
Object.keys(exampleIds).forEach(id => {
const exampleConstructor = exampleIds[id];
const anchor = document.getElementById(id);
if (!anchor || !anchor.parentNode) {
return;
}
const canvas = document.createElement("canvas");
if (!canvas) {
return;
}
anchor.parentNode.insertBefore(canvas, anchor.nextSibling);
const width = (canvas.width = 640);
const height = (canvas.height = 160);
const context = canvas.getContext("2d");
if (!context) {
return;
}
context.translate(0.5, 0.5);
const example = new exampleConstructor(context, width, height);
if (example) {
examples.push(example);
}
});
setInterval(() => {
examples.forEach(example => example.tick(1 / 30));
}, 1000 / 30);
}); | the_stack |
/// <reference path="../text/stringToBytes_SJIS.ts" />
'use strict';
namespace com.d_project.qrcode {
import stringToBytes_SJIS = com.d_project.text.stringToBytes_SJIS;
/**
* QRCode
* @author Kazuhiko Arase
*/
export class QRCode {
private static PAD0 = 0xEC;
private static PAD1 = 0x11;
private typeNumber : number;
private errorCorrectLevel : ErrorCorrectLevel;
private qrDataList : QRData[];
private modules : boolean[][];
private moduleCount : number;
public constructor() {
this.typeNumber = 1;
this.errorCorrectLevel = ErrorCorrectLevel.L;
this.qrDataList = [];
}
public getTypeNumber() : number {
return this.typeNumber;
}
public setTypeNumber(typeNumber : number) : void {
this.typeNumber = typeNumber;
}
public getErrorCorrectLevel() : ErrorCorrectLevel {
return this.errorCorrectLevel;
}
public setErrorCorrectLevel(errorCorrectLevel : ErrorCorrectLevel) {
this.errorCorrectLevel = errorCorrectLevel;
}
public clearData() : void {
this.qrDataList = [];
}
public addData(qrData : QRData | string) : void {
if (qrData instanceof QRData) {
this.qrDataList.push(qrData);
} else if (typeof qrData === 'string') {
this.qrDataList.push(new QR8BitByte(qrData) );
} else {
throw typeof qrData;
}
}
private getDataCount() : number {
return this.qrDataList.length;
}
private getData(index : number) : QRData {
return this.qrDataList[index];
}
public isDark(row : number, col : number) : boolean {
if (this.modules[row][col] != null) {
return this.modules[row][col];
} else {
return false;
}
}
public getModuleCount() : number {
return this.moduleCount;
}
public make() : void {
this.makeImpl(false, this.getBestMaskPattern() );
}
private getBestMaskPattern() : number {
var minLostPoint = 0;
var pattern = 0;
for (var i = 0; i < 8; i += 1) {
this.makeImpl(true, i);
var lostPoint = QRUtil.getLostPoint(this);
if (i == 0 || minLostPoint > lostPoint) {
minLostPoint = lostPoint;
pattern = i;
}
}
return pattern;
}
private makeImpl(test : boolean, maskPattern : number) : void {
// initialize modules
this.moduleCount = this.typeNumber * 4 + 17;
this.modules = [];
for (var i = 0; i < this.moduleCount; i += 1) {
this.modules.push([]);
for (var j = 0; j < this.moduleCount; j += 1) {
this.modules[i].push(null);
}
}
this.setupPositionProbePattern(0, 0);
this.setupPositionProbePattern(this.moduleCount - 7, 0);
this.setupPositionProbePattern(0, this.moduleCount - 7);
this.setupPositionAdjustPattern();
this.setupTimingPattern();
this.setupTypeInfo(test, maskPattern);
if (this.typeNumber >= 7) {
this.setupTypeNumber(test);
}
var data = QRCode.createData(
this.typeNumber, this.errorCorrectLevel, this.qrDataList);
this.mapData(data, maskPattern);
}
private mapData(data : number[], maskPattern : number) : void {
var inc = -1;
var row = this.moduleCount - 1;
var bitIndex = 7;
var byteIndex = 0;
var maskFunc = QRUtil.getMaskFunc(maskPattern);
for (var col = this.moduleCount - 1; col > 0; col -= 2) {
if (col == 6) {
col -= 1;
}
while (true) {
for (var c = 0; c < 2; c += 1) {
if (this.modules[row][col - c] == null) {
var dark = false;
if (byteIndex < data.length) {
dark = ( ( (data[byteIndex] >>> bitIndex) & 1) == 1);
}
var mask = maskFunc(row, col - c);
if (mask) {
dark = !dark;
}
this.modules[row][col - c] = dark;
bitIndex -= 1;
if (bitIndex == -1) {
byteIndex += 1;
bitIndex = 7;
}
}
}
row += inc;
if (row < 0 || this.moduleCount <= row) {
row -= inc;
inc = -inc;
break;
}
}
}
}
private setupPositionAdjustPattern() : void {
var pos = QRUtil.getPatternPosition(this.typeNumber);
for (var i = 0; i < pos.length; i += 1) {
for (var j = 0; j < pos.length; j += 1) {
var row = pos[i];
var col = pos[j];
if (this.modules[row][col] != null) {
continue;
}
for (var r = -2; r <= 2; r += 1) {
for (var c = -2; c <= 2; c += 1) {
if (r == -2 || r == 2 || c == -2 || c == 2
|| (r == 0 && c == 0) ) {
this.modules[row + r][col + c] = true;
} else {
this.modules[row + r][col + c] = false;
}
}
}
}
}
}
private setupPositionProbePattern(row : number, col : number) : void {
for (var r = -1; r <= 7; r += 1) {
for (var c = -1; c <= 7; c += 1) {
if (row + r <= -1 || this.moduleCount <= row + r
|| col + c <= -1 || this.moduleCount <= col + c) {
continue;
}
if ( (0 <= r && r <= 6 && (c == 0 || c == 6) )
|| (0 <= c && c <= 6 && (r == 0 || r == 6) )
|| (2 <= r && r <= 4 && 2 <= c && c <= 4) ) {
this.modules[row + r][col + c] = true;
} else {
this.modules[row + r][col + c] = false;
}
}
}
}
private setupTimingPattern() : void {
for (var r = 8; r < this.moduleCount - 8; r += 1) {
if (this.modules[r][6] != null) {
continue;
}
this.modules[r][6] = r % 2 == 0;
}
for (var c = 8; c < this.moduleCount - 8; c += 1) {
if (this.modules[6][c] != null) {
continue;
}
this.modules[6][c] = c % 2 == 0;
}
}
private setupTypeNumber(test : boolean) : void {
var bits = QRUtil.getBCHTypeNumber(this.typeNumber);
for (var i = 0; i < 18; i += 1) {
this.modules[~~(i / 3)][i % 3 + this.moduleCount - 8 - 3] =
!test && ( (bits >> i) & 1) == 1;
}
for (var i = 0; i < 18; i += 1) {
this.modules[i % 3 + this.moduleCount - 8 - 3][~~(i / 3)] =
!test && ( (bits >> i) & 1) == 1;
}
}
private setupTypeInfo(test : boolean, maskPattern : number) : void {
var data = (this.errorCorrectLevel << 3) | maskPattern;
var bits = QRUtil.getBCHTypeInfo(data);
// vertical
for (var i = 0; i < 15; i += 1) {
var mod = !test && ( (bits >> i) & 1) == 1;
if (i < 6) {
this.modules[i][8] = mod;
} else if (i < 8) {
this.modules[i + 1][8] = mod;
} else {
this.modules[this.moduleCount - 15 + i][8] = mod;
}
}
// horizontal
for (var i = 0; i < 15; i += 1) {
var mod = !test && ( (bits >> i) & 1) == 1;
if (i < 8) {
this.modules[8][this.moduleCount - i - 1] = mod;
} else if (i < 9) {
this.modules[8][15 - i - 1 + 1] = mod;
} else {
this.modules[8][15 - i - 1] = mod;
}
}
// fixed
this.modules[this.moduleCount - 8][8] = !test;
}
public static createData(
typeNumber : number,
errorCorrectLevel : ErrorCorrectLevel,
dataArray : QRData[]
) : number[] {
var rsBlocks : RSBlock[] = RSBlock.getRSBlocks(
typeNumber, errorCorrectLevel);
var buffer = new BitBuffer();
for (var i = 0; i < dataArray.length; i += 1) {
var data = dataArray[i];
buffer.put(data.getMode(), 4);
buffer.put(data.getLength(), data.getLengthInBits(typeNumber) );
data.write(buffer);
}
// calc max data count
var totalDataCount = 0;
for (var i = 0; i < rsBlocks.length; i += 1) {
totalDataCount += rsBlocks[i].getDataCount();
}
if (buffer.getLengthInBits() > totalDataCount * 8) {
throw 'code length overflow. ('
+ buffer.getLengthInBits()
+ '>'
+ totalDataCount * 8
+ ')';
}
// end
if (buffer.getLengthInBits() + 4 <= totalDataCount * 8) {
buffer.put(0, 4);
}
// padding
while (buffer.getLengthInBits() % 8 != 0) {
buffer.putBit(false);
}
// padding
while (true) {
if (buffer.getLengthInBits() >= totalDataCount * 8) {
break;
}
buffer.put(QRCode.PAD0, 8);
if (buffer.getLengthInBits() >= totalDataCount * 8) {
break;
}
buffer.put(QRCode.PAD1, 8);
}
return QRCode.createBytes(buffer, rsBlocks);
}
private static createBytes(
buffer : BitBuffer,
rsBlocks : RSBlock[]
) : number[] {
var offset = 0;
var maxDcCount = 0;
var maxEcCount = 0;
var dcdata : number[][] = [];
var ecdata : number[][] = [];
for (var r = 0; r < rsBlocks.length; r += 1) {
dcdata.push([]);
ecdata.push([]);
}
function createNumArray(len : number) : number[] {
var a : number[] = [];
for (var i = 0; i < len; i += 1) {
a.push(0);
}
return a;
}
for (var r = 0; r < rsBlocks.length; r += 1) {
var dcCount = rsBlocks[r].getDataCount();
var ecCount = rsBlocks[r].getTotalCount() - dcCount;
maxDcCount = Math.max(maxDcCount, dcCount);
maxEcCount = Math.max(maxEcCount, ecCount);
dcdata[r] = createNumArray(dcCount);
for (var i = 0; i < dcdata[r].length; i += 1) {
dcdata[r][i] = 0xff & buffer.getBuffer()[i + offset];
}
offset += dcCount;
var rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount);
var rawPoly = new Polynomial(dcdata[r], rsPoly.getLength() - 1);
var modPoly = rawPoly.mod(rsPoly);
ecdata[r] = createNumArray(rsPoly.getLength() - 1);
for (var i = 0; i < ecdata[r].length; i += 1) {
var modIndex = i + modPoly.getLength() - ecdata[r].length;
ecdata[r][i] = (modIndex >= 0)? modPoly.getAt(modIndex) : 0;
}
}
var totalCodeCount = 0;
for (var i = 0; i < rsBlocks.length; i += 1) {
totalCodeCount += rsBlocks[i].getTotalCount();
}
var data = createNumArray(totalCodeCount);
var index = 0;
for (var i = 0; i < maxDcCount; i += 1) {
for (var r = 0; r < rsBlocks.length; r += 1) {
if (i < dcdata[r].length) {
data[index] = dcdata[r][i];
index += 1;
}
}
}
for (var i = 0; i < maxEcCount; i += 1) {
for (var r = 0; r < rsBlocks.length; r += 1) {
if (i < ecdata[r].length) {
data[index] = ecdata[r][i];
index += 1;
}
}
}
return data;
}
public toDataURL(cellSize = 2, margin = cellSize * 4) : string {
var mods = this.getModuleCount();
var size = cellSize * mods + margin * 2;
var gif = new com.d_project.image.GIFImage(size, size);
for (var y = 0; y < size; y += 1) {
for (var x = 0; x < size; x += 1) {
if (margin <= x && x < size - margin &&
margin <= y && y < size - margin &&
this.isDark(
~~( (y - margin) / cellSize),
~~( (x - margin) / cellSize) ) ) {
gif.setPixel(x, y, 0);
} else {
gif.setPixel(x, y, 1);
}
}
}
return gif.toDataURL();
}
// by default, SJIS encoding is applied.
public static stringToBytes = stringToBytes_SJIS;
}
} | the_stack |
import { OverrideContext, bindingMode } from 'aurelia-binding';
import { View, ViewFactory, ViewSlot } from 'aurelia-templating';
declare enum ActivationStrategy {
/**
* Default activation strategy; the 'activate' lifecycle hook will be invoked when the model changes.
*/
InvokeLifecycle = "invoke-lifecycle",
/**
* The view/view-model will be recreated, when the "model" changes.
*/
Replace = "replace"
}
/**
* Used to compose a new view / view-model template or bind to an existing instance.
*/
export declare class Compose {
/**
* Model to bind the custom element to.
*
* @property model
* @type {CustomElement}
*/
model: any;
/**
* View to bind the custom element to.
*
* @property view
* @type {HtmlElement}
*/
view: any;
/**
* View-model to bind the custom element's template to.
*
* @property viewModel
* @type {Class}
*/
viewModel: any;
/**
* Strategy to activate the view-model. Default is "invoke-lifecycle".
* Bind "replace" to recreate the view/view-model when the model changes.
*
* @property activationStrategy
* @type {ActivationStrategy}
*/
activationStrategy: ActivationStrategy;
/**
* SwapOrder to control the swapping order of the custom element's view.
*
* @property view
* @type {String}
*/
swapOrder: any;
/**
* Creates an instance of Compose.
* @param element The Compose element.
* @param container The dependency injection container instance.
* @param compositionEngine CompositionEngine instance to compose the element.
* @param viewSlot The slot the view is injected in to.
* @param viewResources Collection of resources used to compile the the view.
* @param taskQueue The TaskQueue instance.
*/
constructor(element: any, container: any, compositionEngine: any, viewSlot: any, viewResources: any, taskQueue: any);
/**
* Invoked when the component has been created.
*
* @param owningView The view that this component was created inside of.
*/
created(owningView: View): void;
/**
* Used to set the bindingContext.
*
* @param bindingContext The context in which the view model is executed in.
* @param overrideContext The context in which the view model is executed in.
*/
bind(bindingContext: any, overrideContext: any): void;
/**
* Unbinds the Compose.
*/
unbind(): void;
/**
* Invoked everytime the bound model changes.
* @param newValue The new value.
* @param oldValue The old value.
*/
modelChanged(newValue: any, oldValue: any): void;
/**
* Invoked everytime the bound view changes.
* @param newValue The new value.
* @param oldValue The old value.
*/
viewChanged(newValue: any, oldValue: any): void;
/**
* Invoked everytime the bound view model changes.
* @param newValue The new value.
* @param oldValue The old value.
*/
viewModelChanged(newValue: any, oldValue: any): void;
}
declare class IfCore {
constructor(viewFactory: ViewFactory, viewSlot: ViewSlot);
bind(bindingContext: any, overrideContext: any): void;
unbind(): void;
}
/**
* Binding to conditionally include or not include template logic depending on returned result
* - value should be Boolean or will be treated as such (truthy / falsey)
*/
export declare class If extends IfCore {
condition: any;
swapOrder: 'before' | 'with' | 'after';
cache: boolean | string;
/**
* Binds the if to the binding context and override context
* @param bindingContext The binding context
* @param overrideContext An override context for binding.
*/
bind(bindingContext: any, overrideContext: any): void;
/**
* Invoked everytime value property changes.
* @param newValue The new value
*/
conditionChanged(newValue: any): void;
}
export declare class Else extends IfCore {
constructor(viewFactory: any, viewSlot: any);
bind(bindingContext: any, overrideContext: any): void;
}
/**
* Creates a binding context for decandant elements to bind to.
*/
export declare class With {
value: any;
/**
* Creates an instance of With.
* @param viewFactory The factory generating the view.
* @param viewSlot The slot the view is injected in to.
*/
constructor(viewFactory: ViewFactory, viewSlot: ViewSlot);
/**
* Binds the With with provided binding context and override context.
* @param bindingContext The binding context.
* @param overrideContext An override context for binding.
*/
bind(bindingContext: any, overrideContext: any): void;
/**
* Invoked everytime the bound value changes.
* @param newValue The new value.
*/
valueChanged(newValue: any): void;
/**
* Unbinds With
*/
unbind(): void;
}
/**
* An abstract base class for elements and attributes that repeat
* views.
*/
export declare class AbstractRepeater {
constructor(options: any);
/**
* Returns the number of views the repeater knows about.
*
* @return {Number} the number of views.
*/
viewCount(): number;
/**
* Returns all of the repeaters views as an array.
*
* @return {Array} The repeater's array of views;
*/
views(): any[];
/**
* Returns a single view from the repeater at the provided index.
*
* @param {Number} index The index of the requested view.
* @return {View|ViewSlot} The requested view.
*/
view(index: any): any;
/**
* Returns the matcher function to be used by the repeater, or null if strict matching is to be performed.
*
* @return {Function|null} The requested matcher function.
*/
matcher(): void;
/**
* Adds a view to the repeater, binding the view to the
* provided contexts.
*
* @param {Object} bindingContext The binding context to bind the new view to.
* @param {Object} overrideContext A secondary binding context that can override the primary context.
*/
addView(bindingContext: any, overrideContext: any): void;
/**
* Inserts a view to the repeater at a specific index, binding the view to the
* provided contexts.
*
* @param {Number} index The index at which to create the new view at.
* @param {Object} bindingContext The binding context to bind the new view to.
* @param {Object} overrideContext A secondary binding context that can override the primary context.
*/
insertView(index: any, bindingContext: any, overrideContext: any): void;
/**
* Moves a view across the repeater.
*
* @param {Number} sourceIndex The index of the view to be moved.
* @param {Number} sourceIndex The index where the view should be placed at.
*/
moveView(sourceIndex: any, targetIndex: any): void;
/**
* Removes all views from the repeater.
* @param {Boolean} returnToCache Should the view be returned to the view cache?
* @param {Boolean} skipAnimation Should the removal animation be skipped?
* @return {Promise|null}
*/
removeAllViews(returnToCache?: boolean, skipAnimation?: boolean): void;
/**
* Removes an array of Views from the repeater.
*
* @param {Array} viewsToRemove The array of views to be removed.
* @param {Boolean} returnToCache Should the view be returned to the view cache?
* @param {Boolean} skipAnimation Should the removal animation be skipped?
* @return {Promise|null}
*/
removeViews(viewsToRemove: Array<View>, returnToCache?: boolean, skipAnimation?: boolean): void;
/**
* Removes a view from the repeater at a specific index.
*
* @param {Number} index The index of the view to be removed.
* @param {Boolean} returnToCache Should the view be returned to the view cache?
* @param {Boolean} skipAnimation Should the removal animation be skipped?
* @return {Promise|null}
*/
removeView(index: number, returnToCache?: boolean, skipAnimation?: boolean): void;
/**
* Forces a particular view to update it's bindings, called as part of
* an in-place processing of items for better performance
*
* @param {Object} view the target view for bindings updates
*/
updateBindings(view: View): void;
}
/**
* Binding to iterate over iterable objects (Array, Map and Number) to genereate a template for each iteration.
*/
export declare class Repeat extends AbstractRepeater {
/**
* Setting this to `true` to enable legacy behavior, where a repeat would take first `matcher` binding
* any where inside its view if there's no `matcher` binding on the repeated element itself.
*
* Default value is true to avoid breaking change
* @default true
*/
static useInnerMatcher: boolean;
/**
* List of items to bind the repeater to.
*
* @property items
*/
items: any;
/**
* Local variable which gets assigned on each iteration.
*
* @property local
*/
local: any;
/**
* Key when iterating over Maps.
*
* @property key
*/
key: any;
/**
* Value when iterating over Maps.
*
* @property value
*/
value: any;
/**
* Creates an instance of Repeat.
* @param viewFactory The factory generating the view
* @param instruction The instructions for how the element should be enhanced.
* @param viewResources Collection of resources used to compile the the views.
* @param viewSlot The slot the view is injected in to.
* @param observerLocator The observer locator instance.
* @param collectionStrategyLocator The strategy locator to locate best strategy to iterate the collection.
*/
constructor(viewFactory: any, instruction: any, viewSlot: any, viewResources: any, observerLocator: any, strategyLocator: any);
call(context: any, changes: any): void;
/**
* Binds the repeat to the binding context and override context.
* @param bindingContext The binding context.
* @param overrideContext An override context for binding.
*/
bind(bindingContext: any, overrideContext: any): void;
/**
* Unbinds the repeat
*/
unbind(): void;
/**
* Invoked everytime the item property changes.
*/
itemsChanged(): void;
/**
* Invoked when the underlying collection changes.
*/
handleCollectionMutated(collection: any, changes: any): void;
/**
* Invoked when the underlying inner collection changes.
*/
handleInnerCollectionMutated(collection: any, changes: any): void;
viewCount(): any;
views(): any;
view(index: any): any;
matcher(): any;
addView(bindingContext: any, overrideContext: any): void;
insertView(index: any, bindingContext: any, overrideContext: any): void;
moveView(sourceIndex: any, targetIndex: any): void;
removeAllViews(returnToCache: any, skipAnimation: any): any;
removeViews(viewsToRemove: any, returnToCache: any, skipAnimation: any): any;
removeView(index: any, returnToCache: any, skipAnimation: any): any;
updateBindings(view: View): void;
}
/**
* Binding to conditionally show markup in the DOM based on the value.
* - different from "if" in that the markup is still added to the DOM, simply not shown.
*/
export declare class Show {
value: any;
/**
* Creates a new instance of Show.
* @param element Target element to conditionally show.
* @param animator The animator that conditionally adds or removes the aurelia-hide css class.
* @param domBoundary The DOM boundary. Used when the behavior appears within a component that utilizes the shadow DOM.
*/
constructor(element: any, animator: any, domBoundary: any);
/**
* Invoked when the behavior is created.
*/
created(): void;
/**
* Invoked everytime the bound value changes.
* @param newValue The new value.
*/
valueChanged(newValue: any): void;
/**
* Binds the Show attribute.
*/
bind(bindingContext: any): void;
}
/**
* Binding to conditionally show markup in the DOM based on the value.
* - different from "if" in that the markup is still added to the DOM, simply not shown.
*/
export declare class Hide {
/**
* Creates a new instance of Hide.
* @param element Target element to conditionally hide.
* @param animator The animator that conditionally adds or removes the aurelia-hide css class.
* @param domBoundary The DOM boundary. Used when the behavior appears within a component that utilizes the shadow DOM.
*/
constructor(element: any, animator: any, domBoundary: any);
/**
* Invoked when the behavior is created.
*/
created(): void;
/**
* Invoked everytime the bound value changes.
* @param newValue The new value.
*/
valueChanged(newValue: any): void;
/**
* Binds the Hide attribute.
*/
bind(bindingContext: any): void;
value(value: any): void;
}
/**
* Default Html Sanitizer to prevent script injection.
*/
export declare class HTMLSanitizer {
/**
* Sanitizes the provided input.
* @param input The input to be sanitized.
*/
sanitize(input: any): any;
}
/**
* Simple html sanitization converter to preserve whitelisted elements and attributes on a bound property containing html.
*/
export declare class SanitizeHTMLValueConverter {
/**
* Creates an instanse of the value converter.
* @param sanitizer The html sanitizer.
*/
constructor(sanitizer: HTMLSanitizer);
/**
* Process the provided markup that flows to the view.
* @param untrustedMarkup The untrusted markup to be sanitized.
*/
toView(untrustedMarkup: any): any;
}
/**
* Marks any part of a view to be replacable by the consumer.
*/
export declare class Replaceable {
/**
* @param viewFactory target The factory generating the view.
* @param viewSlot viewSlot The slot the view is injected in to.
*/
constructor(viewFactory: ViewFactory, viewSlot: ViewSlot);
/**
* Binds the replaceable to the binding context and override context.
* @param bindingContext The binding context.
* @param overrideContext An override context for binding.
*/
bind(bindingContext: any, overrideContext: any): void;
/**
* Unbinds the replaceable.
*/
unbind(): void;
}
/**
* CustomAttribute that binds provided DOM element's focus attribute with a property on the viewmodel.
*/
export declare class Focus {
/**
* Creates an instance of Focus.
* @paramelement Target element on where attribute is placed on.
* @param taskQueue The TaskQueue instance.
*/
constructor(element: any, taskQueue: any);
/**
* Invoked everytime the bound value changes.
* @param newValue The new value.
*/
valueChanged(newValue: any): void;
/**
* Invoked when the attribute is attached to the DOM.
*/
attached(): void;
/**
* Invoked when the attribute is detached from the DOM.
*/
detached(): void;
handleEvent(e: any): void;
}
export declare class AttrBindingBehavior {
bind(binding: any, source: any): void;
unbind(binding: any, source: any): void;
}
export declare class OneTimeBindingBehavior {
mode: bindingMode;
constructor();
}
export declare class OneWayBindingBehavior {
mode: bindingMode;
constructor();
}
export declare class ToViewBindingBehavior {
mode: bindingMode;
constructor();
}
export declare class FromViewBindingBehavior {
mode: bindingMode;
constructor();
}
export declare class TwoWayBindingBehavior {
mode: bindingMode;
constructor();
}
export declare class ThrottleBindingBehavior {
bind(binding: any, source: any, delay?: number): void;
unbind(binding: any, source: any): void;
}
export declare class DebounceBindingBehavior {
bind(binding: any, source: any, delay?: number): void;
unbind(binding: any, source: any): void;
}
export declare class SelfBindingBehavior {
bind(binding: any, source: any): void;
unbind(binding: any, source: any): void;
}
export declare class SignalBindingBehavior {
signals: any;
constructor(bindingSignaler: any);
bind(binding: any, source: any, ...names: any[]): void;
unbind(binding: any, source: any): void;
}
export declare class BindingSignaler {
signals: {};
signal(name: string): void;
}
export declare class UpdateTriggerBindingBehavior {
bind(binding: any, source: any, ...events: any[]): void;
unbind(binding: any, source: any): void;
}
/**
* A strategy is for repeating a template over an iterable or iterable-like object.
*/
export interface RepeatStrategy {
instanceChanged(repeat: Repeat, items: any): void;
instanceMutated(repeat: Repeat, items: any, changes: any): void;
getCollectionObserver(observerLocator: any, items: any): any;
}
/**
* Locates the best strategy to best repeating a template over different types of collections.
* Custom strategies can be plugged in as well.
*/
export declare class RepeatStrategyLocator {
/**
* Creates a new RepeatStrategyLocator.
*/
constructor();
/**
* Adds a repeat strategy to be located when repeating a template over different collection types.
* @param strategy A repeat strategy that can iterate a specific collection type.
*/
addStrategy(matcher: (items: any) => boolean, strategy: RepeatStrategy): void;
/**
* Gets the best strategy to handle iteration.
*/
getStrategy(items: any): RepeatStrategy;
}
/**
* A strategy for repeating a template over null or undefined (does nothing)
*/
export declare class NullRepeatStrategy {
instanceChanged(repeat: any, items: any): void;
getCollectionObserver(observerLocator: any, items: any): void;
}
/**
* A strategy for repeating a template over an array.
*/
export declare class ArrayRepeatStrategy {
/**
* Gets an observer for the specified collection.
* @param observerLocator The observer locator instance.
* @param items The items to be observed.
*/
getCollectionObserver(observerLocator: any, items: any): any;
/**
* Handle the repeat's collection instance changing.
* @param repeat The repeater instance.
* @param items The new array instance.
*/
instanceChanged(repeat: any, items: any): void;
/**
* Handle the repeat's collection instance mutating.
* @param repeat The repeat instance.
* @param array The modified array.
* @param splices Records of array changes.
*/
instanceMutated(repeat: any, array: any, splices: any): void;
}
/**
* A strategy for repeating a template over a Map.
*/
export declare class MapRepeatStrategy {
/**
* Gets a Map observer.
* @param items The items to be observed.
*/
getCollectionObserver(observerLocator: any, items: any): any;
/**
* Process the provided Map entries.
* @param items The entries to process.
*/
instanceChanged(repeat: any, items: any): void;
/**
* Handle changes in a Map collection.
* @param map The underlying Map collection.
* @param records The change records.
*/
instanceMutated(repeat: any, map: any, records: any): void;
}
/**
* A strategy for repeating a template over a Set.
*/
export declare class SetRepeatStrategy {
/**
* Gets a Set observer.
* @param items The items to be observed.
*/
getCollectionObserver(observerLocator: any, items: any): any;
/**
* Process the provided Set entries.
* @param items The entries to process.
*/
instanceChanged(repeat: any, items: any): void;
/**
* Handle changes in a Set collection.
* @param repeat The repeat instance.
* @param set The underlying Set collection.
* @param records The change records.
*/
instanceMutated(repeat: any, set: any, records: any): void;
}
/**
* A strategy for repeating a template over a number.
*/
export declare class NumberRepeatStrategy {
/**
* Return the strategies collection observer. In this case none.
*/
getCollectionObserver(): any;
/**
* Process the provided Number.
* @param value The Number of how many time to iterate.
*/
instanceChanged(repeat: any, value: any): void;
}
/**
* Creates a complete override context.
* @param data The item's value.
* @param index The item's index.
* @param length The collections total length.
* @param key The key in a key/value pair.
*/
export declare function createFullOverrideContext(repeat: any, data: any, index: any, length: any, key?: string): OverrideContext;
/**
* Updates the override context.
* @param context The context to be updated.
* @param index The context's index.
* @param length The collection's length.
*/
export declare function updateOverrideContext(overrideContext: any, index: any, length: any): void;
/**
* Gets a repeat instruction's source expression.
*/
export declare function getItemsSourceExpression(instruction: any, attrName: any): any;
/**
* Unwraps an expression to expose the inner, pre-converted / behavior-free expression.
*/
export declare function unwrapExpression(expression: any): any;
/**
* Returns whether an expression has the OneTimeBindingBehavior applied.
*/
export declare function isOneTime(expression: any): boolean;
/**
* Forces a binding instance to reevaluate.
*/
export declare function updateOneTimeBinding(binding: any): void;
export declare function viewsRequireLifecycle(viewFactory: any): any;
export declare function configure(config: any): void; | the_stack |
import { Button, Icon, Popconfirm, Table } from 'antd'
import _, {
get,
isArray,
isBoolean,
isFunction,
isNumber,
isPlainObject,
isString,
} from 'lodash'
import { observer } from 'mobx-react'
// import { DragDropContextProvider } from 'react-dnd'
// import HTML5Backend from 'react-dnd-html5-backend'
import React from 'react'
import { JsonSchema } from '~/types'
import { getLabelByValue } from '~/utils'
import './index.less'
import { ActionColumn, TableColumn } from './interface'
import { addKeyToArray, Columns, getFormFields } from './_utils'
// 弹框表单
const tableEditModalAlias = '$$TableEditorForm'
@observer
class HtTableEditor extends Columns {
static displayName = 'HtTableEditor'
static defaultProps = {
onChange: () => {},
canAddChildren: false,
canAdd: true,
modalConfig: {
alias: tableEditModalAlias,
width: 600,
},
disabled: false,
canDelete: true,
}
state = {
clickedRow: {},
isAddChildren: false,
isEditChildren: false,
alias: get(this.props, 'modalConfig.alias', tableEditModalAlias),
modalWidth: get(this.props, 'modalConfig.width', 600),
}
HtModalEditForm?: {
toggleModalVisible: (v: boolean) => Promise<void>
}
HtModalAddForm?: {
toggleModalVisible: (v: boolean) => Promise<void>
}
// 点击编辑按钮时
onEditBtnClick = async (
record: JsonSchema.DynamicObject,
isEditChildren?: boolean
) => {
const { setStoreState } = this.props.pagestate
if (isFunction(setStoreState)) {
const alias = this.state.alias
setStoreState({
[alias]: record,
})
this.setState(
{
clickedRow: record,
isAddChildren: false,
isEditChildren,
},
() => this.toggleModalEditForm(true)
)
}
}
// 点击添加按钮时
onAddBtnClick = () => {
this.setState({
isAddChildren: false,
})
this.toggleModalAddForm(true)
}
// 点击添加子元素按钮时
onAddChildrenBtnClick = async (record: JsonSchema.DynamicObject) => {
this.setState(
{
clickedRow: record,
isAddChildren: true,
},
() => this.toggleModalAddForm(true)
)
}
// 编辑弹框, 点击提交时
onEditModalOk = async (modalFormData: JsonSchema.DynamicObject) => {
await this.toggleModalEditForm(false)
const { isEditChildren, clickedRow } = this.state
switch (isEditChildren) {
case true:
// @ts-ignore
this.updateChild(clickedRow.parentKey, clickedRow.key, modalFormData)
break
default:
// @ts-ignore
this.update(clickedRow.key, {
...modalFormData,
// @ts-ignore
children: clickedRow.children,
})
}
}
// 创建数据弹框, 点击提交时
onAddModalOk = async (formData: JsonSchema.DynamicObject) => {
await this.toggleModalEditForm(false)
const { isAddChildren, clickedRow } = this.state
if (isAddChildren) {
// 添加二级节点
// @ts-ignore
return this.addChild(clickedRow.key, formData)
}
// 添加一级节点
this.add(formData)
}
toggleModalEditForm = async (visible: boolean) => {
const toggleModalVisible = get(this.HtModalEditForm, 'toggleModalVisible')
if (isFunction(toggleModalVisible)) {
await toggleModalVisible(visible)
}
}
/**
* 切换添加弹框可见状态
*/
toggleModalAddForm = (visible: boolean) => {
const toggleModalVisible = get(this.HtModalAddForm, 'toggleModalVisible')
if (isFunction(toggleModalVisible)) {
toggleModalVisible(visible)
}
}
/**
* 渲染弹框表单
*/
renderEditForm = (formFields: JsonSchema.HtFieldBaseProps[]) => {
const { alias, modalWidth, clickedRow, isEditChildren } = this.state
const { pagestate } = this.props
if (isPlainObject(clickedRow)) {
const modalFormProps = {
width: modalWidth,
fields: formFields,
alias,
title: isEditChildren ? '编辑子节点' : '编辑',
pagestate,
getRef: (c: any) => {
this.HtModalEditForm = c
},
sendFormData: (v: JsonSchema.DynamicObject) => this.onEditModalOk(v),
onSuccessAction: '',
}
const HtModalForm = _.get(window.$$componentMap, 'HtModalForm')
return React.createElement(HtModalForm, modalFormProps)
}
return null
}
/**
* 渲染新增数据弹框
*/
renderAddForm = (formFields: JsonSchema.HtFieldBaseProps[]) => {
const { isAddChildren, alias, modalWidth } = this.state
const { pagestate } = this.props
const modalFormProps = {
width: modalWidth,
fields: formFields,
alias,
title: isAddChildren ? '添加子节点' : '添加',
pagestate,
getRef: (c: any) => {
this.HtModalAddForm = c
},
sendFormData: (v: JsonSchema.DynamicObject) => this.onAddModalOk(v),
onSuccessAction: '',
}
const HtModalForm = _.get(window.$$componentMap, 'HtModalForm')
return React.createElement(HtModalForm, modalFormProps)
}
/**
* 渲染表格列
*/
renderColumns = (columns: TableColumn[], actionColumn?: ActionColumn) => {
const { canAddChildren, disabled, canDelete } = this.props
const extraColumn = {
title: '操作',
...actionColumn,
render: (_text: any, record: JsonSchema.DynamicObject) => {
if (disabled) {
return null
}
const isChildrenRow = !!record.parentKey
// 渲染子节点
if (isChildrenRow) {
return (
<div
style={{ whiteSpace: 'nowrap', textAlign: 'center' }}
onClick={e => e.stopPropagation()}
>
<Icon
type="edit"
className="table-row-link"
onClick={() => this.onEditBtnClick(record, isChildrenRow)}
/>
{canDelete && (
<Icon
type="delete"
className="table-row-link danger"
onClick={() => this.deleteChild(record.parentKey, record.key)}
/>
)}
</div>
)
}
return (
<div
style={{ whiteSpace: 'nowrap', textAlign: 'right' }}
onClick={e => e.stopPropagation()}
>
{canAddChildren && (
<Icon
type="plus"
className="table-row-link"
onClick={() => this.onAddChildrenBtnClick(record)}
/>
)}
<Icon
type="edit"
className="table-row-link"
onClick={() => this.onEditBtnClick(record)}
/>
{canDelete && (
<Popconfirm
title="确认删除"
onConfirm={() => this.delete(record.key)}
>
<Icon type="delete" className="table-row-link danger" />
</Popconfirm>
)}
</div>
)
},
}
const _columns = columns
.map(column => {
let render = (text: any) => {
if (
isString(text) ||
isNumber(text) ||
isBoolean(text) ||
isArray(text)
) {
if (column.type === 'SelectTrees') {
// @ts-ignore
const { labelField } = column
// @ts-ignore
return (text || []).map((item: any) => item[labelField]).join(',')
}
// 如果为基本类型
let type = column.type || 'Input'
if (
['Select', 'SelectMultiple', 'Radio', 'Checkbox'].indexOf(
type
) !== -1
) {
let {
options,
// @ts-ignore
optionsSourceType,
// @ts-ignore
optionsDependencies,
// @ts-ignore
labelField,
// @ts-ignore
valueField,
} = column
let _options = options
switch (optionsSourceType) {
case 'static':
_options = options
break
case 'dependencies':
_options = optionsDependencies
break
}
return getLabelByValue(text, _options, labelField, valueField)
}
return text
}
let other
try {
other = JSON.stringify(text)
} catch (e) {
console.warn(e)
}
return other
}
return {
render,
...column,
}
})
.filter(v => v.width !== 0 && v.width !== '0')
return [..._columns, extraColumn]
}
render() {
let {
disabled,
canAdd,
canAddChildren,
canDelete,
value,
onChange,
columns = [],
actionColumn,
scroll,
pagestate,
...otherProps
} = this.props
let _dataSource: JsonSchema.DynamicObject[] = []
// 给数据加上key/序号
if (Array.isArray(value)) {
_dataSource = addKeyToArray(value)
}
this.dataSource = _dataSource
const tableProps = {
...otherProps,
scroll,
dataSource: _dataSource,
rowKey: (record: JsonSchema.DynamicObject) => record.key,
columns: this.renderColumns(columns, actionColumn),
bordered: true,
defaultExpandAllRows: true,
expandIcon: undefined,
pagination: false as false,
rowClassName: (record: JsonSchema.DynamicObject, index: number) =>
record.parentKey ? `__children__${index}` : `__parent__${index}`,
}
const formFields = getFormFields(columns)
return (
<div
className="ht-table-editor"
data-pageconfig-path={`${this.props['data-pageconfig-path']}`}
>
{/* 新建弹框 */}
{canAdd && (
<Button
disabled={disabled}
onClick={this.onAddBtnClick}
size="small"
style={{ marginBottom: 16 }}
>
添加
</Button>
)}
{canAdd && this.renderAddForm(formFields)}
{/* <DragDropContextProvider backend={HTML5Backend}> */}
{/* 表格 */}
<Table
className={_dataSource.length > 0 ? '' : 'ht-tables-editor'}
{...tableProps}
/>
{/* </DragDropContextProvider> */}
{/* 编辑弹框 */}
{this.renderEditForm(formFields)}
</div>
)
}
}
export default HtTableEditor | the_stack |
import language from "../language_pack/selected_language"
import { logger } from "../logger/logger";
const Web3 = require('web3');
class CommsHandler {
public readonly HTTP_PROVIDER : string;
public readonly CHAIN_ID : number;
public readonly web3;
private signed_tx : [Promise<Object>] = [new Promise<Object>(function(){})];
private private_keys : string[] = [];
private gas_amount : string;
private target_contract : string;
/**
* @private
* @property
* @description GWEI per unit of gas
*/
private gas_price : string;
/**
* @private
* @property
* @description amount in ETHER of BNB to send
*/
private amount : string;
public readonly WBNB_ADDRESS : string;
public readonly BUSD_ADDRESS : string;
private readonly PCS_ROUTER_CA : string;
private readonly PCS_FACTORY_CA : string;
private readonly PCS_ROUTER_ABI : string = '[{"inputs":[{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactETHForTokensSupportingFeeOnTransferTokens","outputs":[],"stateMutability":"payable","type":"function"}, {"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactTokensForTokensSupportingFeeOnTransferTokens","outputs":[],"stateMutability":"nonpayable","type":"function"}]';
private readonly PCS_FACTORY_ABI : string = '[{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"getPair","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"}]';
public readonly NOPAIR : string = '0x0000000000000000000000000000000000000000'
private readonly BALANCE_ABI : string = '[{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]'
public readonly pcs_factory : any;
public readonly pcs_router : any;
private target_contract_callable : any;
private swap_deadline : any;
/**
* Creates a new handler and initializes web3 connection.
* @constructor
* @param {boolean} useTestnet if false (default) txs will be executed on mainnet - testnet otherwise.
* @param {number} gas_price price in gwei per unit of gas.
* @param {number} gas_amount amount of gas in gwei.
* @param {string} amount amount to buy.
* */
constructor(useTestnet : boolean = false, gas_price : string = '10', gas_amount : string = '500000', amount : string) {
this.HTTP_PROVIDER = (useTestnet ? "https://data-seed-prebsc-1-s1.binance.org:8545" : "https://bsc-dataseed1.binance.org:443");
this.CHAIN_ID = (useTestnet ? 97 : 56);
this.web3 = new Web3(new Web3.providers.HttpProvider(this.HTTP_PROVIDER));
this.gas_price = gas_price;
this.gas_amount = gas_amount;
this.amount = amount;
this.signed_tx.pop();
if (useTestnet) {
this.WBNB_ADDRESS = "0xae13d989dac2f0debff460ac112a837c89baa7cd";
this.BUSD_ADDRESS = "0x78867BbEeF44f2326bF8DDd1941a4439382EF2A7";
this.PCS_ROUTER_CA = "0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3";
this.PCS_FACTORY_CA = "0x6725F303b657a9451d8BA641348b6761A6CC7a17";
}
else {
this.WBNB_ADDRESS = "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c";
this.BUSD_ADDRESS = "0xe9e7cea3dedca5984780bafc599bd69add087d56";
this.PCS_ROUTER_CA = "0x10ED43C718714eb63d5aA57B78B54704E256024E";
this.PCS_FACTORY_CA = "0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73";
}
this.pcs_factory = new this.web3.eth.Contract(JSON.parse(this.PCS_FACTORY_ABI), this.PCS_FACTORY_CA);
this.pcs_router = new this.web3.eth.Contract(JSON.parse(this.PCS_ROUTER_ABI), this.PCS_ROUTER_CA);
}
/**
* @method setTargetContract() sets contract to snipe.
* @param {string} target_contract contract to snipe.
* @returns {void}
* @throws Will throw error if address not valid.
*/
public setTargetContract(target_contract : string) : void {
if (!this.web3.utils.isAddress(target_contract))
throw new Error(language.lang.ADDR_NOT_VALID);
this.target_contract = target_contract;
this.target_contract_callable = new this.web3.eth.Contract(JSON.parse(this.BALANCE_ABI), this.target_contract);
}
public getTargetContract() : string {
return this.target_contract;
}
public getTargetContractCallable() {
return this.target_contract_callable;
}
public getSwapDeadline() {
return this.swap_deadline;
}
/**
* @private
* @method verifyPrivateKey() check if private key is valid.
* @param {string} private_key private key to verify. NOTE: remove '0x' prefix.
* @returns {boolean} true if valid, false otherwise.
* */
private verifyPrivateKey(private_key : string) : boolean {
try {
this.web3.eth.accounts.privateKeyToAccount(private_key);
return true;
} catch (error) {
return false;
}
}
/**
* @method addPrivateKeys() set private keys to sign transaction with (ALL private keys will be used).
* @param {string[]} private_keys array of private keys to sign transaction with (ALL private keys will be used). NOTE: remove "0x" prefix.
* @returns {void}
* @throws Will throw error if private keys are not correct.
* */
public addPrivateKeys(private_keys : string[]) : void {
private_keys.forEach( (key : string) => {
if (!this.verifyPrivateKey(key))
throw new Error(language.lang.PVT_KEY_NOT_VALID);
})
this.private_keys = this.private_keys.concat(private_keys);
}
/**
* @function preparePresaleTXs() prepare txs to sign
* @returns {void}
* @throws Will throw error if gas settings are wrong (or other are incosistent).
*/
//TODO: implementare logs degli errori col callback
public preparePresaleTXs() : void {
this.private_keys.forEach((key : string) => {
this.signed_tx.push(this.web3.eth.accounts.signTransaction(
{
value: this.web3.utils.toHex(this.web3.utils.toWei(this.amount, 'ether')),
gas: this.web3.utils.toHex(this.gas_amount),
gasPrice: this.web3.utils.toHex(this.web3.utils.toWei(this.gas_price, 'gwei')),
chainId: this.CHAIN_ID,
to: this.target_contract,
},
key,
null
)
);
});
}
/**
* @function prepareFairlaunchTXs() prepare txs to sign
* @returns {void}
* @throws Will throw error if gas settings are wrong.
*/
//TODO: implementare logs degli errori col callback
public async prepareFairlaunchTXs(bnb_pair : boolean) {
//lines needed if there is the necessity to re-prepare the txs (in case of deadline reached)
this.signed_tx = [new Promise<Object>(function(){})];
this.signed_tx.pop();
this.swap_deadline = (new Date()).getTime() + 1000 * 60 * 20;
for (var key of this.private_keys) {
if (bnb_pair) {
this.signed_tx.push(
this.web3.eth.accounts.signTransaction(
{
'from': await this.web3.eth.accounts.privateKeyToAccount(key).address,
'to': this.PCS_ROUTER_CA,
'value': this.web3.utils.toHex(this.web3.utils.toWei(this.amount, 'ether')),
'chainId': this.CHAIN_ID,
'gas': this.web3.utils.toHex(this.gas_amount),
'gasPrice': this.web3.utils.toHex(this.web3.utils.toWei(this.gas_price, 'gwei')),
'data': this.pcs_router.methods.swapExactETHForTokensSupportingFeeOnTransferTokens(
this.web3.utils.toHex(this.web3.utils.toWei('0', 'ether')), //SLIPPAGE 100%
[this.WBNB_ADDRESS, this.target_contract],
await this.web3.eth.accounts.privateKeyToAccount(key).address,
this.web3.utils.toHex(this.swap_deadline)
).encodeABI()
},
key,
null
)
);
}
else {
this.signed_tx.push(
this.web3.eth.accounts.signTransaction(
{
'from': await this.web3.eth.accounts.privateKeyToAccount(key).address,
'to': this.PCS_ROUTER_CA,
'chainId': this.CHAIN_ID,
'gas': this.web3.utils.toHex(this.gas_amount),
'gasPrice': this.web3.utils.toHex(this.web3.utils.toWei(this.gas_price, 'gwei')),
'data': this.pcs_router.methods.swapExactTokensForTokensSupportingFeeOnTransferTokens(
this.web3.utils.toHex(this.web3.utils.toWei(this.amount, 'ether')),
this.web3.utils.toHex(this.web3.utils.toWei('0', 'ether')), //SLIPPAGE 100%
[this.BUSD_ADDRESS, this.target_contract],
await this.web3.eth.accounts.privateKeyToAccount(key).address,
this.web3.utils.toHex(this.swap_deadline)
).encodeABI()
},
key,
null
)
);
}
}
}
/**
* @function defaultCallback()
* default callback to be used after tx has been issued to the blockchain via web3.eth.sendSignedTransaction();
* @param {Error} error error - if any - issuing the transaction.
* @param {result} result transaction hash - if successfull.
*/
private defaultCallback(error : Error, result : any) {
if (error)
console.log(error);
else
console.log(result);
}
/**
* @method sendTXs()
* @throws Will throw an error for wrong gas settings or insufficient balance.
*/
public sendTXs(callback : Function) : void {
this.signed_tx.forEach(async (sig_tx: any) => {
this.web3.eth.sendSignedTransaction((await sig_tx).rawTransaction, (error : Error, result : any) => {
if (!callback)
this.defaultCallback(error, result);
else
callback(error, result);
console.log("\x1b[33m" + language.lang.WAITING_BLOCKCHAIN_CONFIRM + '\x1b[0m');
})
.on('receipt', () => {
console.log("\x1b[32m" + language.lang.TX_CONFIRMED + '\x1b[0m');
})
.on('error', (error : any) => {
console.log("\x1b[32m" + language.lang.TX_ERROR + '\x1b[0m');
console.log(error);
});
});
}
/**
* @method subscribeNewBlocks()
* Triggers callback on new blocks.
* @param {Function} callback callback function to be called on new blocks.
*/
public subscribeNewBlocks(callback : Function) : NodeJS.Timeout {
var previous_block : number;
return setInterval(
async function (){
try {
let current_block : number = await this.web3.eth.getBlockNumber();
if (current_block > previous_block || previous_block == undefined) {
previous_block = current_block;
callback(await this.web3.eth.getBlock('latest'));
}
} catch (err : any) {
logger.getInstance().notifyHandledException(err);
console.warn("====================" + language.lang.BLOCK_QUERY_ERR + "====================");
console.warn(err);
console.warn("====================" + language.lang.EOR + "====================");
console.warn(language.lang.SHOULD_NOT_INTERFER);
}
}.bind(this)
, 100
) ;
}
}
export {CommsHandler} | the_stack |
import { AfterContentInit, ContentChildren, Directive, ElementRef, EventEmitter, HostBinding,
Input, OnDestroy, Output, QueryList, Renderer2, Inject, Optional, Self, HostListener } from '@angular/core';
import { MDCDismissibleDrawerFoundation, MDCModalDrawerFoundation, MDCDrawerAdapter } from '@material/drawer';
import { asBoolean } from '../../utils/value.utils';
import { DOCUMENT } from '@angular/common';
import { AbstractMdcFocusTrap, FocusTrapHandle } from '../focus-trap/abstract.mdc.focus-trap';
import { MdcListItemDirective } from '../list/mdc.list.directive';
/**
* Directive for the title of a drawer. The use of this directive is optional.
* If used, it should be placed as first element inside an `mdcDrawerHeader`
*/
@Directive({
selector: '[mdcDrawerTitle]'
})
export class MdcDrawerTitleDirective {
/** @internal */
@HostBinding('class.mdc-drawer__title') readonly _cls = true;
}
/**
* Directive for the subtitle of a drawer. The use of this directive is optional.
* If used, it should be placed as a sibling element of `mdcDrawerTitle`
* inside an `mdcDrawerHeader`
*/
@Directive({
selector: '[mdcDrawerSubtitle]'
})
export class MdcDrawerSubtitleDirective {
/** @internal */
@HostBinding('class.mdc-drawer__subtitle') readonly _cls = true;
}
/**
* A toolbar header is an optional first child of an `mdcDrawer`.
* The header will not scroll with the rest of the drawer content, so is a
* good place to place titles and account switchers.
*
* Directives that are typically used inside an `mdcDrawerHeader`:
* `mdcDrawerTitle`, and `mdcDrawerSubTitle`
*/
@Directive({
selector: '[mdcDrawerHeader]'
})
export class MdcDrawerHeaderDirective {
/** @internal */
@HostBinding('class.mdc-drawer__header') readonly _cls = true;
}
/**
* Directive for the drawer content. You would typically also apply the `mdcList`
* or `mdcListGroup` directive to the drawer content (see the examples).
*/
@Directive({
selector: '[mdcDrawerContent]'
})
export class MdcDrawerContentDirective {
/** @internal */
@HostBinding('class.mdc-drawer__content') readonly _cls = true;
}
@Directive({
selector: '[mdcDrawerScrim]'
})
export class MdcDrawerScrimDirective {
/** @internal */
@HostBinding('class.mdc-drawer-scrim') readonly _cls = true;
}
/**
* Directive for a (navigation) drawer. The following drawer types are
* supported:
* * `permanent`: the default type if none was specified.
* * `dismissible`: the drawer is hidden by default, and can slide into view.
* Typically used when navigation is not common, and the main app content is
* prioritized.
* * `modal`: the drawer is hidden by default. When activated, the drawer is elevated
* above the UI of the app. It uses a scrim to block interaction with the rest of
* the app with a scrim.
*
* Drawers may contain an `mdcDrawerHeader`, and should contain an `mdcDrawerContent`
* directive.
*/
@Directive({
selector: '[mdcDrawer]'
})
export class MdcDrawerDirective implements AfterContentInit, OnDestroy {
/** @internal */
@HostBinding('class.mdc-drawer') readonly _cls = true;
/** @internal */
@ContentChildren(MdcListItemDirective, {descendants: true}) _items?: QueryList<MdcListItemDirective>;
private _onDocumentClick = (event: MouseEvent) => this.onDocumentClick(event);
private focusTrapHandle: FocusTrapHandle | null = null;
private type: 'permanent' | 'dismissible' | 'modal' = 'permanent';
private previousFocus: Element | HTMLOrSVGElement | null = null;
private _open: boolean | null = null;
private document: Document;
private mdcAdapter: MDCDrawerAdapter = {
addClass: (className) => this._rndr.addClass(this._elm.nativeElement, className),
removeClass: (className) => this._rndr.removeClass(this._elm.nativeElement, className),
hasClass: (className) => this._elm.nativeElement.classList.contains(className),
elementHasClass: (element, className) => element.classList.contains(className),
saveFocus: () => this.previousFocus = this.document.activeElement,
restoreFocus: () => {
const prev = this.previousFocus as HTMLOrSVGElement | null;
if (prev && prev.focus && this._elm.nativeElement.contains(this.document.activeElement))
prev.focus();
},
focusActiveNavigationItem: () => {
const active = this._items!.find(item => item.active);
active?._elm.nativeElement.focus();
},
notifyClose: () => {
this.fixOpenClose(false);
this.afterClosed.emit();
this.document.removeEventListener('click', this._onDocumentClick);
},
notifyOpen: () => {
this.fixOpenClose(true);
this.afterOpened.emit();
if (this.type === 'modal')
this.document.addEventListener('click', this._onDocumentClick);
},
trapFocus: () => this.trapFocus(),
releaseFocus: () => this.untrapFocus()
};
private foundation: MDCDismissibleDrawerFoundation | null = null; // MDCModalDrawerFoundation extends MDCDismissibleDrawerFoundation
/**
* Event emitted when the drawer is opened or closed. The event value will be
* `true` when the drawer is opened, and `false` when the
* drawer is closed. (When this event is triggered, the drawer is starting to open/close,
* but the animation may not have fully completed yet)
*/
@Output() readonly openChange: EventEmitter<boolean> = new EventEmitter<boolean>();
/**
* Event emitted after the drawer has fully opened. When this event is emitted the full
* opening animation has completed, and the drawer is visible.
*/
@Output() readonly afterOpened: EventEmitter<void> = new EventEmitter();
/**
* Event emitted after the drawer has fully closed. When this event is emitted the full
* closing animation has completed, and the drawer is not visible anymore.
*/
@Output() readonly afterClosed: EventEmitter<void> = new EventEmitter();
constructor(public _elm: ElementRef, protected _rndr: Renderer2, @Inject(DOCUMENT) doc: any,
@Optional() @Self() private _focusTrap: AbstractMdcFocusTrap) {
this.document = doc as Document; // work around ngc issue https://github.com/angular/angular/issues/20351
}
ngAfterContentInit() {
this.initDrawer();
}
ngOnDestroy() {
this.destroyDrawer();
}
private destroyDrawer() {
// when foundation is reconstructed and then .open() is called,
// if these classes are still available the foundation assumes open was already called,
// and it won't do anything:
this._rndr.removeClass(this._elm.nativeElement, 'mdc-drawer--animate');
this._rndr.removeClass(this._elm.nativeElement, 'mdc-drawer--closing');
this._rndr.removeClass(this._elm.nativeElement, 'mdc-drawer--open');
this._rndr.removeClass(this._elm.nativeElement, 'mdc-drawer--opening');
if (this.foundation) {
this.document.removeEventListener('click', this._onDocumentClick);
this.foundation.destroy();
this.foundation = null;
}
}
private initDrawer() {
this.destroyDrawer();
let newFoundation: MDCDismissibleDrawerFoundation | null = null;
const thiz = this;
if (this.type === 'dismissible')
newFoundation = new class extends MDCDismissibleDrawerFoundation{
close() {
const emit = thiz._open;
thiz._open = false;
super.close();
emit ? thiz.openChange.emit(thiz._open) : undefined;
}
open() {
const emit = !thiz._open;
thiz._open = true;
super.open();
emit ? thiz.openChange.emit(thiz._open) : undefined;
}
}(this.mdcAdapter);
else if (this.type === 'modal')
newFoundation = new class extends MDCModalDrawerFoundation{
close() {
const emit = thiz._open;
thiz._open = false;
super.close();
emit ? thiz.openChange.emit(thiz._open) : undefined;
}
open() {
const emit = !thiz._open;
thiz._open = true;
super.open();
emit ? thiz.openChange.emit(thiz._open) : undefined;
}
}(this.mdcAdapter);
// else: permanent drawer -> doesn't need a foundation, just styling
if (newFoundation) {
this.foundation = newFoundation;
newFoundation.init();
if (this._open)
newFoundation.open();
}
}
/** @internal */
@HostBinding('class.mdc-drawer--modal') get _isModal() {
return this.type === 'modal';
}
/** @internal */
@HostBinding('class.mdc-drawer--dismissible') get _isDismisible() {
return this.type === 'dismissible';
}
/**
* Set the type of drawer. Either `permanent`, `dismissible`, or `modal`.
* The default type is `permanent`.
*/
@Input() get mdcDrawer(): 'permanent' | 'dismissible' | 'modal' {
return this.type;
}
set mdcDrawer(value: 'permanent' | 'dismissible' | 'modal') {
if (value !== 'dismissible' && value !== 'modal')
value = 'permanent';
if (value !== this.type) {
this.type = value;
this.initDrawer();
}
}
static ngAcceptInputType_mdcDrawer: 'permanent' | 'dismissible' | 'modal' | '';
/**
* Input to open (assign value `true`) or close (assign value `false`)
* the drawer.
*/
@Input() get open() {
return !!this._open;
}
set open(value: boolean) {
let newValue = asBoolean(value);
if (newValue !== this._open) {
if (this.foundation) {
newValue ? this.foundation.open() : this.foundation.close();
} else {
this._open = newValue;
this.openChange.emit(newValue);
}
}
}
static ngAcceptInputType_open: boolean | '';
private fixOpenClose(open: boolean) {
// the foundation ignores calls to open/close while an opening/closing animation is running.
// so when the animation ends, we're just going to try again
// (needs to be done in the next micro cycle, because otherwise foundation will still think it's
// running the opening/closing animation):
Promise.resolve().then(() => {
if (this._open !== open) {
if (this._open)
this.foundation!.open();
else
this.foundation!.close();
}
});
}
private trapFocus() {
this.untrapFocus();
if (this._focusTrap)
this.focusTrapHandle = this._focusTrap.trapFocus();
}
private untrapFocus() {
if (this.focusTrapHandle && this.focusTrapHandle.active) {
this.focusTrapHandle.untrap();
this.focusTrapHandle = null;
}
}
/** @internal */
@HostListener('keydown', ['$event']) onKeydown(event: KeyboardEvent) {
this.foundation?.handleKeydown(event);
}
/** @internal */
@HostListener('transitionend', ['$event']) handleTransitionEnd(event: TransitionEvent) {
this.foundation?.handleTransitionEnd(event);
}
/** @internal */
onDocumentClick(event: MouseEvent) {
if (this.type === 'modal') {
// instead of listening to click event on mdcDrawerScrim (which would require wiring between
// mdcDrawerScrim and mdcDrawer), we just listen to document clicks.
let el: Element | null = event.target as Element;
while (el) {
if (el === this._elm.nativeElement)
return;
el = el.parentElement;
}
(this.foundation as MDCModalDrawerFoundation)?.handleScrimClick();
}
}
}
/**
* Use this directive for marking the sibling element after a dismissible `mdcDrawer`.
* This will apply styling so that the open/close animations work correctly.
*/
@Directive({
selector: '[mdcDrawerAppContent]'
})
export class MdcDrawerAppContent {
/** @internal */
@HostBinding('class.mdc-drawer-app-content') _cls = true;
/**
* Set this to false to disable the styling for sibbling app content of a dismissible drawer.
* This is typically only used when your `mdcDrawer` type is dynamic. In those cases you can
* disable the `mdcDrawerAppContent` when you set your drawer type to anything other than
* `dismissible`.
*/
@Input() get mdcDrawerAppContent() {
return this._cls;
}
set mdcDrawerAppContent(value: boolean) {
this._cls = asBoolean(value);
}
static ngAcceptInputType_mdcDrawerAppContent: boolean | '';
}
export const DRAWER_DIRECTIVES = [
MdcDrawerTitleDirective,
MdcDrawerSubtitleDirective,
MdcDrawerHeaderDirective,
MdcDrawerContentDirective,
MdcDrawerScrimDirective,
MdcDrawerDirective,
MdcDrawerAppContent
]; | the_stack |
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';
import { Observable, Observer, Subscription } from 'rxjs';
import { SERVER_API_URL } from 'app/app.constants';
import { createRequestOption } from 'app/shared';
import { Router } from '@angular/router';
import { WindowRef } from 'app/shared';
import { saveAs } from 'file-saver/FileSaver';
import { IGateway } from 'app/shared/model/gateway.model';
import { IFlow, Flow } from 'app/shared/model/flow.model';
import * as SockJS from 'sockjs-client';
import * as Stomp from 'webstomp-client';
import { CSRFService } from 'app/core';
type EntityResponseType = HttpResponse<IFlow>;
type EntityArrayResponseType = HttpResponse<IFlow[]>;
@Injectable({ providedIn: 'root' })
export class FlowService {
public resourceUrl = SERVER_API_URL + 'api/flows';
public connectorUrl = SERVER_API_URL + 'api/connector';
public environmentUrl = SERVER_API_URL + 'api/environment';
stompClient = null;
subscriber = null;
connection: Promise<any>;
connectedPromise: any;
listener: Observable<any>;
listenerObserver: Observer<any>;
alreadyConnectedOnce = false;
private subscription: Subscription;
private gatewayid = 1;
constructor(protected http: HttpClient, protected router: Router, protected $window: WindowRef, protected csrfService: CSRFService) {
this.connection = this.createConnection();
this.listener = this.createListener();
}
create(flow: IFlow): Observable<EntityResponseType> {
return this.http.post<IFlow>(this.resourceUrl, flow, { observe: 'response' });
}
update(flow: IFlow): Observable<EntityResponseType> {
return this.http.put<IFlow>(this.resourceUrl, flow, { observe: 'response' });
}
find(id: number): Observable<EntityResponseType> {
return this.http.get<IFlow>(`${this.resourceUrl}/${id}`, { observe: 'response' });
}
query(req?: any): Observable<EntityArrayResponseType> {
const options = createRequestOption(req);
return this.http.get<IFlow[]>(this.resourceUrl, { params: options, observe: 'response' });
}
delete(id: number): Observable<HttpResponse<any>> {
return this.http.delete<any>(`${this.resourceUrl}/${id}`, { observe: 'response' });
}
getFlowByGatewayId(gatewayid: Number, req?: any): Observable<EntityArrayResponseType> {
const options = createRequestOption(req);
return this.http.get<IFlow[]>(`${this.resourceUrl}/bygatewayid/${gatewayid}`, { params: options, observe: 'response' });
}
getConfiguration(flowid: number): Observable<HttpResponse<any>> {
return this.http.get(`${this.environmentUrl}/${this.gatewayid}/flow/${flowid}`, {
headers: new HttpHeaders({ PlaceholderReplacement: 'true', Accept: 'application/xml' }),
observe: 'response',
responseType: 'text'
});
}
setConfiguration(id: number, xmlconfiguration: string, header?: string): Observable<any> {
if (!!header) {
return this.http.post(`${this.connectorUrl}/${this.gatewayid}/setflowconfiguration/${id}`, xmlconfiguration, {
headers: new HttpHeaders({ PlaceholderReplacement: 'true', Accept: 'application/xml' }),
observe: 'response',
responseType: 'text'
});
} else {
return this.http.post(`${this.connectorUrl}/${this.gatewayid}/setflowconfiguration/${id}`, xmlconfiguration, {
observe: 'response',
responseType: 'text'
});
}
}
saveFlows(id: number, xmlconfiguration: string, header: string): Observable<EntityResponseType> {
const options = {
headers: new HttpHeaders({ Accept: 'application/xml' })
};
return this.http.post<any>(`${this.environmentUrl}/${this.gatewayid}/flow/${id}`, xmlconfiguration, options);
}
validateFlowsUri(connectorId: number, uri: string): Observable<EntityResponseType> {
const options = {
headers: new HttpHeaders({ Accept: 'application/xml' })
};
return this.http.get<any>(`${this.connectorUrl}/${connectorId}/flow/validateUri`, options);
}
start(id: number): Observable<HttpResponse<any>> {
return this.http.get(`${this.connectorUrl}/${this.gatewayid}/flow/start/${id}`, { observe: 'response', responseType: 'text' });
}
pause(id: number): Observable<HttpResponse<any>> {
return this.http.get(`${this.connectorUrl}/${this.gatewayid}/flow/pause/${id}`, { observe: 'response', responseType: 'text' });
}
resume(id: number): Observable<HttpResponse<any>> {
return this.http.get(`${this.connectorUrl}/${this.gatewayid}/flow/resume/${id}`, { observe: 'response', responseType: 'text' });
}
restart(id: number): Observable<HttpResponse<any>> {
return this.http.get(`${this.connectorUrl}/${this.gatewayid}/flow/restart/${id}`, { observe: 'response', responseType: 'text' });
}
stop(id: number): Observable<HttpResponse<any>> {
return this.http.get(`${this.connectorUrl}/${this.gatewayid}/flow/stop/${id}`, { observe: 'response', responseType: 'text' });
}
getFlowStatus(id: number): Observable<any> {
return this.http.get(`${this.connectorUrl}/${this.gatewayid}/flow/status/${id}`, { observe: 'response', responseType: 'text' });
}
getFlowAlerts(id: number): Observable<any> {
return this.http.get(`${this.connectorUrl}/${this.gatewayid}/flow/alerts/${id}`, { observe: 'response', responseType: 'text' });
}
getFlowNumberOfAlerts(id: number): Observable<any> {
return this.http.get(`${this.connectorUrl}/${this.gatewayid}/flow/numberofalerts/${id}`, {
observe: 'response',
responseType: 'text'
});
}
getFlowLastError(id: number): Observable<any> {
return this.http.get(`${this.connectorUrl}/${this.gatewayid}/flow/lasterror/${id}`, { observe: 'response', responseType: 'text' });
}
getFlowStats(id: number, endpointid: number, gatewayid: number): Observable<HttpResponse<any>> {
return this.http.get(`${this.connectorUrl}/${gatewayid}/flow/stats/${id}/${endpointid}`, { observe: 'response' });
}
getComponentOptions(gatewayid: number, componentType: String): Observable<any> {
return this.http.get(`${this.connectorUrl}/${gatewayid}/flow/schema/` + componentType, { observe: 'response' });
}
getWikiDocUrl(): Observable<HttpResponse<any>> {
return this.http.get(`${SERVER_API_URL}/api/wiki-url`, { observe: 'response', responseType: 'text' });
}
getCamelDocUrl(): Observable<HttpResponse<any>> {
return this.http.get(`${SERVER_API_URL}/api/camel-url`, { observe: 'response', responseType: 'text' });
}
getGatewayName(): Observable<HttpResponse<any>> {
return this.http.get(`${SERVER_API_URL}/api/gateway-name`, { observe: 'response', responseType: 'text' });
}
setMaintenance(time: number, flowsIds: Array<number>): Observable<HttpResponse<any>> {
return this.http.post(`${this.connectorUrl}/${this.gatewayid}/maintenance/${time}`, flowsIds, {
observe: 'response',
responseType: 'text'
});
}
testConnection(gatewayid: number, host: string, port: number, timeout: number): Observable<HttpResponse<any>> {
return this.http.get(`${this.connectorUrl}/${this.gatewayid}/testconnection/${host}/${port}/${timeout}`, {
observe: 'response',
responseType: 'text'
});
}
send(
gatewayId: number,
uri: string,
endpointId: string,
serviceId: string,
serviceKeys: string,
headerKeys: string,
numberOfTimes: string,
messageBody: string
): Observable<any> {
const options = new HttpHeaders({
uri: uri,
endpointId: endpointId,
serviceid: serviceId,
serviceKeys: serviceKeys,
headerKeys: headerKeys,
'Content-Type': 'text/plain',
Accept: 'text/plain'
});
return this.http.post(`${this.connectorUrl}/${gatewayId}/send/${numberOfTimes}`, messageBody, {
headers: options,
observe: 'response',
responseType: 'text'
});
}
sendRequest(
gatewayId: number,
uri: string,
endpointId: string,
serviceId: string,
serviceKeys: string,
headerKeys: string,
messageBody: string
): Observable<any> {
const options = new HttpHeaders({
uri: uri,
endpointId: endpointId,
serviceid: serviceId,
serviceKeys: serviceKeys,
headerKeys: headerKeys,
'Content-Type': 'text/plain',
Accept: 'text/plain'
});
return this.http.post(`${this.connectorUrl}/${gatewayId}/sendrequest`, messageBody, {
headers: options,
observe: 'response',
responseType: 'text'
});
}
exportGatewayConfiguration(gateway: IGateway) {
const url = `${this.environmentUrl}/${gateway.id}`;
const exportDate = this.getDate();
this.http
.get(url, {
headers: new HttpHeaders({
Accept: 'application/xml',
'Content-Type': 'application/octet-stream',
PlaceholderReplacement: 'false'
}),
observe: 'response',
responseType: 'blob'
})
.subscribe(
data => {
const blob = new Blob([data.body], { type: 'application/xml' });
saveAs(blob, `export_gateway_${gateway.name}_${exportDate}.xml`);
},
error => console.log(error)
);
}
exportFlowConfiguration(flow: IFlow) {
const url = `${this.environmentUrl}/1/flow/${flow.id}`;
const exportDate = this.getDate();
this.http
.get(url, {
headers: new HttpHeaders({
Accept: 'application/xml',
'Content-Type': 'application/octet-stream',
PlaceholderReplacement: 'false'
}),
observe: 'response',
responseType: 'blob'
})
.subscribe(
data => {
const blob = new Blob([data.body], { type: 'application/xml' });
saveAs(blob, `export_flow_${flow.name}_${exportDate}.xml`);
},
error => console.log(error)
);
}
connect() {
if (this.connectedPromise === null) {
this.connection = this.createConnection();
}
// building absolute path so that websocket doesn't fail when deploying with a context path
const loc = this.$window.nativeWindow.location;
let url;
if (loc.host === 'localhost:9000') {
// allow websockets on dev
url = '//localhost:8080' + loc.pathname + 'websocket/alert';
} else {
url = '//' + loc.host + loc.pathname + 'websocket/alert';
}
const socket = new SockJS(url);
this.stompClient = Stomp.over(socket);
const headers = {};
headers['X-XSRF-TOKEN'] = this.csrfService.getCSRF('XSRF-TOKEN');
this.stompClient.connect(headers, () => {
this.connectedPromise('success');
this.connectedPromise = null;
});
}
disconnect() {
if (this.stompClient !== null) {
this.stompClient.disconnect();
this.stompClient = null;
}
if (this.subscription) {
this.subscription.unsubscribe();
this.subscription = null;
}
this.alreadyConnectedOnce = false;
}
receive() {
return this.listener;
}
connectionStomp() {
return this.connection;
}
client() {
return this.stompClient;
}
subscribe(id) {
const topic = '/topic/' + id + '/alert';
this.connection.then(() => {
this.subscriber = this.stompClient.subscribe(topic, data => {
this.listenerObserver.next(JSON.parse(data.body));
});
});
}
unsubscribe() {
if (this.subscriber !== null) {
this.subscriber.unsubscribe();
}
this.listener = this.createListener();
}
private createListener(): Observable<any> {
return new Observable(observer => {
this.listenerObserver = observer;
});
}
private createConnection(): Promise<any> {
return new Promise((resolve, reject) => (this.connectedPromise = resolve));
}
/**
* Convert a returned JSON object to Flow.
*/
private convertItemFromServer(json: any): IFlow {
const entity: IFlow = Object.assign(new Flow(), json);
return entity;
}
private getDate() {
const date = new Date();
const year = date.getFullYear();
let month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
let day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year + month + day;
}
} | the_stack |
export type Operator<T, U, CtxResult = any> =
import("../Operator").Operator<T, U, CtxResult>;
namespace Operator {
export type fλ<T, U, CtxResult = any> =
import("../Operator").Operator.fλ<T, U, CtxResult>;
export namespace fλ {
export type Stateless<T, U, CtxResult = any> =
import("../Operator").Operator.fλ.Stateless<T, U, CtxResult>;
}
export type Stateless<T, U, CtxResult = any> =
import("../Operator").Operator.Stateless<T, U, CtxResult>;
}
type StatefulEvt<T> = import("./StatefulEvt").StatefulEvt<T>;
type CtxLike<Result = any> = import("./CtxLike").CtxLike<Result>;
type Evt<T> = import("./Evt").Evt<T>;
type Handler<T, U, CtxProp extends CtxLike<any> | undefined = CtxLike<any> | undefined> =
import("../Handler").Handler<T, U, CtxProp>;
export interface NonPostableEvt<T> {
/** https://docs.evt.land/api/statefulevt#converting-an-evt-into-a-statefulevt */
toStateful(initialState: T, ctx?: CtxLike): StatefulEvt<T>;
toStateful(ctx?: CtxLike): StatefulEvt<T | undefined>;
/** https://docs.evt.land/api/evt/evtattachdetach */
readonly evtAttach: Evt<Handler<T, any>>;
/** https://docs.evt.land/api/evt/evtattachdetach */
readonly evtDetach: Evt<Handler<T, any>>;
/** https://docs.evt.land/api/evt/setmaxhandlers */
setMaxHandlers(n: number): this;
/**
* https://docs.evt.land/api/evt/post
*
* Number of times .post(data) have been called.
*/
readonly postCount: number;
/** https://docs.evt.land/api/evt/enabletrace */
enableTrace(
params: {
id: string,
formatter?: (data: T) => string,
log?: ((message?: any, ...optionalParams: any[]) => void) | false
}
//NOTE: Not typeof console.log as we don't want to expose types from node
): void;
/** https://docs.evt.land/api/evt/enabletrace */
disableTrace(): this;
/** https://docs.evt.land/api/evt/getstatelessop */
getStatelessOp<U, CtxResult>(op: Operator<T, U, CtxResult>): Operator.Stateless<T, U, CtxResult>;
/**
* https://docs.evt.land/api/evt/ishandled
*
* Test if posting a given event data will have an effect.
*
* Return true if:
* -There is at least one handler matching
* this event data ( at least one handler's callback function
* will be invoked if the data is posted. )
* -Handlers could be will be detached
* if the event data is posted.
*
*/
isHandled(data: T): boolean;
/** https://docs.evt.land/api/evt/gethandler */
getHandlers(): Handler<T, any>[];
/**
* https://docs.evt.land/api/evt/detach
*
* Detach every handlers of the Evt that are bound to the provided context
* */
detach<CtxResult>(ctx: CtxLike<CtxResult>): Handler<T, any, CtxLike<CtxResult>>[];
/**
* https://docs.evt.land/api/evt/detach
*
* (unsafe) Detach every handlers from the Evt
* */
detach(): Handler<T, any>[];
/** https://docs.evt.land/api/evt/pipe */
pipe(): Evt<T>;
pipe<U, CtxResult>(
op: Operator.fλ<T, U, CtxResult>
): Evt<U>;
pipe<U extends T>(
op: (data: T) => data is U
): Evt<U>;
pipe(
op: (data: T) => boolean
): Evt<T>;
pipe(ctx: CtxLike): Evt<T>;
pipe<U, CtxResult>(
ctx: CtxLike,
op: Operator.fλ<T, U, CtxResult>
): Evt<U>;
pipe<U extends T>(
ctx: CtxLike,
op: (data: T) => data is U
): Evt<U>;
pipe(
ctx: CtxLike,
op: (data: T) => boolean
): Evt<T>;
pipe<B, C, CtxResultOp1, CtxResultOp2>(
op1: Operator.fλ<T, B, CtxResultOp1>,
op2: Operator.fλ<B, C, CtxResultOp2>
): Evt<C>;
pipe<B, C extends B, CtxResult>(
op1: Operator.fλ<T, B, CtxResult>,
op2: (data: B) => data is C
): Evt<C>;
pipe<B, CtxResult>(
op1: Operator.fλ<T, B, CtxResult>,
op2: (data: B) => boolean
): Evt<B>;
pipe<B extends T, C, CtxResult>(
op1: (data: T) => data is B,
op2: Operator.fλ<B, C, CtxResult>
): Evt<B>;
pipe<B, CtxResult>(
op1: (data: T) => boolean,
op2: Operator.fλ<T, B, CtxResult>
): Evt<B>;
pipe<B extends T, C extends B>(
op1: (data: T) => data is B,
op2: (data: B) => data is C
): Evt<C>;
pipe<B extends T>(
op1: (data: T) => data is B,
op2: (data: B) => boolean
): Evt<B>;
pipe<B extends T>(
op1: (data: T) => boolean,
op2: (data: T) => data is B
): Evt<B>;
pipe<T>(
op1: (data: T) => boolean,
op2: (data: T) => boolean
): Evt<T>;
pipe<B, C, D, CtxResultOp1, CtxResultOp2, CtxResultOp3>(
op1: Operator.fλ<T, B, CtxResultOp1>,
op2: Operator.fλ<B, C, CtxResultOp2>,
op3: Operator.fλ<C, D, CtxResultOp3>
): Evt<D>;
pipe<B, C, D, E, CtxResultOp1 = any, CtxResultOp2 = any, CtxResultOp3 = any, CtxResultOp4 = any>(
op1: Operator.fλ<T, B, CtxResultOp1>,
op2: Operator.fλ<B, C, CtxResultOp2>,
op3: Operator.fλ<C, D, CtxResultOp3>,
op4: Operator.fλ<D, E, CtxResultOp4>
): Evt<E>;
pipe<B, C, D, E, CtxResultOp1 = any, CtxResultOp2 = any, CtxResultOp3 = any, CtxResultOp4 = any>(
op1: Operator.fλ<T, B, CtxResultOp1>,
op2: Operator.fλ<B, C, CtxResultOp2>,
op3: Operator.fλ<C, D, CtxResultOp3>,
op4: Operator.fλ<D, E, CtxResultOp4>
): Evt<E>;
pipe<B, C, D, E, F, CtxResultOp1 = any, CtxResultOp2 = any, CtxResultOp3 = any, CtxResultOp4 = any, CtxResultOp5 = any>(
op1: Operator.fλ<T, B, CtxResultOp1>,
op2: Operator.fλ<B, C, CtxResultOp2>,
op3: Operator.fλ<C, D, CtxResultOp3>,
op4: Operator.fλ<D, E, CtxResultOp4>,
op5: Operator.fλ<E, F, CtxResultOp5>
): Evt<F>;
pipe<B, C, CtxResultOp1 = any, CtxResultOp2 = any>(
op1: Operator<T, B, CtxResultOp2>,
op2: Operator<B, C, CtxResultOp2>
): Evt<C>;
pipe<B, C, D, CtxResultOp1 = any, CtxResultOp2 = any, CtxResultOp3 = any>(
op1: Operator<T, B, CtxResultOp1>,
op2: Operator<B, C, CtxResultOp2>,
op3: Operator<C, D, CtxResultOp3>
): Evt<D>;
pipe<B, C, D, E, CtxResultOp1 = any, CtxResultOp2 = any, CtxResultOp3 = any, CtxResultOp4 = any>(
op1: Operator<T, B, CtxResultOp1>,
op2: Operator<B, C, CtxResultOp2>,
op3: Operator<C, D, CtxResultOp3>,
op4: Operator<D, E, CtxResultOp4>
): Evt<E>;
pipe<B, C, D, E, F, CtxResultOp1 = any, CtxResultOp2 = any, CtxResultOp3 = any, CtxResultOp4 = any, CtxResultOp5 = any>(
op1: Operator<T, B, CtxResultOp1>,
op2: Operator<B, C, CtxResultOp2>,
op3: Operator<C, D, CtxResultOp3>,
op4: Operator<D, E, CtxResultOp4>,
op5: Operator<E, F, CtxResultOp5>
): Evt<F>;
pipe(
...ops: [
Operator<T, any, any>,
...Operator<any, any, any>[]
]
): Evt<any>;
pipe<T>(
...ops: [
Operator<T, any, any>,
...Operator<any, any, any>[]
]
): Evt<any>;
/**
* https://docs.evt.land/api/evt/waitfor
*
* op - fλ
*
* ctx
*
* timeout?
*/
waitFor<U, CtxResult>(
op: Operator.fλ.Stateless<T, U, CtxResult>,
ctx: CtxLike,
timeout?: number
): Promise<U>;
/**
* https://docs.evt.land/api/evt/waitfor
*
* op - Type guard
*
* ctx
*
* timeout?
*/
waitFor<Q extends T>(
op: (data: T) => data is Q,
ctx: CtxLike,
timeout?: number
): Promise<Q>;
/**
* https://docs.evt.land/api/evt/waitfor
*
* op - Filter
*
* ctx
*
* timeout?
*/
waitFor(
op: (data: T) => boolean,
ctx: CtxLike,
timeout?: number
): Promise<T>;
/**
* https://docs.evt.land/api/evt/waitfor
*
* op - fλ
*
* timeout?
*/
waitFor<U, CtxResult>(
op: Operator.fλ.Stateless<T, U, CtxResult>,
timeout?: number
): Promise<U>;
/**
* https://docs.evt.land/api/evt/waitfor
*
* op - Type guard
*
* timeout?
*/
waitFor<Q extends T>(
op: (data: T) => data is Q,
timeout?: number
): Promise<Q>;
/**
* https://docs.evt.land/api/evt/waitfor
*
* op - Filter
*
* timeout?
*/
waitFor(
op: (data: T) => boolean,
timeout?: number
): Promise<T>;
/**
* https://docs.evt.land/api/evt/waitfor
*
* ctx
*
* timeout?
*/
waitFor(
ctx: CtxLike,
timeout?: number
): Promise<T>;
/**
* https://docs.evt.land/api/evt/waitfor
*
* timeout?
*/
waitFor(
timeout?: number
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* ctx
*
* timeout
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attach<U, CtxResult = any>(
op: Operator.fλ<T, U, CtxResult>,
ctx: CtxLike,
timeout: number,
callback: (transformedData: U) => void
): Promise<U>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* ctx
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attach<U, CtxResult = any>(
op: Operator.fλ<T, U, CtxResult>,
ctx: CtxLike<CtxResult>,
callback: (transformedData: U) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* timeout
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attach<U, CtxResult = any>(
op: Operator.fλ<T, U, CtxResult>,
timeout: number,
callback: (transformedData: U) => void
): Promise<U>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attach<U, R>(
op: Operator.fλ<T, U, R>,
callback: (transformedData: U) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* ctx
*
* timeout
*
* callback
*
* NOTE: If you whish to use a fλ operator ( an operator that do not return a boolean )
* the '$' prefix should be used ( use the $attach() method )
*
*/
attach<Q extends T>(
op: (data: T) => data is Q,
ctx: CtxLike,
timeout: number,
callback: (data: Q) => void
): Promise<Q>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* ctx
*
* timeout
*
* callback
*
* NOTE: If you whish to use a fλ operator ( an operator that do not return a boolean )
* the '$' prefix should be used ( use the $attach() method )
*/
attach(
op: (data: T) => boolean,
ctx: CtxLike,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* ctx
*
* callback
*
* NOTE: If you whish to use a fλ operator ( an operator that do not return a boolean )
* the '$' prefix should be used ( use the $attach() method )
*/
attach<Q extends T>(
op: (data: T) => data is Q,
ctx: CtxLike,
callback: (data: Q) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* ctx
*
* callback
*
* NOTE: If you whish to use a fλ operator ( an operator that do not return a boolean )
* the '$' prefix should be used ( use the $attach() method )
*/
attach(
op: (data: T) => boolean,
ctx: CtxLike,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* timeout
*
* callback
*
* NOTE: If you whish to use a fλ operator ( an operator that do not return a boolean )
* the '$' prefix should be used ( use the $attach() method )
*/
attach<Q extends T>(
op: (data: T) => data is Q,
timeout: number,
callback: (data: Q) => void
): Promise<Q>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* timeout
*
* callback
*
* NOTE: If you whish to use a fλ operator ( an operator that do not return a boolean )
* the '$' prefix should be used ( use the $attach() method )
*/
attach(
op: (data: T) => boolean,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* ctx
*
* timeout
*
* callback
*/
attach(
ctx: CtxLike,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* callback
*
* NOTE: If you whish to use a fλ operator ( an operator that do not return a boolean )
* the '$' prefix should be used ( use the $attach() method )
*/
attach<Q extends T>(
op: (data: T) => data is Q,
callback: (data: Q) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* callback
*
* NOTE: If you whish to use a fλ operator ( an operator that do not return a boolean )
* the '$' prefix should be used ( use the $attach() method )
*/
attach(
op: (data: T) => boolean,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* ctx
*
* callback
*/
attach(
ctx: CtxLike,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* timeout
*
* callback
*/
attach(
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* callback
*/
attach(
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* ctx
*
* timeout
*
* callback
*
* NOTE: $attachOnce() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attachOnce() without the '$' prefix.
*/
$attachOnce<U, CtxResult = any>(
op: Operator.fλ.Stateless<T, U, CtxResult>,
ctx: CtxLike,
timeout: number,
callback: (transformedData: U) => void
): Promise<U>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* ctx
*
* callback
*
* NOTE: $attachOnce() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attachOnce() without the '$' prefix.
*/
$attachOnce<U, CtxResult = any>(
op: Operator.fλ.Stateless<T, U, CtxResult>,
ctx: CtxLike,
callback: (transformedData: U) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* timeout
*
* callback
*
* NOTE: $attachOnce() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attachOnce() without the '$' prefix.
*/
$attachOnce<U, CtxResult = any>(
op: Operator.fλ.Stateless<T, U, CtxResult>,
timeout: number,
callback: (transformedData: U) => void
): Promise<U>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* callback
*
* NOTE: $attachOnce() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attachOnce() without the '$' prefix.
*/
$attachOnce<U, CtxResult = any>(
op: Operator.fλ.Stateless<T, U, CtxResult>,
callback: (transformedData: U) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* ctx
*
* timeout
*
* callback
*
* NOTE: If you whish to use a fλ operator ( an operator that do not return a boolean )
* the '$' prefix should be used ( use the $attachOnce() method )
*/
attachOnce<Q extends T>(
op: (data: T) => data is Q,
ctx: CtxLike,
timeout: number,
callback: (data: Q) => void
): Promise<Q>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* ctx
*
* timeout
*
* callback
*
* NOTE: If you whish to use a fλ operator ( an operator that do not return a boolean )
* the '$' prefix should be used ( use the $attachOnce() method )
*/
attachOnce(
op: (data: T) => boolean,
ctx: CtxLike,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* ctx
*
* callback
*
* NOTE: If you whish to use a fλ operator ( an operator that do not return a boolean )
* the '$' prefix should be used ( use the $attachOnce() method )
*/
attachOnce<Q extends T>(
op: (data: T) => data is Q,
ctx: CtxLike,
callback: (data: Q) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* ctx
*
* callback
*
* NOTE: If you whish to use a fλ operator ( an operator that do not return a boolean )
* the '$' prefix should be used ( use the $attachOnce() method )
*/
attachOnce(
op: (data: T) => boolean,
ctx: CtxLike,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* timeout
*
* callback
*
* NOTE: If you whish to use a fλ operator ( an operator that do not return a boolean )
* the '$' prefix should be used ( use the $attachOnce() method )
*/
attachOnce<Q extends T>(
op: (data: T) => data is Q,
timeout: number,
callback: (data: Q) => void
): Promise<Q>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* timeout
*
* callback
*
* NOTE: If you whish to use a fλ operator ( an operator that do not return a boolean )
* the '$' prefix should be used ( use the $attachOnce() method )
*/
attachOnce(
op: (data: T) => boolean,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* ctx
*
* timeout
*
* callback
*/
attachOnce(
ctx: CtxLike,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* callback
*
* NOTE: If you whish to use a fλ operator ( an operator that do not return a boolean )
* the '$' prefix should be used ( use the $attachOnce() method )
*/
attachOnce<Q extends T>(
op: (data: T) => data is Q,
callback: (data: Q) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* callback
*
* NOTE: If you whish to use a fλ operator ( an operator that do not return a boolean )
* the '$' prefix should be used ( use the $attachOnce() method )
*/
attachOnce(
op: (data: T) => boolean,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* ctx
*
* callback
*/
attachOnce(
ctx: CtxLike,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* timeout
*
* callback
*/
attachOnce(
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* callback
*/
attachOnce(
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* ctx
*
* timeout
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attachExtract<U, CtxResult>(
op: Operator.fλ<T, U, CtxResult>,
ctx: CtxLike,
timeout: number,
callback: (transformedData: U) => void
): Promise<U>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* ctx
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attachExtract<U, CtxResult>(
op: Operator.fλ<T, U, CtxResult>,
ctx: CtxLike,
callback: (transformedData: U) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* timeout
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attachExtract<U, CtxResult = any>(
op: Operator.fλ<T, U, CtxResult>,
timeout: number,
callback: (transformedData: U) => void
): Promise<U>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attachExtract<U, CtxResult = any>(
op: Operator.fλ<T, U, CtxResult>,
callback: (transformedData: U) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* ctx
*
* timeout
*
* callback
*/
attachExtract<Q extends T>(
op: (data: T) => data is Q,
ctx: CtxLike,
timeout: number,
callback: (data: Q) => void
): Promise<Q>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* ctx
*
* timeout
*
* callback
*/
attachExtract(
op: (data: T) => boolean,
ctx: CtxLike,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* ctx
*
* callback
*/
attachExtract<Q extends T>(
op: (data: T) => data is Q,
ctx: CtxLike,
callback: (data: Q) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* ctx
*
* callback
*/
attachExtract(
op: (data: T) => boolean,
ctx: CtxLike,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* timeout
*
* callback
*/
attachExtract<Q extends T>(
op: (data: T) => data is Q,
timeout: number,
callback: (data: Q) => void
): Promise<Q>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* timeout
*
* callback
*/
attachExtract(
op: (data: T) => boolean,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* ctx
*
* timeout
*/
attachExtract(
ctx: CtxLike,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* callback
*/
attachExtract<Q extends T>(
op: (data: T) => data is Q,
callback: (data: Q) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* callback
*/
attachExtract(
op: (data: T) => boolean,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* ctx
*
* callback
*/
attachExtract(
ctx: CtxLike,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* timeout
*
* callback
*/
attachExtract(
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* callback
*/
attachExtract(
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* ctx
*
* timeout
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attachPrepend<U, CtxResult = any>(
op: Operator.fλ<T, U, CtxResult>,
ctx: CtxLike,
timeout: number,
callback: (transformedData: U) => void
): Promise<U>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* ctx
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attachPrepend<U, CtxResult = any>(
op: Operator.fλ<T, U, CtxResult>,
ctx: CtxLike,
callback: (transformedData: U) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* timeout
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attachPrepend<U, CtxResult = any>(
op: Operator.fλ<T, U, CtxResult>,
timeout: number,
callback: (transformedData: U) => void
): Promise<U>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attachPrepend<U, CtxResult = any>(
op: Operator.fλ<T, U, CtxResult>,
callback: (transformedData: U) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* ctx
*
* timeout
*
* callback
*/
attachPrepend<Q extends T>(
op: (data: T) => data is Q,
ctx: CtxLike,
timeout: number,
callback: (data: Q) => void
): Promise<Q>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* ctx
*
* timeout
*
* callback
*/
attachPrepend(
op: (data: T) => boolean,
ctx: CtxLike,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* ctx
*
* callback
*/
attachPrepend<Q extends T>(
op: (data: T) => data is Q,
ctx: CtxLike,
callback: (data: Q) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* ctx
*
* callback
*/
attachPrepend(
op: (data: T) => boolean,
ctx: CtxLike,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* timeout
*
* callback
*/
attachPrepend<Q extends T>(
op: (data: T) => data is Q,
timeout: number,
callback: (data: Q) => void
): Promise<Q>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* timeout
*
* callback
*/
attachPrepend(
op: (data: T) => boolean,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* ctx
*
* timeout
*
* callback
*/
attachPrepend(
ctx: CtxLike,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* callback
*/
attachPrepend<Q extends T>(
op: (data: T) => data is Q,
callback: (data: Q) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* callback
*/
attachPrepend(
op: (data: T) => boolean,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* ctx
*
* callback
*/
attachPrepend(
ctx: CtxLike,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* timeout
*
* callback
*/
attachPrepend(
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* callback
*/
attachPrepend(
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* ctx
*
* timeout
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attachOncePrepend<U, CtxResult = any>(
op: Operator.fλ.Stateless<T, U, CtxResult>,
ctx: CtxLike,
timeout: number,
callback: (transformedData: U) => void
): Promise<U>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* ctx
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attachOncePrepend<U, CtxResult = any>(
op: Operator.fλ.Stateless<T, U, CtxResult>,
ctx: CtxLike,
callback: (transformedData: U) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* timeout
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attachOncePrepend<U, CtxResult = any>(
op: Operator.fλ.Stateless<T, U, CtxResult>,
timeout: number,
callback: (transformedData: U) => void
): Promise<U>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attachOncePrepend<U, CtxResult = any>(
op: Operator.fλ.Stateless<T, U, CtxResult>,
callback: (transformedData: U) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* ctx
*
* timeout
*
* callback
*/
attachOncePrepend<Q extends T>(
op: (data: T) => data is Q,
ctx: CtxLike,
timeout: number,
callback: (data: Q) => void
): Promise<Q>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* ctx
*
* timeout
*
* callback
*/
attachOncePrepend(
op: (data: T) => boolean,
ctx: CtxLike,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* ctx
*
* callback
*/
attachOncePrepend<Q extends T>(
op: (data: T) => data is Q,
ctx: CtxLike,
callback: (data: Q) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* ctx
*
* callback
*/
attachOncePrepend(
op: (data: T) => boolean,
ctx: CtxLike,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* timeout
*
* callback
*/
attachOncePrepend<Q extends T>(
op: (data: T) => data is Q,
timeout: number,
callback: (data: Q) => void
): Promise<Q>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* timeout
*
* callback
*/
attachOncePrepend(
op: (data: T) => boolean,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* ctx
*
* timeout
*
* callback
*/
attachOncePrepend(
ctx: CtxLike,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* callback
*/
attachOncePrepend<Q extends T>(
op: (data: T) => data is Q,
callback: (data: Q) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* callback
*/
attachOncePrepend(
op: (data: T) => boolean,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* ctx
*
* callback
*/
attachOncePrepend(
ctx: CtxLike,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* timeout
*
* callback
*/
attachOncePrepend(
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* callback
*/
attachOncePrepend(
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* ctx
*
* timeout
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attachOnceExtract<U, CtxResult = any>(
op: Operator.fλ.Stateless<T, U, CtxResult>,
ctx: CtxLike,
timeout: number,
callback: (transformedData: U) => void
): Promise<U>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* ctx
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attachOnceExtract<U, CtxResult = any>(
op: Operator.fλ.Stateless<T, U, CtxResult>,
ctx: CtxLike,
callback: (transformedData: U) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* timeout
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attachOnceExtract<U, CtxResult = any>(
op: Operator.fλ.Stateless<T, U, CtxResult>,
timeout: number,
callback: (transformedData: U) => void
): Promise<U>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - fλ
*
* callback
*
* NOTE: $attach() with '$' is to use only with fλ operators,
* if your operator return a boolean use the attach() without the '$' prefix.
*/
$attachOnceExtract<U, CtxResult = any>(
op: Operator.fλ.Stateless<T, U, CtxResult>,
callback: (transformedData: U) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* ctx
*
* timeout
*
* callback
*/
attachOnceExtract<Q extends T>(
op: (data: T) => data is Q,
ctx: CtxLike,
timeout: number,
callback: (data: Q) => void
): Promise<Q>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* ctx
*
* timeout
*
* callback
*/
attachOnceExtract(
op: (data: T) => boolean,
ctx: CtxLike,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* ctx
*
* callback
*/
attachOnceExtract<Q extends T>(
op: (data: T) => data is Q,
ctx: CtxLike,
callback: (data: Q) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* ctx
*
* callback
*/
attachOnceExtract(
op: (data: T) => boolean,
ctx: CtxLike,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* timeout
*
* callback
*/
attachOnceExtract<Q extends T>(
op: (data: T) => data is Q,
timeout: number,
callback: (data: Q) => void
): Promise<Q>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* timeout
*
* callback
*/
attachOnceExtract(
op: (data: T) => boolean,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* ctx
*
* timeout
*/
attachOnceExtract(
ctx: CtxLike,
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Type guard
*
* callback
*/
attachOnceExtract<Q extends T>(
op: (data: T) => data is Q,
callback: (data: Q) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* op - Filter
*
* callback
*/
attachOnceExtract(
op: (data: T) => boolean,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* ctx
*
* callback
*/
attachOnceExtract(
ctx: CtxLike,
callback: (data: T) => void
): this;
/**
* https://docs.evt.land/api/evt/attach
*
* timeout
*
* callback
*/
attachOnceExtract(
timeout: number,
callback: (data: T) => void
): Promise<T>;
/**
* https://docs.evt.land/api/evt/attach
*
* callback
*/
attachOnceExtract(
callback: (data: T) => void
): this;
} | the_stack |
import { IPdfPrimitive } from './../../interfaces/i-pdf-primitives';
import { IPdfWriter } from './../../interfaces/i-pdf-writer';
import { ObjectStatus } from './../input-output/enum';
import { PdfCrossTable } from './../input-output/pdf-cross-table';
import { PdfNumber } from './pdf-number';
import { RectangleF } from './../drawing/pdf-drawing';
import { Operators } from './../input-output/pdf-operators';
import { PdfName } from './pdf-name';
/**
* `PdfArray` class is used to perform array related primitive operations.
* @private
*/
export class PdfArray implements IPdfPrimitive {
//Fields
/**
* `startMark` - '['
* @private
*/
public startMark : string = '[';
/**
* `endMark` - ']'.
* @private
*/
public endMark : string = ']';
/**
* The `elements` of the PDF array.
* @private
*/
private internalElements : IPdfPrimitive[];
/**
* Indicates if the array `was changed`.
* @private
*/
private bChanged : boolean;
/**
* Shows the type of object `status` whether it is object registered or other status;
* @private
*/
private status9 : ObjectStatus;
/**
* Indicates if the object is currently in `saving state` or not.
* @private
*/
private isSaving9 : boolean;
/**
* Holds the `index` number of the object.
* @private
*/
private index9 : number;
/**
* Internal variable to store the `position`.
* @default -1
* @private
*/
private position9 : number = -1;
/**
* Internal variable to hold `PdfCrossTable` reference.
* @private
*/
private pdfCrossTable : PdfCrossTable;
/**
* Internal variable to hold `cloned object`.
* @default null
* @private
*/
private clonedObject9 : PdfArray = null;
/**
* Represents the Font dictionary.
* @hidden
* @private
*/
public isFont : boolean = false;
//property
/**
* Gets the `IPdfSavable` at the specified index.
* @private
*/
public items(index : number) : IPdfPrimitive {
// if (index < 0 || index >= this.Count) {
// throw new Error('ArgumentOutOfRangeException : index, The index can"t be less then zero or greater then Count.');
// }
return this.internalElements[index] as IPdfPrimitive;
}
/**
* Gets the `count`.
* @private
*/
public get count() : number {
return this.internalElements.length;
}
/**
* Gets or sets the `Status` of the specified object.
* @private
*/
public get status() : ObjectStatus {
return this.status9;
}
public set status(value : ObjectStatus) {
this.status9 = value;
}
/**
* Gets or sets a value indicating whether this document `is saving` or not.
* @private
*/
public get isSaving() : boolean {
return this.isSaving9;
}
public set isSaving(value : boolean) {
this.isSaving9 = value;
}
/**
* Returns `cloned object`.
* @private
*/
public get clonedObject() : IPdfPrimitive {
return this.clonedObject9;
}
/**
* Gets or sets the `position` of the object.
* @private
*/
public get position() : number {
return this.position9;
}
public set position(value : number) {
this.position9 = value;
}
/**
* Gets or sets the `index` value of the specified object.
* @private
*/
public get objectCollectionIndex() : number {
return this.index9;
}
public set objectCollectionIndex(value : number) {
this.index9 = value;
}
/**
* Returns `PdfCrossTable` associated with the object.
* @private
*/
public get CrossTable() : PdfCrossTable {
return this.pdfCrossTable;
}
/**
* Gets the `elements` of the Pdf Array.
* @private
*/
public get elements() : IPdfPrimitive[] {
return this.internalElements;
}
//constructor
/**
* Initializes a new instance of the `PdfArray` class.
* @private
*/
constructor()
/**
* Initializes a new instance of the `PdfArray` class.
* @private
*/
constructor(array : PdfArray|number[])
constructor(array? : PdfArray|number[]) {
if (typeof array === 'undefined') {
this.internalElements = [];
} else {
if (typeof array !== 'undefined' && !(array instanceof PdfArray)) {
let tempNumberArray : number[] = array;
for (let index : number = 0; index < tempNumberArray.length; index++) {
let pdfNumber : PdfNumber = new PdfNumber(tempNumberArray[index]);
this.add(pdfNumber);
}
// } else if (typeof array !== 'undefined' && (array instanceof PdfArray)) {
} else {
let tempArray : PdfArray = array as PdfArray;
// if (tempArray.Elements.length > 0) {
this.internalElements = [];
for (let index : number = 0; index < tempArray.elements.length; index++) {
this.internalElements.push(tempArray.elements[index]);
}
// }
}
}
}
/**
* `Adds` the specified element to the PDF array.
* @private
*/
public add(element : IPdfPrimitive) : void {
// if (element === null) {
// throw new Error('ArgumentNullException : obj');
// }
if (typeof this.internalElements === 'undefined') {
this.internalElements = [];
}
this.internalElements.push(element);
this.markedChange();
}
/**
* `Marks` the object changed.
* @private
*/
private markedChange() : void {
this.bChanged = true;
}
/**
* `Determines` whether the specified element is within the array.
* @private
*/
public contains(element : IPdfPrimitive) : boolean {
let returnValue : boolean = false;
for (let index : number = 0; index < this.internalElements.length; index++) {
let tempElement : PdfName = this.internalElements[index] as PdfName;
let inputElement : PdfName = element as PdfName;
if (tempElement != null && typeof tempElement !== 'undefined' && inputElement != null && typeof inputElement !== 'undefined') {
if (tempElement.value === inputElement.value) {
return true;
}
}
// if (this.internalElements[index] === element) {
// returnValue = true;
// }
}
return returnValue;
}
/**
* Returns the `primitive object` of input index.
* @private
*/
public getItems(index : number) : IPdfPrimitive {
// if (index < 0 || index >= this.Count) {
// throw new Error('ArgumentOutOfRangeException : index , The index can"t be less then zero or greater then Count.');
// }
return this.internalElements[index] as IPdfPrimitive;
}
/**
* `Saves` the object using the specified writer.
* @private
*/
public save(writer : IPdfWriter) : void {
// if (writer === null) {
// throw new Error('ArgumentNullException : writer');
// }
writer.write(this.startMark);
for (let i : number = 0, len : number = this.count; i < len; i++) {
this.getItems(i).save(writer);
if (i + 1 !== len) {
writer.write(Operators.whiteSpace);
}
}
writer.write(this.endMark);
}
/**
* Creates a `copy of PdfArray`.
* @private
*/
public clone(crossTable : PdfCrossTable) : IPdfPrimitive {
// if (this.clonedObject9 !== null && this.clonedObject9.CrossTable === crossTable) {
// return this.clonedObject9;
// } else {
this.clonedObject9 = null;
// Else clone the object.
let newArray : PdfArray = new PdfArray();
for (let index : number = 0; index < this.internalElements.length; index++) {
let obj : IPdfPrimitive = this.internalElements[index];
newArray.add(obj.clone(crossTable));
}
newArray.pdfCrossTable = crossTable;
this.clonedObject9 = newArray;
return newArray;
}
/**
* Creates filled PDF array `from the rectangle`.
* @private
*/
public static fromRectangle(bounds : RectangleF) : PdfArray {
let values : number[] = [bounds.x, bounds.y, bounds.width, bounds.height];
let array : PdfArray = new PdfArray(values);
return array;
}
// /**
// * Creates the rectangle from filled PDF array.
// * @private
// */
// public ToRectangle() : RectangleF {
// if (this.Count < 4) {
// throw Error('InvalidOperationException-Can not convert to rectangle.');
// }
// let x1 : number;
// let x2 : number;
// let y1 : number;
// let y2 : number;
// let num : PdfNumber = this.getItems(0) as PdfNumber;
// x1 = num.IntValue;
// num = this.getItems(1) as PdfNumber;
// y1 = num.IntValue;
// num = this.getItems(2) as PdfNumber;
// x2 = num.IntValue;
// num = this.getItems(3) as PdfNumber;
// y2 = num.IntValue;
// let x : number = Math.min(x1, x2);
// let y : number = Math.min(y1, y2);
// let width : number = Math.abs(x1 - x2);
// let height : number = Math.abs(y1 - y2);
// let rect : RectangleF = new RectangleF(new PointF(x, y), new SizeF(width, height));
// return rect;
// }
/**
* `Inserts` the element into the array.
* @private
*/
public insert(index : number, element : IPdfPrimitive) : void {
if (index < this.internalElements.length && index > 0) {
let tempElements : IPdfPrimitive[] = [];
for (let i : number = 0; i < index ; i++) {
tempElements.push(this.internalElements[i]);
}
tempElements.push(element);
for (let i : number = index; i < this.internalElements.length ; i++) {
tempElements.push(this.internalElements[i]);
}
this.internalElements = tempElements;
} else {
this.internalElements.push(element);
}
this.markChanged();
}
/**
* `Checks whether array contains the element`.
* @private
*/
public indexOf(element : IPdfPrimitive) : number {
return this.internalElements.indexOf(element);
}
/**
* `Removes` element from the array.
* @private
*/
public remove(element : IPdfPrimitive) : void {
// if (element === null) {
// throw new Error('ArgumentNullException : element');
// }
let index : number = this.internalElements.indexOf(element);
// if (index >= 0 && index < this.internalElements.length) {
this.internalElements[index] = null;
// }
this.markChanged();
}
/**
* `Remove` the element from the array by its index.
* @private
*/
public removeAt(index : number) : void {
// this.internalElements.RemoveAt(index);
if (this.internalElements.length > index) {
let tempArray : IPdfPrimitive[] = [];
for (let i : number = 0; i < index; i++) {
tempArray.push(this.internalElements[i]);
}
for (let i : number = index + 1; i < this.internalElements.length; i++) {
tempArray.push(this.internalElements[i]);
}
this.internalElements = tempArray;
}
this.markChanged();
}
/**
* `Clear` the array.
* @private
*/
public clear() : void {
this.internalElements = [];
this.markChanged();
}
/**
* `Marks` the object changed.
* @private
*/
public markChanged() : void {
this.bChanged = true;
}
} | the_stack |
import { toQueryString } from "../../utils";
import { SdkClient } from "../common/sdk-client";
import { JobManagerModels } from "./jobmanager-models";
/**
* Offers execution mechanisms for running models stored in Model Management module.
* A schedule is created based on a model identifier and a cron expression so the model will run one or multiple times.
* Each time a model runs a new job is generated.
* When the schedule is created it will start according to the cron expression.
* If a user wants to stop the executions it can update the status of the schedule and the executions will stop.
* Also the user has the possibility to update again the status and trigger again the schedule.
* If a user does not want to run a model multiple times or based on a schedule expression
* it can start immediately a new job.
*
* @export
* @class JobManagerClient
* @extends {SdkClient}
*/
export class JobManagerClient extends SdkClient {
private _baseUrl: string = "/api/jobmanager/v3";
/**
* * Jobs
*
* Retrieves all the job executions within a tenant, sorted by creationDate descendant order,
* up to 10.000 items, paged, maximum 100 items per request if no paging parameters are specified.
* The service purges all jobs older than 90 days that have one of the final statuses
* (e.g. STOPPED, FAILED, SUCCEEDED).
*
* @param {{
* pageNumber?: number;
* pageSize?: number;
* filter?: string;
* }} [params]
* @returns {Promise<JobManagerModels.JobList>}
*
* @example Filter example:
* {"message": {"contains": "Error"},"status": { "or": {{"eq" : "STOPPED"},{"eq" : "FAILED"}}},"creationDate":
* {{"after": "2018-06-23T20:09:00"}}}
* @memberOf JobManagerClient
*/
public async GetJobs(params?: {
pageNumber?: number;
pageSize?: number;
filter?: string;
}): Promise<JobManagerModels.JobList> {
const parameters = params || {};
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/jobs?${toQueryString(parameters)}`,
});
return result as JobManagerModels.JobList;
}
/**
* * Jobs
*
* Creates a new job execution based on the model identifier.
* This endpoint offers the possibility of running a model or an algorithms
* just one time without the need of providing a schedule string
* The inputFolderId and outputFolderId are identifiers of data sources provided by
* Data Exchange module.
*
* @param {JobManagerModels.JobParameters} parameter
* @returns {Promise<JobManagerModels.Job>}
*
* @memberOf JobManagerClient
*/
public async PostJob(parameter: JobManagerModels.JobParameters): Promise<JobManagerModels.Job> {
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
body: parameter,
baseUrl: `${this._baseUrl}/jobs`,
});
return result as JobManagerModels.Job;
}
/**
*
* * Jobs
*
* Retrieves the details regarding a job execution
*
* @param {string} id
* @returns {Promise<JobManagerModels.Job>}
*
* @memberOf JobManagerClient
*/
public async GetJob(id: string): Promise<JobManagerModels.Job> {
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/jobs/${id}`,
});
return result as JobManagerModels.Job;
}
/**
*
* * Jobs
*
* Stops a job execution. The call sets the job's status to STOPPING,
* while letting the service to internally handle the additional
* steps required to get the job into a STOPPED status.
* Caller is responsible for polling the status until the job has reached
* a final state. In the event that the stop action fails for various
* reasons, the job execution can end up with a FAILED status.
* Existing results that were resulted from execution will be kept and
* provided to Data Exchange following the parameters used to start the
* job execution. If no output parameters were defined, any definitive
* (or partial) results will be lost and cleaned up during the stopping process.
*
* @param {string} id
* @returns {Promise<JobManagerModels.Job>}
*
* @memberOf JobManagerClient
*/
public async StopJob(id: string): Promise<JobManagerModels.Job> {
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/jobs/${id}/stop`,
});
return result as JobManagerModels.Job;
}
/**
* * Schedules
*
* Retrieves a list with all schedules stored within the same tenant
*
* @param {{
* pageNumber?: number;
* pageSize?: number;
* filter?: string;
* }} [params]
* @returns {Promise<JobManagerModels.ScheduleList>}
* @example Schedule Filter
*
* Complex and flexible filter that can filter by creationDate, name, status, modelId and scheduleString.
* All the top fields used in the filter are ANDed, but the searched values can use AND and OR operands, including comparison operators where the values allow. All fields are optional.
* The expected filter format is:
* ?filter={
* "status": {
* "eq": "RUNNING"
* },"message": {
* "eq": "Insufficient disk space"
* },"creationDate": {
* "gt": "2018-06-23T20:09:00"
* },
* "name": {
* "eq": "Every 2 Months"
* }
* }
*
* @memberOf JobManagerClient
*/
public async GetSchedules(params?: {
pageNumber?: number;
pageSize?: number;
filter?: string;
}): Promise<JobManagerModels.ScheduleList> {
const parameters = params || {};
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/schedules?${toQueryString(parameters)}`,
body: {},
additionalHeaders: { "Content-Type": "application/json" }, // ! fix: April 2021 manual fix for the schedules endpoint
});
return result as JobManagerModels.ScheduleList;
}
/**
* * Schedules
*
* Schedules a job for execution specified by its model id and a schedule string.
* The model ID is retrieved from Model Management module after uploading a model.
* The schedule string follows the cron format. Example 0 15 10 * * ? - will trigger the model at 10:15 am every day
*
* @param {JobManagerModels.ScheduleParameters} parameters
* @returns {Promise<JobManagerModels.ScheduleDetails>}
*
* @memberOf JobManagerClient
*/
public async PostSchedule(
parameters: JobManagerModels.ScheduleParameters
): Promise<JobManagerModels.ScheduleDetails> {
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
body: parameters,
baseUrl: `${this._baseUrl}/schedules`,
});
return result as JobManagerModels.ScheduleDetails;
}
/**
* * Schedules
*
* Retrieves information about a schedule
*
* @param {string} id
* @returns {Promise<JobManagerModels.ScheduleDetails>}
*
* @memberOf JobManagerClient
*/
public async GetSchedule(id: string): Promise<JobManagerModels.ScheduleDetails> {
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/schedules/${id}`,
});
return result as JobManagerModels.ScheduleDetails;
}
/**
* * Schedules
*
* Removes a schedule
*
* This endpoint offers the possibility of removing a schedule from the storage
*
* @param {string} id
*
* @memberOf JobManagerClient
*/
public async DeleteSchedule(id: string) {
await this.HttpAction({
verb: "DELETE",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/schedules/${id}`,
noResponse: true,
});
}
/**
*
* * Jobs
*
* Updates the status of the schedule to started.
* If a schedule has been stopped it can be started again using this endpoint.
* If a schedule is running, based on the schedule string it creates jobs
*
* @param {string} id
* @returns {Promise<JobManagerModels.ScheduleDetails>}
*
* @memberOf JobManagerClient
*/
public async StartSchedule(id: string): Promise<JobManagerModels.ScheduleDetails> {
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/schedules/${id}/start`,
});
return result as JobManagerModels.ScheduleDetails;
}
/**
* * Schedules
*
* Updates the status of the schedule to stopped.
* If a user wants to stop a schedule this endpoint offers the possibility to update the status
* of the schedule to stop. When a scheduler is stopped it cannot create new jobs executions
*
* @param {string} id
* @returns {Promise<JobManagerModels.ScheduleDetails>}
*
* @memberOf JobManagerClient
*/
public async StopSchedule(id: string): Promise<JobManagerModels.ScheduleDetails> {
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/schedules/${id}/stop`,
});
return result as JobManagerModels.ScheduleDetails;
}
} | the_stack |
import '@polymer/polymer/polymer-legacy';
import '@polymer/iron-collapse/iron-collapse';
import '@polymer/iron-icon/iron-icon';
import '@polymer/iron-icons/iron-icons';
import '@polymer/paper-button/paper-button';
import '@polymer/paper-dialog/paper-dialog';
import '@polymer/paper-input/paper-textarea';
import '@polymer/paper-progress/paper-progress';
import './cloud-install-styles';
import './outline-cloud-instructions-view';
import './outline-step-view';
import './style.css';
import {Polymer} from '@polymer/polymer/lib/legacy/polymer-fn';
import {html} from '@polymer/polymer/lib/utils/html-tag';
import type {IronCollapseElement} from '@polymer/iron-collapse/iron-collapse';
import type {IronIconElement} from '@polymer/iron-icon/iron-icon';
export interface OutlineManualServerEntry extends Element {
clear(): void;
retryTapped(): void;
cancelTapped(): void;
cloudProvider: 'generic'|'aws'|'gcp';
enableDoneButton: boolean;
showConnection: boolean;
}
Polymer({
_template: html`
<style include="cloud-install-styles"></style>
<style>
:host {
text-align: center;
--code-mixin: {
color: var(--dark-gray);
font-size: 14px;
font-family: RobotoMono-Regular, monospace;
line-height: 24px;
word-break: break-all;
}
}
.card {
color: var(--light-gray);
margin: 24px 0;
text-align: left;
}
.section {
padding: 24px 12px;
background: var(--background-contrast-color);
border-radius: 2px;
}
.section:not(:first-child) {
margin-top: 8px;
}
.section-header {
padding: 0 6px 0;
display: flex;
}
.instructions {
font-size: 16px;
line-height: 26px;
margin-left: 16px;
flex: 2;
}
.stepcircle {
height: 26px;
width: 26px;
font-size: 14px;
border-radius: 50%;
float: left;
vertical-align: middle;
color: #000;
background-color: #fff;
margin: auto;
text-align: center;
line-height: 26px;
}
.drop-down,
.drop-down iron-icon {
color: #fff;
}
.drop-down > * {
vertical-align: middle;
}
.drop-down span {
margin: 0 6px;
}
.drop-down:hover {
cursor: pointer;
}
/* This element surrounds the copy and paste elements. */
.section-content {
margin: 24px 12px 0 48px;
padding: 24px;
background-color: #eceff1;
border-radius: 4px;
}
.section-content-instructions {
margin: 24px 12px;
}
.section-content-instructions li {
margin-bottom: 24px;
}
.section-content-instructions a {
color: #00bfa5;
}
.section-content-instructions iron-icon {
color: #00bfa5;
width: 16px;
height: 16px;
margin-left: 4px;
vertical-align: middle;
}
paper-textarea {
--iron-autogrow-textarea: {
@apply --code-mixin;
}
--paper-input-container-underline: {
display: none;
}
--paper-input-container-underline-focus: {
display: none;
}
}
#gcp-tag {
font-weight: 500;
letter-spacing: 0.05em;
font-size: 10px;
margin-bottom: 8px;
text-transform: uppercase;
color: var(--light-gray);
}
#gcp-new-flow-promo {
padding: 24px;
border: 1px solid var(--border-color);
cursor: pointer;
font-size: 16px;
margin-top: unset;
}
/* rtl:ignore */
.code,
#command,
paper-textarea {
direction: ltr;
text-align: left;
@apply --code-mixin;
}
iron-icon {
display: inline-block;
vertical-align: top;
color: black;
}
#button-row {
display: flex;
justify-content: space-between;
padding: 0 24px 24px 60px;
background-color: var(--background-contrast-color);
}
paper-button {
margin: 0;
}
paper-progress {
margin: 0;
}
#cancelButton {
color: var(--light-gray);
border: 1px solid var(--border-color);
border-radius: 2px;
width: 45%;
}
#doneButton {
border-radius: 2px;
width: 45%;
background-color: var(--primary-green);
color: var(--light-gray);
}
#doneButton[disabled] {
background-color: var(--border-color);
}
#aws-logo {
vertical-align: top;
}
</style>
<outline-step-view>
<span slot="step-title">[[localize('manual-server-title')]]</span>
<span slot="step-description">[[localize('manual-server-description', 'cloudProvider', cloudProviderName)]]</span>
<div class="card">
<!-- GCP -->
<div id="gcp-new-flow-promo" class="section-content-instructions" on-tap="gcpNewFlowTapped" hidden\$="[[!isCloudProviderGcp]]">
<div id="gcp-tag">[[localize('experimental')]]</div>
<a>[[localize('setup-gcp-promo')]]<iron-icon icon=open-in-new></iron-icon></a>
</div>
<div class="section" hidden\$="[[!isCloudProviderGcp]]">
<div class="section-header">
<!-- TODO(alalama): localize numbers -->
<span class="stepcircle">1</span>
<div class="instructions">[[localize('gcp-create-server')]]</div>
<div class="drop-down" on-tap="_toggleGcpCreateServerDropDown">
<img src="images/gcp-logo.svg">
<span>[[localize('manual-server-instructions')]]</span>
<iron-icon id="gcpCreateServerDropDownIcon" icon="arrow-drop-down"></iron-icon>
</div>
</div>
<iron-collapse id="gcpCreateServerDropDown" class="instructions-collapse">
<div class="section-content-instructions">
<outline-cloud-instructions-view title="[[localize('gcp-create-project')]]" thumbnail-path="images/gcp-create-project-thumbnail.png" image-path="images/gcp-create-project-screenshot.png" localize="[[localize]]">
<ol>
<li inner-h-t-m-l="[[localize('gcp-create-new-project', 'openLink', '<a href=https://console.cloud.google.com/projectcreate>', 'closeLink', '<iron-icon icon=open-in-new></iron-icon></a>')]]"></li>
<li>[[localize('gcp-name-your-project')]]</li>
<li>[[localize('gcp-click-create')]]</li>
</ol>
</outline-cloud-instructions-view>
</div>
<div class="section-content-instructions">
<outline-cloud-instructions-view title="[[localize('manual-server-create-firewall')]]" thumbnail-path="images/gcp-thumbnail-1.png" image-path="images/gcp-screenshot-1.png" localize="[[localize]]">
<ol>
<li inner-h-t-m-l="[[localize('gcp-firewall-create-0', 'openLink', '<a href=https://console.cloud.google.com/networking/firewalls/add>', 'closeLink', '<iron-icon icon=open-in-new></iron-icon></a>')]]"></li>
<li>[[localize('gcp-firewall-create-1')]]</li>
<li>[[localize('gcp-firewall-create-2')]]</li>
<li>[[localize('gcp-firewall-create-3')]]</li>
<li>[[localize('gcp-firewall-create-4')]]</li>
<li>[[localize('gcp-click-create')]]</li>
</ol>
</outline-cloud-instructions-view>
</div>
<div class="section-content-instructions">
<outline-cloud-instructions-view title="[[localize('gcp-create-vm')]]" thumbnail-path="images/gcp-create-instance-thumbnail.png" image-path="images/gcp-create-instance-screenshot.png" localize="[[localize]]">
<ol>
<li inner-h-t-m-l="[[localize('gcp-create-new-vm', 'openLink', '<a href=https://console.cloud.google.com/compute/instancesAdd>', 'closeLink', '<iron-icon icon=open-in-new></iron-icon></a>')]]"></li>
<li>[[localize('gcp-type-outline-server')]]</li>
<li>[[localize('gcp-select-region')]]</li>
<li>[[localize('gcp-select-machine-type')]]</li>
<li>[[localize('gcp-select-networking')]]</li>
<li>[[localize('gcp-type-network-tag')]]</li>
<li>[[localize('gcp-click-create')]]</li>
</ol>
</outline-cloud-instructions-view>
</div>
</iron-collapse>
</div>
<!-- AWS -->
<div class="section" hidden\$="[[!isCloudProviderAws]]">
<div class="section-header">
<span class="stepcircle">1</span>
<div class="instructions">
[[localize('manual-server-firewall')]]
</div>
<div class="drop-down" on-tap="_toggleAwsDropDown">
<img id="aws-logo" src="images/aws-logo.svg">
<span>[[localize('manual-server-instructions')]]</span>
<iron-icon id="awsDropDownIcon" icon="arrow-drop-down"></iron-icon>
</div>
</div>
<iron-collapse id="awsDropDown" class="instructions-collapse">
<div class="section-content-instructions">
<outline-cloud-instructions-view title="[[localize('manual-server-create-group')]]" thumbnail-path="images/aws-lightsail-thumbnail-1.png" image-path="images/aws-lightsail-screenshot-1.png" localize="[[localize]]">
<ol>
<li inner-h-t-m-l="[[localize('aws-lightsail-firewall-0', 'openLink', '<a href=https://lightsail.aws.amazon.com>', 'closeLink', '<iron-icon icon=open-in-new></iron-icon></a>')]]"></li>
<li>[[localize('aws-lightsail-firewall-1')]]</li>
<li>[[localize('aws-lightsail-firewall-2')]]</li>
<li>[[localize('aws-lightsail-firewall-3')]]</li>
<li>[[localize('aws-lightsail-firewall-4')]]</li>
<li>[[localize('aws-lightsail-firewall-5')]]</li>
</ol>
</outline-cloud-instructions-view>
</div>
</iron-collapse>
</div>
<!-- Install command -->
<div class="section">
<div class="section-header">
<span class="stepcircle">[[installScriptStepNumber]]</span>
<div class="instructions">
[[localize('manual-server-install-run')]]
</div>
</div>
<div class="section-content">
<div id="command">
sudo bash -c "\$(wget -qO-
https://raw.githubusercontent.com/Jigsaw-Code/outline-server/master/src/server_manager/install_scripts/install_server.sh)"
</div>
</div>
</div>
<!-- Paste input -->
<div class="section">
<div class="section-header">
<span class="stepcircle">[[pasteJsonStepNumber]]</span>
<div class="instructions">
[[localize('manual-server-install-paste')]]
</div>
</div>
<div class="section-content">
<paper-textarea id="serverConfig" type="text" placeholder\$="[[placeholderText]]" class="code" rows="4" max-rows="4" no-label-float="" on-value-changed="onServerConfigChanged"></paper-textarea>
</div>
</div>
<div id="button-row">
<paper-button id="cancelButton" on-tap="cancelTapped" class="secondary">[[localize('cancel')]]</paper-button>
<paper-button id="doneButton" on-tap="doneTapped" class="primary" disabled\$="[[!enableDoneButton]]">[[localize('done')]]</paper-button>
</div>
<paper-progress hidden\$="[[!showConnection]]" indeterminate="" class="slow"></paper-progress>
</div>
</outline-step-view>
`,
is: 'outline-manual-server-entry',
properties: {
placeholderText: {
type: String,
value:
'{"apiUrl":"https://xxx.xxx.xxx.xxx:xxxxx/xxxxxxxxxxxxxxxxxxxxxx","certSha256":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}',
},
showConnection: Boolean,
cloudProvider: {
type: String,
value: 'generic',
},
cloudProviderName: {
type: String,
computed: '_computeCloudProviderName(cloudProvider)',
},
isCloudProviderAws: {
type: Boolean,
computed: '_computeIsCloudProviderAws(cloudProvider)',
},
isCloudProviderGcp: {
type: Boolean,
computed: '_computeIsCloudProviderGcp(cloudProvider)',
},
isGenericCloudProvider: {
type: Boolean,
computed: '_computeIsGenericCloudProvider(cloudProvider)',
},
installScriptStepNumber: {
type: Number,
computed: '_computeInstallScriptStepNumber(isGenericCloudProvider)',
},
pasteJsonStepNumber: {
type: Number,
computed: '_computePasteJsonStepNumber(installScriptStepNumber)',
},
enableDoneButton: {
type: Boolean,
value: false,
},
localize: {
type: Function,
},
},
doneTapped() {
this.showConnection = true;
this.fire('ManualServerEntered', {
userInput: this.$.serverConfig.value,
});
},
cancelTapped() {
this.fire('ManualServerEntryCancelled');
},
retryTapped() {
this.showConnection = false;
this.doneTapped();
},
gcpNewFlowTapped() {
this.fire('ConnectGcpAccountRequested');
},
clear() {
this.$.serverConfig.value = '';
this.showConnection = false;
for (const dropdown of this.root.querySelectorAll('.instructions-collapse')) {
dropdown.hide();
}
},
_computeCloudProviderName(cloudProvider: string) {
switch (cloudProvider) {
case 'aws':
return 'Amazon Web Services';
case 'gcp':
return 'Google Cloud Platform';
default:
return '';
}
},
_computeIsCloudProviderAws(cloudProvider: string) {
return cloudProvider === 'aws';
},
_computeIsCloudProviderGcp(cloudProvider: string) {
return cloudProvider === 'gcp';
},
_computeIsGenericCloudProvider(cloudProvider: string) {
return cloudProvider === 'generic';
},
_computeInstallScriptStepNumber(isGenericCloudProvider: boolean) {
return isGenericCloudProvider ? 1 : 2;
},
_computePasteJsonStepNumber(installScriptStepNumber: number) {
return installScriptStepNumber + 1;
},
_toggleAwsDropDown() {
this._toggleDropDown(this.$.awsDropDown, this.$.awsDropDownIcon);
},
_toggleGcpFirewallDropDown() {
this._toggleDropDown(this.$.gcpFirewallDropDown, this.$.gcpFirewallDropDownIcon);
},
_toggleGcpCreateServerDropDown() {
this._toggleDropDown(this.$.gcpCreateServerDropDown, this.$.gcpCreateServerDropDownIcon);
},
_toggleGcpCreateProjectDropDown() {
this._toggleDropDown(this.$.gcpCreateProjectDropDown, this.$.gcpCreateProjectDropDownIcon);
},
_toggleDropDown(dropDown: IronCollapseElement, icon: IronIconElement) {
dropDown.toggle();
icon.icon = dropDown.opened ? 'arrow-drop-up' : 'arrow-drop-down';
},
onServerConfigChanged() {
this.fire('ManualServerEdited', {
userInput: this.$.serverConfig.value,
});
}
}); | the_stack |
// Copyright (c) 2022, Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
/**
* This file was auto-generated by openapi-typescript.
* Do not make direct changes to the file.
*/
export interface paths {
'/addresses': {
/** Retrieve all managed addresses for this client. */
get: operations['get_addresses'];
};
'/call': {
/**
* Execute a Move call transaction by calling the specified function in the
* module of the given package. Arguments are passed in and type will be
* inferred from function signature. Gas usage is capped by the gas_budget.
*
* Example CallRequest
* {
* "sender": "b378b8d26c4daa95c5f6a2e2295e6e5f34371c1659e95f572788ffa55c265363",
* "package_object_id": "0x2",
* "module": "ObjectBasics",
* "function": "create",
* "args": [
* 200,
* "b378b8d26c4daa95c5f6a2e2295e6e5f34371c1659e95f572788ffa55c265363"
* ],
* "gas_object_id": "1AC945CA31E77991654C0A0FCA8B0FD9C469B5C6",
* "gas_budget": 2000
* }
*/
post: operations['call'];
};
'/docs': {
/** Generate OpenAPI documentation. */
get: operations['docs'];
};
'/object_info': {
/** Returns the object information for a specified object. */
get: operations['object_info'];
};
'/object_schema': {
/** Returns the schema for a specified object. */
get: operations['object_schema'];
};
'/objects': {
/** Returns list of objects owned by an address. */
get: operations['get_objects'];
};
'/sui/genesis': {
/**
* Specify the genesis state of the network.
*
* You can specify the number of authorities, an initial number of addresses
* and the number of gas objects to be assigned to those addresses.
*
* Note: This is a temporary endpoint that will no longer be needed once the
* network has been started on testnet or mainnet.
*/
post: operations['genesis'];
};
'/sui/start': {
/**
* Start servers with the specified configurations from the genesis endpoint.
*
* Note: This is a temporary endpoint that will no longer be needed once the
* network has been started on testnet or mainnet.
*/
post: operations['sui_start'];
};
'/sui/stop': {
/**
* Stop sui network and delete generated configs & storage.
*
* Note: This is a temporary endpoint that will no longer be needed once the
* network has been started on testnet or mainnet.
*/
post: operations['sui_stop'];
};
'/sync': {
/**
* Synchronize client state with authorities. This will fetch the latest information
* on all objects owned by each address that is managed by this client state.
*/
post: operations['sync'];
};
'/transfer': {
/**
* Transfer object from one address to another. Gas will be paid using the gas
* provided in the request. This will be done through a native transfer
* transaction that does not require Move VM executions, hence is much cheaper.
*
* Notes:
* - Non-coin objects cannot be transferred natively and will require a Move call
*
* Example TransferTransactionRequest
* {
* "from_address": "1DA89C9279E5199DDC9BC183EB523CF478AB7168",
* "object_id": "4EED236612B000B9BEBB99BA7A317EFF27556A0C",
* "to_address": "5C20B3F832F2A36ED19F792106EC73811CB5F62C",
* "gas_object_id": "96ABE602707B343B571AAAA23E3A4594934159A5"
* }
*/
post: operations['transfer_object'];
};
}
export interface components {
schemas: {
/** @description Request containing the information required to execute a move module. */
CallRequest: {
/** @description Required; JSON representation of the arguments */
args: components['schemas']['SuiJsonValue'][];
/** @description Required; Name of the function to be called in the move module */
function: string;
/**
* Format: uint64
* @description Required; Gas budget required as a cap for gas usage
*/
gasBudget: number;
/** @description Required; Hex code as string representing the gas object id */
gasObjectId: string;
/** @description Required; Name of the move module */
module: string;
/** @description Required; Hex code as string representing Move module location */
packageObjectId: string;
/** @description Required; Hex code as string representing the sender's address */
sender: string;
/** @description Optional; The argument types to be parsed */
typeArgs?: string[] | null;
};
/** @description Response containing the API documentation. */
DocumentationResponse: {
/** @description A JSON object containing the OpenAPI definition for this API. */
documentation: unknown;
};
/** @description Response containing the resulting wallet & network config of the provided genesis configuration. */
GenesisResponse: {
/** @description Information about authorities and the list of loaded move packages. */
networkConfig: unknown;
/** @description List of managed addresses and the list of authorities */
walletConfig: unknown;
};
/** @description Response containing the managed addresses for this client. */
GetAddressResponse: {
/** @description Vector of hex codes as strings representing the managed addresses */
addresses: string[];
};
/** @description Returns the list of objects owned by an address. */
GetObjectsResponse: {
objects: components['schemas']['Object'][];
};
/** @description JSON representation of an object in the Sui network. */
Object: {
/** @description Hash of the object's contents used for local validation */
objectDigest: string;
/** @description Hex code as string representing the object id */
objectId: string;
/** @description Object version */
version: string;
};
/** @description Response containing the information of an object if found, otherwise an error is returned. */
ObjectInfoResponse: {
/** @description JSON representation of the object data */
data: unknown;
/** @description Hex code as string representing the objet id */
id: string;
/** @description Type of object, i.e. Coin */
objType: string;
/** @description Hex code as string representing the owner's address */
owner: string;
/** @description Boolean representing if the object is mutable */
readonly: string;
/** @description Sequence number of the object */
version: string;
};
/** @description Response containing the information of an object schema if found, otherwise an error is returned. */
ObjectSchemaResponse: {
/** @description JSON representation of the object schema */
schema: unknown;
};
SuiJsonValue: unknown;
/** @description Request containing the address that requires a sync. */
SyncRequest: {
/** @description Required; Hex code as string representing the address */
address: string;
};
/** @description Response containing the summary of effects made on an object and the certificate associated with the transaction that verifies the transaction. */
TransactionResponse: {
/** @description JSON representation of the certificate verifying the transaction */
certificate: unknown;
/**
* Format: uint64
* @description Integer representing the acutal cost of the transaction
*/
gasUsed: number;
/** @description JSON representation of the list of resulting effects on the object */
objectEffectsSummary: unknown;
};
/** @description Request containing the information needed to execute a transfer transaction. */
TransferTransactionRequest: {
/** @description Required; Hex code as string representing the address to be sent from */
fromAddress: string;
/** @description Required; Hex code as string representing the gas object id to be used as payment */
gasObjectId: string;
/** @description Required; Hex code as string representing the object id */
objectId: string;
/** @description Required; Hex code as string representing the address to be sent to */
toAddress: string;
};
};
}
export interface operations {
/** Retrieve all managed addresses for this client. */
get_addresses: {
responses: {
/** successful operation */
200: {
content: {
'application/json': components['schemas']['GetAddressResponse'];
};
};
};
};
/**
* Execute a Move call transaction by calling the specified function in the
* module of the given package. Arguments are passed in and type will be
* inferred from function signature. Gas usage is capped by the gas_budget.
*
* Example CallRequest
* {
* "sender": "b378b8d26c4daa95c5f6a2e2295e6e5f34371c1659e95f572788ffa55c265363",
* "package_object_id": "0x2",
* "module": "ObjectBasics",
* "function": "create",
* "args": [
* 200,
* "b378b8d26c4daa95c5f6a2e2295e6e5f34371c1659e95f572788ffa55c265363"
* ],
* "gas_object_id": "1AC945CA31E77991654C0A0FCA8B0FD9C469B5C6",
* "gas_budget": 2000
* }
*/
call: {
responses: {
/** successful operation */
200: {
content: {
'application/json': components['schemas']['TransactionResponse'];
};
};
};
requestBody: {
content: {
'application/json': components['schemas']['CallRequest'];
};
};
};
/** Generate OpenAPI documentation. */
docs: {
responses: {
/** successful operation */
200: {
content: {
'application/json': components['schemas']['DocumentationResponse'];
};
};
};
};
/** Returns the object information for a specified object. */
object_info: {
parameters: {
query: {
objectId: string;
};
};
responses: {
/** successful operation */
200: {
content: {
'application/json': components['schemas']['ObjectInfoResponse'];
};
};
};
};
/** Returns the schema for a specified object. */
object_schema: {
parameters: {
query: {
objectId: string;
};
};
responses: {
/** successful operation */
200: {
content: {
'application/json': components['schemas']['ObjectSchemaResponse'];
};
};
};
};
/** Returns list of objects owned by an address. */
get_objects: {
parameters: {
query: {
address: string;
};
};
responses: {
/** successful operation */
200: {
content: {
'application/json': components['schemas']['GetObjectsResponse'];
};
};
};
};
/**
* Specify the genesis state of the network.
*
* You can specify the number of authorities, an initial number of addresses
* and the number of gas objects to be assigned to those addresses.
*
* Note: This is a temporary endpoint that will no longer be needed once the
* network has been started on testnet or mainnet.
*/
genesis: {
responses: {
/** successful operation */
200: {
content: {
'application/json': components['schemas']['GenesisResponse'];
};
};
};
};
/**
* Start servers with the specified configurations from the genesis endpoint.
*
* Note: This is a temporary endpoint that will no longer be needed once the
* network has been started on testnet or mainnet.
*/
sui_start: {
responses: {
/** successful operation */
200: {
content: {
'application/json': string;
};
};
};
};
/**
* Stop sui network and delete generated configs & storage.
*
* Note: This is a temporary endpoint that will no longer be needed once the
* network has been started on testnet or mainnet.
*/
sui_stop: {
responses: {
/** resource updated */
204: never;
};
};
/**
* Synchronize client state with authorities. This will fetch the latest information
* on all objects owned by each address that is managed by this client state.
*/
sync: {
responses: {
/** resource updated */
204: never;
};
requestBody: {
content: {
'application/json': components['schemas']['SyncRequest'];
};
};
};
/**
* Transfer object from one address to another. Gas will be paid using the gas
* provided in the request. This will be done through a native transfer
* transaction that does not require Move VM executions, hence is much cheaper.
*
* Notes:
* - Non-coin objects cannot be transferred natively and will require a Move call
*
* Example TransferTransactionRequest
* {
* "from_address": "1DA89C9279E5199DDC9BC183EB523CF478AB7168",
* "object_id": "4EED236612B000B9BEBB99BA7A317EFF27556A0C",
* "to_address": "5C20B3F832F2A36ED19F792106EC73811CB5F62C",
* "gas_object_id": "96ABE602707B343B571AAAA23E3A4594934159A5"
* }
*/
transfer_object: {
responses: {
/** successful operation */
200: {
content: {
'application/json': components['schemas']['TransactionResponse'];
};
};
};
requestBody: {
content: {
'application/json': components['schemas']['TransferTransactionRequest'];
};
};
};
}
export interface external {} | the_stack |
import EnumInsideTypeCollectionWithoutVersion from "../../../generated/joynr/types/TestTypesWithoutVersion/EnumInsideTypeCollectionWithoutVersion";
import MapInsideTypeCollectionWithoutVersion from "../../../generated/joynr/types/TestTypesWithoutVersion/MapInsideTypeCollectionWithoutVersion";
import StructInsideTypeCollectionWithoutVersion from "../../../generated/joynr/types/TestTypesWithoutVersion/StructInsideTypeCollectionWithoutVersion";
import TEnum from "../../../generated/joynr/types/TestTypes/TEnum";
import TStringKeyMap from "../../../generated/joynr/types/TestTypes/TStringKeyMap";
import TStruct from "../../../generated/joynr/types/TestTypes/TStruct";
import TStructWithTypedefMembers from "../../../generated/joynr/types/TestTypes/TStructWithTypedefMembers";
import * as Typing from "../../../../main/js/joynr/util/Typing";
describe("libjoynr-js.joynr.TypeGenerator.Enum", () => {
it("type collection enum default version is set correctly", () => {
expect(EnumInsideTypeCollectionWithoutVersion.MAJOR_VERSION).toBeDefined();
expect(EnumInsideTypeCollectionWithoutVersion.MAJOR_VERSION).toEqual(0);
expect(EnumInsideTypeCollectionWithoutVersion.MINOR_VERSION).toBeDefined();
expect(EnumInsideTypeCollectionWithoutVersion.MINOR_VERSION).toEqual(0);
});
it("type collection enum version is set correctly", () => {
expect(TEnum.MAJOR_VERSION).toBeDefined();
expect(TEnum.MAJOR_VERSION).toEqual(49);
expect(TEnum.MINOR_VERSION).toBeDefined();
expect(TEnum.MINOR_VERSION).toEqual(13);
});
}); // describe Enum
describe("libjoynr-js.joynr.TypeGenerator.Map", () => {
it("type collection map default version is set correctly", () => {
expect(MapInsideTypeCollectionWithoutVersion.MAJOR_VERSION).toBeDefined();
expect(MapInsideTypeCollectionWithoutVersion.MAJOR_VERSION).toEqual(0);
expect(MapInsideTypeCollectionWithoutVersion.MINOR_VERSION).toBeDefined();
expect(MapInsideTypeCollectionWithoutVersion.MINOR_VERSION).toEqual(0);
});
it("type collection map version is set correctly", () => {
expect(TStringKeyMap.MAJOR_VERSION).toBeDefined();
expect(TStringKeyMap.MAJOR_VERSION).toEqual(49);
expect(TStringKeyMap.MINOR_VERSION).toBeDefined();
expect(TStringKeyMap.MINOR_VERSION).toEqual(13);
});
}); // describe Map
describe("libjoynr-js.joynr.TypeGenerator.Compound", () => {
let testStructWithTypeDefMembers: any;
let testStructWithObjectNullMaps: any;
beforeEach(() => {
testStructWithTypeDefMembers = new TStructWithTypedefMembers({
typeDefForPrimitive: 42,
typeDefForTStruct: new TStruct({
tDouble: 47.11,
tInt64: 2323,
tString: "testString"
}),
typeDefForTStringKeyMap: new TStringKeyMap({
key1: "value1",
key2: "value2"
}),
typeDefForTEnum: TEnum.TLITERALA,
arrayOfTypeDefForPrimitive: [],
arrayOfTypeDefForTStruct: [],
arrayOfTypeDefForTStringKeyMap: [],
arrayOfTypeDefForTEnum: []
});
const testObjectNullTStruct = Object.create(null);
testObjectNullTStruct["tDouble"] = 47.11;
testObjectNullTStruct["tInt64"] = 2323;
testObjectNullTStruct["tString"] = "testString";
const testObjectNullStringKeyMap = Object.create(null);
testObjectNullStringKeyMap["key1"] = "value1";
testObjectNullStringKeyMap["key2"] = "value2";
testStructWithObjectNullMaps = new TStructWithTypedefMembers({
typeDefForPrimitive: 42,
typeDefForTStruct: new TStruct(testObjectNullTStruct),
typeDefForTStringKeyMap: new TStringKeyMap(testObjectNullStringKeyMap),
typeDefForTEnum: TEnum.TLITERALA,
arrayOfTypeDefForPrimitive: [],
arrayOfTypeDefForTStruct: [],
arrayOfTypeDefForTStringKeyMap: [],
arrayOfTypeDefForTEnum: []
});
});
it("type collection struct default version is set correctly", () => {
expect(StructInsideTypeCollectionWithoutVersion.MAJOR_VERSION).toBeDefined();
expect(StructInsideTypeCollectionWithoutVersion.MAJOR_VERSION).toEqual(0);
expect(StructInsideTypeCollectionWithoutVersion.MINOR_VERSION).toBeDefined();
expect(StructInsideTypeCollectionWithoutVersion.MINOR_VERSION).toEqual(0);
});
it("type collection struct version is set correctly", () => {
expect(TStruct.MAJOR_VERSION).toBeDefined();
expect(TStruct.MAJOR_VERSION).toEqual(49);
expect(TStruct.MINOR_VERSION).toBeDefined();
expect(TStruct.MINOR_VERSION).toEqual(13);
});
it("StructWithTypedefMembers: checkMembers accepts correct types", () => {
expect(() =>
TStructWithTypedefMembers.checkMembers(testStructWithTypeDefMembers, Typing.checkPropertyIfDefined)
).not.toThrow();
});
it("StructWithTypedefMembers: checkMembers detects wrong types", () => {
let testStruct: any;
testStruct = new TStructWithTypedefMembers(testStructWithTypeDefMembers);
testStruct.typeDefForPrimitive = "string";
expect(() => TStructWithTypedefMembers.checkMembers(testStruct, Typing.checkPropertyIfDefined)).toThrow(
"members.typeDefForPrimitive is not of type Number. Actual type is String"
);
testStruct = new TStructWithTypedefMembers(testStructWithTypeDefMembers);
testStruct.typeDefForTStruct = "string";
expect(() => TStructWithTypedefMembers.checkMembers(testStruct, Typing.checkPropertyIfDefined)).toThrow(
"members.typeDefForTStruct is not of type TStruct. Actual type is String"
);
testStruct = new TStructWithTypedefMembers(testStructWithTypeDefMembers);
testStruct.typeDefForTStringKeyMap = "string";
expect(() => TStructWithTypedefMembers.checkMembers(testStruct, Typing.checkPropertyIfDefined)).toThrow(
"members.typeDefForTStringKeyMap is not of type TStringKeyMap. Actual type is String"
);
testStruct = new TStructWithTypedefMembers(testStructWithTypeDefMembers);
testStruct.typeDefForTEnum = 44;
expect(() => TStructWithTypedefMembers.checkMembers(testStruct, Typing.checkPropertyIfDefined)).toThrow(
"members.typeDefForTEnum is not of type TEnum. Actual type is Number"
);
testStruct = new TStructWithTypedefMembers(testStructWithTypeDefMembers);
testStruct.arrayOfTypeDefForPrimitive = testStruct.typeDefForPrimitive;
expect(() => TStructWithTypedefMembers.checkMembers(testStruct, Typing.checkPropertyIfDefined)).toThrow(
"members.arrayOfTypeDefForPrimitive is not of type Array. Actual type is Number"
);
testStruct = new TStructWithTypedefMembers(testStructWithTypeDefMembers);
testStruct.arrayOfTypeDefForTStruct = testStruct.typeDefForTStruct;
expect(() => TStructWithTypedefMembers.checkMembers(testStruct, Typing.checkPropertyIfDefined)).toThrow(
"members.arrayOfTypeDefForTStruct is not of type Array. Actual type is TStruct"
);
testStruct = new TStructWithTypedefMembers(testStructWithTypeDefMembers);
testStruct.arrayOfTypeDefForTStringKeyMap = testStruct.typeDefForTStringKeyMap;
expect(() => TStructWithTypedefMembers.checkMembers(testStruct, Typing.checkPropertyIfDefined)).toThrow(
"members.arrayOfTypeDefForTStringKeyMap is not of type Array. Actual type is TStringKeyMap"
);
testStruct = new TStructWithTypedefMembers(testStructWithTypeDefMembers);
testStruct.arrayOfTypeDefForTEnum = testStruct.typeDefForTEnum;
expect(() => TStructWithTypedefMembers.checkMembers(testStruct, Typing.checkPropertyIfDefined)).toThrow(
"members.arrayOfTypeDefForTEnum is not of type Array. Actual type is TEnum"
);
});
it("StructWithTypedefMembers with ObjectNullMaps: checkMembers detects wrong types", () => {
let testStruct: any;
testStruct = new TStructWithTypedefMembers(testStructWithObjectNullMaps);
testStruct.typeDefForPrimitive = "string";
expect(() => TStructWithTypedefMembers.checkMembers(testStruct, Typing.checkPropertyIfDefined)).toThrow(
"members.typeDefForPrimitive is not of type Number. Actual type is String"
);
testStruct = new TStructWithTypedefMembers(testStructWithObjectNullMaps);
testStruct.typeDefForTStruct = "string";
expect(() => TStructWithTypedefMembers.checkMembers(testStruct, Typing.checkPropertyIfDefined)).toThrow(
"members.typeDefForTStruct is not of type TStruct. Actual type is String"
);
testStruct = new TStructWithTypedefMembers(testStructWithObjectNullMaps);
testStruct.typeDefForTStringKeyMap = "string";
expect(() => TStructWithTypedefMembers.checkMembers(testStruct, Typing.checkPropertyIfDefined)).toThrow(
"members.typeDefForTStringKeyMap is not of type TStringKeyMap. Actual type is String"
);
testStruct = new TStructWithTypedefMembers(testStructWithObjectNullMaps);
testStruct.typeDefForTEnum = 44;
expect(() => TStructWithTypedefMembers.checkMembers(testStruct, Typing.checkPropertyIfDefined)).toThrow(
"members.typeDefForTEnum is not of type TEnum. Actual type is Number"
);
testStruct = new TStructWithTypedefMembers(testStructWithObjectNullMaps);
testStruct.arrayOfTypeDefForPrimitive = testStruct.typeDefForPrimitive;
expect(() => TStructWithTypedefMembers.checkMembers(testStruct, Typing.checkPropertyIfDefined)).toThrow(
"members.arrayOfTypeDefForPrimitive is not of type Array. Actual type is Number"
);
testStruct = new TStructWithTypedefMembers(testStructWithObjectNullMaps);
testStruct.arrayOfTypeDefForTStruct = testStruct.typeDefForTStruct;
expect(() => TStructWithTypedefMembers.checkMembers(testStruct, Typing.checkPropertyIfDefined)).toThrow(
"members.arrayOfTypeDefForTStruct is not of type Array. Actual type is TStruct"
);
testStruct = new TStructWithTypedefMembers(testStructWithObjectNullMaps);
testStruct.arrayOfTypeDefForTStringKeyMap = testStruct.typeDefForTStringKeyMap;
expect(() => TStructWithTypedefMembers.checkMembers(testStruct, Typing.checkPropertyIfDefined)).toThrow(
"members.arrayOfTypeDefForTStringKeyMap is not of type Array. Actual type is TStringKeyMap"
);
testStruct = new TStructWithTypedefMembers(testStructWithObjectNullMaps);
testStruct.arrayOfTypeDefForTEnum = testStruct.typeDefForTEnum;
expect(() => TStructWithTypedefMembers.checkMembers(testStruct, Typing.checkPropertyIfDefined)).toThrow(
"members.arrayOfTypeDefForTEnum is not of type Array. Actual type is TEnum"
);
});
}); | the_stack |
import { decimalStr, fromWei } from '../utils/Converter';
import { logGas } from '../utils/Log';
import { VDODOContext, getVDODOContext } from '../utils/VDODOContext';
import { assert } from 'chai';
import BigNumber from 'bignumber.js';
const truffleAssert = require('truffle-assertions');
let account0: string;
let account1: string;
let account2: string;
let account3: string;
let dodoTeam: string;
let defaultSuperAddress: string;
let owner: string;
async function init(ctx: VDODOContext): Promise<void> {
dodoTeam = ctx.Deployer;
account0 = ctx.SpareAccounts[0];
account1 = ctx.SpareAccounts[1];
account2 = ctx.SpareAccounts[2];
account3 = ctx.SpareAccounts[3];
defaultSuperAddress = ctx.Maintainer
owner = ctx.Deployer
await ctx.mintTestToken(account0, decimalStr("1000"));
await ctx.mintTestToken(account1, decimalStr("1000"));
await ctx.mintTestToken(account2, decimalStr("1000"));
await ctx.mintTestToken(account3, decimalStr("1000"));
await ctx.approveProxy(account0);
await ctx.approveProxy(account1);
await ctx.approveProxy(account2);
await ctx.approveProxy(account3);
await ctx.VDODO.methods.setCantransfer(true).send(ctx.sendParam(owner))
}
async function getGlobalState(ctx: VDODOContext, logInfo?: string) {
let [alpha,] = await ctx.VDODO.methods.getLatestAlpha().call();
var lastRewardBlock = await ctx.VDODO.methods._LAST_REWARD_BLOCK_().call();
var totalSuppy = await ctx.VDODO.methods.totalSupply().call();
// console.log(logInfo + " alpha:" + fromWei(alpha, 'ether') + " lastRewardBlock:" + lastRewardBlock + " totalSuppy:" + fromWei(totalSuppy, 'ether'));
return [alpha, lastRewardBlock, totalSuppy]
}
async function dodoBalance(ctx: VDODOContext, user: string, logInfo?: string) {
var dodo_contract = await ctx.DODO.methods.balanceOf(ctx.VDODO.options.address).call();
var dodo_account = await ctx.DODO.methods.balanceOf(user).call();
// console.log(logInfo + " DODO:" + fromWei(dodo_contract, 'ether') + " account:" + fromWei(dodo_account, 'ether'));
return [dodo_contract, dodo_account]
}
async function getUserInfo(ctx: VDODOContext, user: string, logInfo?: string) {
var info = await ctx.VDODO.methods.userInfo(user).call();
var res = {
"stakingPower": info.stakingPower,
"superiorSP": info.superiorSP,
"superior": info.superior,
"credit": info.credit
}
// console.log(logInfo + " stakingPower:" + fromWei(info.stakingPower, 'ether') + " superiorSP:" + fromWei(info.superiorSP, 'ether') + " superior:" + info.superior + " credit:" + fromWei(info.credit, 'ether'));
return res
}
async function mint(ctx: VDODOContext, user: string, mintAmount: string, superior: string) {
await ctx.VDODO.methods.mint(
mintAmount,
superior
).send(ctx.sendParam(user));
}
describe("vDODO-erc20", () => {
let snapshotId: string;
let ctx: VDODOContext;
before(async () => {
ctx = await getVDODOContext();
//打开transfer开关
await init(ctx);
});
beforeEach(async () => {
snapshotId = await ctx.EVM.snapshot();
});
afterEach(async () => {
await ctx.EVM.reset(snapshotId);
});
describe("vdodo-erc20", () => {
it("totalSupply", async () => {
var lastRewardBlock = await ctx.VDODO.methods._LAST_REWARD_BLOCK_().call();
var curBlock = await ctx.Web3.eth.getBlockNumber();
console.log("init-block:" + lastRewardBlock + " blockNumber:" + curBlock)
var totalSuppy = await ctx.VDODO.methods.totalSupply().call();
assert(totalSuppy, decimalStr("0.09"))
await ctx.VDODO.methods.mint(decimalStr("10"), dodoTeam).send(ctx.sendParam(account0))
var totalSuppy = await ctx.VDODO.methods.totalSupply().call();
assert(totalSuppy, decimalStr("0.2"))
await ctx.VDODO.methods.mint(decimalStr("10"), dodoTeam).send(ctx.sendParam(account0))
var totalSuppy = await ctx.VDODO.methods.totalSupply().call();
assert(totalSuppy, decimalStr("0.31"))
})
it("transfer-vdodo", async () => {
//检查四个人 【包括from, to 以及各自的上级】,info变化
//alpha lastRewardBlock
//各自dodo余额变化
let [, lastRewardBlockStart,] = await getGlobalState(ctx, "before");
await ctx.VDODO.methods.mint(decimalStr("10"), dodoTeam).send(ctx.sendParam(account0))
await ctx.VDODO.methods.mint(decimalStr("10"), account0).send(ctx.sendParam(account1))
await ctx.VDODO.methods.mint(decimalStr("10"), account1).send(ctx.sendParam(account2))
await ctx.VDODO.methods.mint(decimalStr("10"), account2).send(ctx.sendParam(account3))
//增加一个区块
await ctx.mintTestToken(account0, decimalStr("0"));
let [alpha, lastRewardBlock,] = await getGlobalState(ctx, "after");
assert.equal(alpha, "1195775916960005765");
var totalSuppy = await ctx.VDODO.methods.totalSupply().call();
assert.equal(totalSuppy, "540000000000000000");
let userInfo0 = await getUserInfo(ctx, account0, "User0 ");
assert.equal(userInfo0.stakingPower, "10916666666666666666");
assert.equal(userInfo0.superiorSP, decimalStr("1"));
assert.equal(userInfo0.credit, "999999999999999999");
let userInfo1 = await getUserInfo(ctx, account1, "User1 ")
assert.equal(userInfo1.stakingPower, "10045138888888888889");
assert.equal(userInfo1.superiorSP, "916666666666666666");
assert.equal(userInfo1.credit, "999999999999999999");
let userInfo2 = await getUserInfo(ctx, account2, "User2 ");
assert.equal(userInfo2.stakingPower, "9638792438271604945");
assert.equal(userInfo2.superiorSP, "878472222222222222");
assert.equal(userInfo2.credit, "999999999999999999");
let userInfo3 = await getUserInfo(ctx, account3, "User3 ");
assert.equal(userInfo3.stakingPower, "8540702160493827171");
assert.equal(userInfo3.superiorSP, "854070216049382717");
assert.equal(userInfo3.credit, decimalStr("0"));
let [, dodo_u0] = await dodoBalance(ctx, account0, "start")
assert.equal(dodo_u0, "990000000000000000000");
let [, dodo_u1] = await dodoBalance(ctx, account1, "start")
assert.equal(dodo_u1, "990000000000000000000");
let [, dodo_u2] = await dodoBalance(ctx, account2, "start")
assert.equal(dodo_u2, "990000000000000000000");
let [, dodo_u3] = await dodoBalance(ctx, account3, "start")
assert.equal(dodo_u3, "990000000000000000000");
let account1Balance = await ctx.VDODO.methods.balanceOf(account1).call()
await logGas(await ctx.VDODO.methods.transfer(
account3,
account1Balance
), ctx.sendParam(account1), "transfer");
let userInfo0_after = await getUserInfo(ctx, account0, "userInfo0_after");
let userInfo1_after = await getUserInfo(ctx, account1, "userInfo1_after");
let userInfo2_after = await getUserInfo(ctx, account2, "userInfo2_after");
let userInfo3_after = await getUserInfo(ctx, account3, "userInfo3_after");
assert.equal(userInfo0_after.stakingPower, "10097456459435626102");
assert.equal(userInfo0_after.superiorSP, decimalStr("1"));
assert.equal(userInfo0_after.credit, "0");
assert.equal(userInfo1_after.stakingPower, "1024213041698160810");
assert.equal(userInfo1_after.superiorSP, "14574081947593859");
assert.equal(userInfo1_after.credit, "999999999999999999");
assert.equal(userInfo2_after.stakingPower, "10540885022990677752");
assert.equal(userInfo2_after.superiorSP, "878472222222222222");
assert.equal(userInfo2_after.credit, "2101173516585172447");
assert.equal(userInfo3_after.stakingPower, "17561628007684555250");
assert.equal(userInfo3_after.superiorSP, "1756162800768455524");
assert.equal(userInfo3_after.credit, "0");
let [alphaEnd, lastRewardBlockEnd, totalSuppyEnd] = await getGlobalState(ctx, "end");
assert.equal(alphaEnd, "1220687915230005885");
assert.equal(totalSuppyEnd, "550000000000000000");
assert.equal(lastRewardBlockEnd, Number(lastRewardBlock) + 2);
});
it("transferFrom-vdodo", async () => {
await ctx.VDODO.methods.mint(decimalStr("10"), dodoTeam).send(ctx.sendParam(account0))
await ctx.VDODO.methods.mint(decimalStr("10"), dodoTeam).send(ctx.sendParam(account1))
//增加一个区块
await ctx.mintTestToken(account0, decimalStr("0"));
let [alpha, lastRewardBlock,] = await getGlobalState(ctx, "after");
assert.equal(alpha, "1138339920948616600");
var totalSuppy = await ctx.VDODO.methods.totalSupply().call();
assert.equal(totalSuppy, "320000000000000000");
let userInfo0 = await getUserInfo(ctx, account0, "User0 ");
assert.equal(userInfo0.stakingPower, decimalStr("10"));
assert.equal(userInfo0.superiorSP, decimalStr("1"));
assert.equal(userInfo0.credit, "0");
let userInfo1 = await getUserInfo(ctx, account1, "User1 ")
assert.equal(userInfo1.stakingPower, "9166666666666666667");
assert.equal(userInfo1.superiorSP, "916666666666666666");
assert.equal(userInfo1.credit, decimalStr("0"));
let [, dodo_u0] = await dodoBalance(ctx, account0, "start")
assert.equal(dodo_u0, "990000000000000000000");
let [, dodo_u1] = await dodoBalance(ctx, account1, "start")
assert.equal(dodo_u1, "990000000000000000000");
let account0Balance = await ctx.VDODO.methods.balanceOf(account0).call()
await logGas(await ctx.VDODO.methods.approve(
account2,
account0Balance
), ctx.sendParam(account0), "approve");
await logGas(await ctx.VDODO.methods.transferFrom(
account0,
account1,
account0Balance
), ctx.sendParam(account2), "transferFrom");
let userInfo0_after = await getUserInfo(ctx, account0, "userInfo0_after");
let userInfo1_after = await getUserInfo(ctx, account1, "userInfo1_after");
let userInfo2_after = await getUserInfo(ctx, account2, "userInfo2_after");
assert.equal(userInfo0_after.stakingPower, "769230769230769236");
assert.equal(userInfo0_after.superiorSP, "76923076923076924");
assert.equal(userInfo0_after.credit, "0");
assert.equal(userInfo1_after.stakingPower, "18397435897435897431");
assert.equal(userInfo1_after.superiorSP, "1839743589743589742");
assert.equal(userInfo1_after.credit, "0");
assert.equal(userInfo2_after.stakingPower, "0");
assert.equal(userInfo2_after.superiorSP, "0");
assert.equal(userInfo2_after.credit, "0");
let [alphaEnd, lastRewardBlockEnd, totalSuppyEnd] = await getGlobalState(ctx, "end");
assert.equal(alphaEnd, "1233201581027667984");
assert.equal(totalSuppyEnd, "340000000000000000");
assert.equal(lastRewardBlockEnd, Number(lastRewardBlock) + 3);
//再次transferFrom 预期revert
//预期revert
await truffleAssert.reverts(
ctx.VDODO.methods.transferFrom(account0, account1, 1).send(ctx.sendParam(account2)),
"ALLOWANCE_NOT_ENOUGH"
)
});
it("transfer - close", async () => {
await ctx.VDODO.methods.setCantransfer(false).send(ctx.sendParam(owner))
await ctx.VDODO.methods.mint(decimalStr("10"), dodoTeam).send(ctx.sendParam(account0))
assert.equal(
await ctx.DODO.methods.balanceOf(account0).call(),
decimalStr("990")
);
assert.equal(
await ctx.DODO.methods.balanceOf(ctx.VDODO.options.address).call(),
decimalStr("10010")
);
assert.equal(
await ctx.VDODO.methods.balanceOf(account0).call(),
decimalStr("0.1")
);
assert.equal(
await ctx.VDODO.methods.balanceOf(dodoTeam).call(),
decimalStr("0")
);
//预期revert
await truffleAssert.reverts(
ctx.VDODO.methods.transfer(account1, 1).send(ctx.sendParam(account0)),
"vDODOToken: not allowed transfer"
)
//revert 触发产生区块,造成vdodo增加
assert.equal(
await ctx.VDODO.methods.balanceOf(account0).call(),
"109090909090909090"
);
assert.equal(
await ctx.VDODO.methods.balanceOf(account1).call(),
decimalStr("0")
);
});
})
}); | the_stack |
export * from './account';
export * from './accountEvent';
export * from './accountHolderDetails';
export * from './accountHolderStatus';
export * from './accountPayoutState';
export * from './accountProcessingState';
export * from './amount';
export * from './bankAccountDetail';
export * from './businessDetails';
export * from './closeAccountHolderRequest';
export * from './closeAccountHolderResponse';
export * from './closeAccountRequest';
export * from './closeAccountResponse';
export * from './createAccountHolderRequest';
export * from './createAccountHolderResponse';
export * from './createAccountRequest';
export * from './createAccountResponse';
export * from './deleteBankAccountRequest';
export * from './deletePayoutMethodRequest';
export * from './deleteShareholderRequest';
export * from './deleteSignatoriesRequest';
export * from './documentDetail';
export * from './errorFieldType';
export * from './fieldType';
export * from './genericResponse';
export * from './getAccountHolderRequest';
export * from './getAccountHolderResponse';
export * from './getAccountHolderStatusResponse';
export * from './getTaxFormRequest';
export * from './getTaxFormResponse';
export * from './getUploadedDocumentsRequest';
export * from './getUploadedDocumentsResponse';
export * from './individualDetails';
export * from './kYCCheckResult2';
export * from './kYCCheckStatusData';
export * from './kYCCheckSummary';
export * from './kYCLegalArrangementCheckResult';
export * from './kYCLegalArrangementEntityCheckResult';
export * from './kYCPayoutMethodCheckResult';
export * from './kYCShareholderCheckResult';
export * from './kYCSignatoryCheckResult';
export * from './kYCVerificationResult2';
export * from './legalArrangementDetail';
export * from './legalArrangementEntityDetail';
export * from './payoutMethod';
export * from './payoutScheduleResponse';
export * from './performVerificationRequest';
export * from './personalDocumentData';
export * from './serviceError';
export * from './shareholderContact';
export * from './signatoryContact';
export * from './storeDetail';
export * from './suspendAccountHolderRequest';
export * from './suspendAccountHolderResponse';
export * from './unSuspendAccountHolderRequest';
export * from './unSuspendAccountHolderResponse';
export * from './updateAccountHolderRequest';
export * from './updateAccountHolderResponse';
export * from './updateAccountHolderStateRequest';
export * from './updateAccountRequest';
export * from './updateAccountResponse';
export * from './updatePayoutScheduleRequest';
export * from './uploadDocumentRequest';
export * from './viasAddress';
export * from './viasName';
export * from './viasPersonalData';
export * from './viasPhoneNumber';
import * as fs from 'fs';
import {Account} from './account';
import {AccountEvent} from './accountEvent';
import {AccountHolderDetails} from './accountHolderDetails';
import {AccountHolderStatus} from './accountHolderStatus';
import {AccountPayoutState} from './accountPayoutState';
import {AccountProcessingState} from './accountProcessingState';
import {Amount} from './amount';
import {BankAccountDetail} from './bankAccountDetail';
import {BusinessDetails} from './businessDetails';
import {CloseAccountHolderRequest} from './closeAccountHolderRequest';
import {CloseAccountHolderResponse} from './closeAccountHolderResponse';
import {CloseAccountRequest} from './closeAccountRequest';
import {CloseAccountResponse} from './closeAccountResponse';
import {CreateAccountHolderRequest} from './createAccountHolderRequest';
import {CreateAccountHolderResponse} from './createAccountHolderResponse';
import {CreateAccountRequest} from './createAccountRequest';
import {CreateAccountResponse} from './createAccountResponse';
import {DeleteBankAccountRequest} from './deleteBankAccountRequest';
import {DeletePayoutMethodRequest} from './deletePayoutMethodRequest';
import {DeleteShareholderRequest} from './deleteShareholderRequest';
import {DeleteSignatoriesRequest} from './deleteSignatoriesRequest';
import {DocumentDetail} from './documentDetail';
import {ErrorFieldType} from './errorFieldType';
import {FieldType} from './fieldType';
import {GenericResponse} from './genericResponse';
import {GetAccountHolderRequest} from './getAccountHolderRequest';
import {GetAccountHolderResponse} from './getAccountHolderResponse';
import {GetAccountHolderStatusResponse} from './getAccountHolderStatusResponse';
import {GetTaxFormRequest} from './getTaxFormRequest';
import {GetTaxFormResponse} from './getTaxFormResponse';
import {GetUploadedDocumentsRequest} from './getUploadedDocumentsRequest';
import {GetUploadedDocumentsResponse} from './getUploadedDocumentsResponse';
import {IndividualDetails} from './individualDetails';
import {KYCCheckResult2} from './kYCCheckResult2';
import {KYCCheckStatusData} from './kYCCheckStatusData';
import {KYCCheckSummary} from './kYCCheckSummary';
import {KYCLegalArrangementCheckResult} from './kYCLegalArrangementCheckResult';
import {KYCLegalArrangementEntityCheckResult} from './kYCLegalArrangementEntityCheckResult';
import {KYCPayoutMethodCheckResult} from './kYCPayoutMethodCheckResult';
import {KYCShareholderCheckResult} from './kYCShareholderCheckResult';
import {KYCSignatoryCheckResult} from './kYCSignatoryCheckResult';
import {KYCVerificationResult2} from './kYCVerificationResult2';
import {LegalArrangementDetail} from './legalArrangementDetail';
import {LegalArrangementEntityDetail} from './legalArrangementEntityDetail';
import {PayoutMethod} from './payoutMethod';
import {PayoutScheduleResponse} from './payoutScheduleResponse';
import {PerformVerificationRequest} from './performVerificationRequest';
import {PersonalDocumentData} from './personalDocumentData';
import {ServiceError} from './serviceError';
import {ShareholderContact} from './shareholderContact';
import {SignatoryContact} from './signatoryContact';
import {StoreDetail} from './storeDetail';
import {SuspendAccountHolderRequest} from './suspendAccountHolderRequest';
import {SuspendAccountHolderResponse} from './suspendAccountHolderResponse';
import {UnSuspendAccountHolderRequest} from './unSuspendAccountHolderRequest';
import {UnSuspendAccountHolderResponse} from './unSuspendAccountHolderResponse';
import {UpdateAccountHolderRequest} from './updateAccountHolderRequest';
import {UpdateAccountHolderResponse} from './updateAccountHolderResponse';
import {UpdateAccountHolderStateRequest} from './updateAccountHolderStateRequest';
import {UpdateAccountRequest} from './updateAccountRequest';
import {UpdateAccountResponse} from './updateAccountResponse';
import {UpdatePayoutScheduleRequest} from './updatePayoutScheduleRequest';
import {UploadDocumentRequest} from './uploadDocumentRequest';
import {ViasAddress} from './viasAddress';
import {ViasName} from './viasName';
import {ViasPersonalData} from './viasPersonalData';
import {ViasPhoneNumber} from './viasPhoneNumber';
export interface RequestDetailedFile {
value: Buffer;
options?: {
filename?: string;
contentType?: string;
}
}
export type RequestFile = string | Buffer | fs.ReadStream | RequestDetailedFile;
/* tslint:disable:no-unused-variable */
let primitives = [
"string",
"boolean",
"double",
"integer",
"long",
"float",
"number",
"any"
];
let enumsMap: {[index: string]: any} = {
"Account.PayoutSpeedEnum": Account.PayoutSpeedEnum,
"AccountEvent.EventEnum": AccountEvent.EventEnum,
"AccountHolderStatus.StatusEnum": AccountHolderStatus.StatusEnum,
"CloseAccountResponse.StatusEnum": CloseAccountResponse.StatusEnum,
"CreateAccountHolderRequest.LegalEntityEnum": CreateAccountHolderRequest.LegalEntityEnum,
"CreateAccountHolderResponse.LegalEntityEnum": CreateAccountHolderResponse.LegalEntityEnum,
"CreateAccountRequest.PayoutScheduleEnum": CreateAccountRequest.PayoutScheduleEnum,
"CreateAccountRequest.PayoutSpeedEnum": CreateAccountRequest.PayoutSpeedEnum,
"CreateAccountResponse.PayoutSpeedEnum": CreateAccountResponse.PayoutSpeedEnum,
"CreateAccountResponse.StatusEnum": CreateAccountResponse.StatusEnum,
"DocumentDetail.DocumentTypeEnum": DocumentDetail.DocumentTypeEnum,
"FieldType.FieldNameEnum": FieldType.FieldNameEnum,
"GetAccountHolderResponse.LegalEntityEnum": GetAccountHolderResponse.LegalEntityEnum,
"KYCCheckStatusData.StatusEnum": KYCCheckStatusData.StatusEnum,
"KYCCheckStatusData.TypeEnum": KYCCheckStatusData.TypeEnum,
"LegalArrangementDetail.LegalFormEnum": LegalArrangementDetail.LegalFormEnum,
"LegalArrangementDetail.TypeEnum": LegalArrangementDetail.TypeEnum,
"LegalArrangementEntityDetail.LegalArrangementMemberEnum": LegalArrangementEntityDetail.LegalArrangementMemberEnum,
"LegalArrangementEntityDetail.LegalEntityTypeEnum": LegalArrangementEntityDetail.LegalEntityTypeEnum,
"PayoutMethod.PayoutMethodTypeEnum": PayoutMethod.PayoutMethodTypeEnum,
"PayoutScheduleResponse.ScheduleEnum": PayoutScheduleResponse.ScheduleEnum,
"PerformVerificationRequest.AccountStateTypeEnum": PerformVerificationRequest.AccountStateTypeEnum,
"PersonalDocumentData.TypeEnum": PersonalDocumentData.TypeEnum,
"ShareholderContact.ShareholderTypeEnum": ShareholderContact.ShareholderTypeEnum,
"StoreDetail.ShopperInteractionEnum": StoreDetail.ShopperInteractionEnum,
"StoreDetail.StatusEnum": StoreDetail.StatusEnum,
"UpdateAccountHolderRequest.LegalEntityEnum": UpdateAccountHolderRequest.LegalEntityEnum,
"UpdateAccountHolderResponse.LegalEntityEnum": UpdateAccountHolderResponse.LegalEntityEnum,
"UpdateAccountHolderStateRequest.StateTypeEnum": UpdateAccountHolderStateRequest.StateTypeEnum,
"UpdateAccountRequest.PayoutSpeedEnum": UpdateAccountRequest.PayoutSpeedEnum,
"UpdateAccountResponse.PayoutSpeedEnum": UpdateAccountResponse.PayoutSpeedEnum,
"UpdatePayoutScheduleRequest.ActionEnum": UpdatePayoutScheduleRequest.ActionEnum,
"UpdatePayoutScheduleRequest.ScheduleEnum": UpdatePayoutScheduleRequest.ScheduleEnum,
"ViasName.GenderEnum": ViasName.GenderEnum,
"ViasPhoneNumber.PhoneTypeEnum": ViasPhoneNumber.PhoneTypeEnum,
}
let typeMap: {[index: string]: any} = {
"Account": Account,
"AccountEvent": AccountEvent,
"AccountHolderDetails": AccountHolderDetails,
"AccountHolderStatus": AccountHolderStatus,
"AccountPayoutState": AccountPayoutState,
"AccountProcessingState": AccountProcessingState,
"Amount": Amount,
"BankAccountDetail": BankAccountDetail,
"BusinessDetails": BusinessDetails,
"CloseAccountHolderRequest": CloseAccountHolderRequest,
"CloseAccountHolderResponse": CloseAccountHolderResponse,
"CloseAccountRequest": CloseAccountRequest,
"CloseAccountResponse": CloseAccountResponse,
"CreateAccountHolderRequest": CreateAccountHolderRequest,
"CreateAccountHolderResponse": CreateAccountHolderResponse,
"CreateAccountRequest": CreateAccountRequest,
"CreateAccountResponse": CreateAccountResponse,
"DeleteBankAccountRequest": DeleteBankAccountRequest,
"DeletePayoutMethodRequest": DeletePayoutMethodRequest,
"DeleteShareholderRequest": DeleteShareholderRequest,
"DeleteSignatoriesRequest": DeleteSignatoriesRequest,
"DocumentDetail": DocumentDetail,
"ErrorFieldType": ErrorFieldType,
"FieldType": FieldType,
"GenericResponse": GenericResponse,
"GetAccountHolderRequest": GetAccountHolderRequest,
"GetAccountHolderResponse": GetAccountHolderResponse,
"GetAccountHolderStatusResponse": GetAccountHolderStatusResponse,
"GetTaxFormRequest": GetTaxFormRequest,
"GetTaxFormResponse": GetTaxFormResponse,
"GetUploadedDocumentsRequest": GetUploadedDocumentsRequest,
"GetUploadedDocumentsResponse": GetUploadedDocumentsResponse,
"IndividualDetails": IndividualDetails,
"KYCCheckResult2": KYCCheckResult2,
"KYCCheckStatusData": KYCCheckStatusData,
"KYCCheckSummary": KYCCheckSummary,
"KYCLegalArrangementCheckResult": KYCLegalArrangementCheckResult,
"KYCLegalArrangementEntityCheckResult": KYCLegalArrangementEntityCheckResult,
"KYCPayoutMethodCheckResult": KYCPayoutMethodCheckResult,
"KYCShareholderCheckResult": KYCShareholderCheckResult,
"KYCSignatoryCheckResult": KYCSignatoryCheckResult,
"KYCVerificationResult2": KYCVerificationResult2,
"LegalArrangementDetail": LegalArrangementDetail,
"LegalArrangementEntityDetail": LegalArrangementEntityDetail,
"PayoutMethod": PayoutMethod,
"PayoutScheduleResponse": PayoutScheduleResponse,
"PerformVerificationRequest": PerformVerificationRequest,
"PersonalDocumentData": PersonalDocumentData,
"ServiceError": ServiceError,
"ShareholderContact": ShareholderContact,
"SignatoryContact": SignatoryContact,
"StoreDetail": StoreDetail,
"SuspendAccountHolderRequest": SuspendAccountHolderRequest,
"SuspendAccountHolderResponse": SuspendAccountHolderResponse,
"UnSuspendAccountHolderRequest": UnSuspendAccountHolderRequest,
"UnSuspendAccountHolderResponse": UnSuspendAccountHolderResponse,
"UpdateAccountHolderRequest": UpdateAccountHolderRequest,
"UpdateAccountHolderResponse": UpdateAccountHolderResponse,
"UpdateAccountHolderStateRequest": UpdateAccountHolderStateRequest,
"UpdateAccountRequest": UpdateAccountRequest,
"UpdateAccountResponse": UpdateAccountResponse,
"UpdatePayoutScheduleRequest": UpdatePayoutScheduleRequest,
"UploadDocumentRequest": UploadDocumentRequest,
"ViasAddress": ViasAddress,
"ViasName": ViasName,
"ViasPersonalData": ViasPersonalData,
"ViasPhoneNumber": ViasPhoneNumber,
}
export class ObjectSerializer {
public static findCorrectType(data: any, expectedType: string) {
if (data == undefined) {
return expectedType;
} else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) {
return expectedType;
} else if (expectedType === "Date") {
return expectedType;
} else {
if (enumsMap[expectedType]) {
return expectedType;
}
if (!typeMap[expectedType]) {
return expectedType; // w/e we don't know the type
}
// Check the discriminator
let discriminatorProperty = typeMap[expectedType].discriminator;
if (discriminatorProperty == null) {
return expectedType; // the type does not have a discriminator. use it.
} else {
if (data[discriminatorProperty]) {
var discriminatorType = data[discriminatorProperty];
if(typeMap[discriminatorType]){
return discriminatorType; // use the type given in the discriminator
} else {
return expectedType; // discriminator did not map to a type
}
} else {
return expectedType; // discriminator was not present (or an empty string)
}
}
}
}
public static serialize(data: any, type: string) {
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index = 0; index < data.length; index++) {
let datum = data[index];
transformedData.push(ObjectSerializer.serialize(datum, subType));
}
return transformedData;
} else if (type === "Date") {
return data.toISOString();
} else {
if (enumsMap[type]) {
return data;
}
if (!typeMap[type]) { // in case we dont know the type
return data;
}
// Get the actual type of this object
type = this.findCorrectType(data, type);
// get the map for the correct type.
let attributeTypes = typeMap[type].getAttributeTypeMap();
let instance: {[index: string]: any} = {};
for (let index = 0; index < attributeTypes.length; index++) {
let attributeType = attributeTypes[index];
instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type);
}
return instance;
}
}
public static deserialize(data: any, type: string) {
// polymorphism may change the actual type.
type = ObjectSerializer.findCorrectType(data, type);
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index = 0; index < data.length; index++) {
let datum = data[index];
transformedData.push(ObjectSerializer.deserialize(datum, subType));
}
return transformedData;
} else if (type === "Date") {
return new Date(data);
} else {
if (enumsMap[type]) {// is Enum
return data;
}
if (!typeMap[type]) { // dont know the type
return data;
}
let instance = new typeMap[type]();
let attributeTypes = typeMap[type].getAttributeTypeMap();
for (let index = 0; index < attributeTypes.length; index++) {
let attributeType = attributeTypes[index];
instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type);
}
return instance;
}
}
} | the_stack |
import type {Mutable, Class} from "@swim/util";
import {Provider} from "@swim/component";
import {R2Box, Transform} from "@swim/math";
import type {Color} from "@swim/style";
import {
ViewEvent,
ViewMouseEvent,
ViewPointerEvent,
ViewEventHandler,
ViewContext,
ViewContextType,
ViewInit,
ViewFlags,
View,
} from "@swim/view";
import {SpriteService} from "../sprite/SpriteService";
import type {GraphicsRenderer} from "./GraphicsRenderer";
import type {GraphicsViewContext} from "./GraphicsViewContext";
import type {GraphicsViewObserver} from "./GraphicsViewObserver";
import type {CanvasContext} from "../canvas/CanvasContext";
import {CanvasView} from "../"; // forward import
/** @public */
export interface GraphicsViewEventMap {
"auxclick": MouseEvent;
"click": MouseEvent;
"contextmenu": MouseEvent;
"dblclick": MouseEvent;
"mousedown": MouseEvent;
"mouseenter": MouseEvent;
"mouseleave": MouseEvent;
"mousemove": MouseEvent;
"mouseout": MouseEvent;
"mouseover": MouseEvent;
"mouseup": MouseEvent;
"pointercancel": PointerEvent;
"pointerdown": PointerEvent;
"pointerenter": PointerEvent;
"pointerleave": PointerEvent;
"pointermove": PointerEvent;
"pointerout": PointerEvent;
"pointerover": PointerEvent;
"pointerup": PointerEvent;
"touchcancel": TouchEvent;
"touchend": TouchEvent;
"touchmove": TouchEvent;
"touchstart": TouchEvent;
"wheel": WheelEvent;
}
/** @public */
export interface GraphicsViewInit extends ViewInit {
hidden?: boolean;
}
/** @public */
export class GraphicsView extends View {
constructor() {
super();
this.ownViewFrame = null;
this.eventHandlers = null;
this.hoverSet = null;
}
override readonly observerType?: Class<GraphicsViewObserver>;
override readonly contextType?: Class<GraphicsViewContext>;
declare readonly renderer: GraphicsRenderer | null; // getter defined below to work around useDefineForClassFields lunacy
protected override needsProcess(processFlags: ViewFlags, viewContext: ViewContextType<this>): ViewFlags {
if ((this.flags & View.NeedsAnimate) === 0) {
processFlags &= ~View.NeedsAnimate;
}
return processFlags;
}
protected renderViewOutline(viewBox: R2Box, context: CanvasContext, outlineColor: Color, outlineWidth: number): void {
if (viewBox.isDefined()) {
// save
const contextLineWidth = context.lineWidth;
const contextStrokeStyle = context.strokeStyle;
context.beginPath();
context.moveTo(viewBox.xMin, viewBox.yMin);
context.lineTo(viewBox.xMin, viewBox.yMax);
context.lineTo(viewBox.xMax, viewBox.yMax);
context.lineTo(viewBox.xMax, viewBox.yMin);
context.closePath();
context.lineWidth = outlineWidth;
context.strokeStyle = outlineColor.toString();
context.stroke();
// restore
context.lineWidth = contextLineWidth;
context.strokeStyle = contextStrokeStyle;
}
}
@Provider({
type: SpriteService,
observes: false,
service: SpriteService.global(),
})
readonly spriteProvider!: Provider<this, SpriteService>;
/** @internal */
readonly ownViewFrame: R2Box | null;
/**
* The parent-specified view-coordinate bounding box in which this view
* should layout and render graphics.
*/
get viewFrame(): R2Box {
let viewFrame = this.ownViewFrame;
if (viewFrame === null) {
viewFrame = this.deriveViewFrame();
}
return viewFrame;
}
/**
* Sets the view-coordinate bounding box in which this view should layout
* and render graphics. Should only be invoked by the view's parent view.
*/
setViewFrame(viewFrame: R2Box | null): void {
(this as Mutable<this>).ownViewFrame = viewFrame;
}
protected deriveViewFrame(): R2Box {
const parent = this.parent;
if (parent instanceof GraphicsView || parent instanceof CanvasView) {
return parent.viewFrame;
} else {
return R2Box.undefined();
}
}
cullViewFrame(viewFrame: R2Box = this.viewFrame): void {
this.setCulled(!viewFrame.intersects(this.viewBounds));
}
/**
* The self-defined view-coordinate bounding box surrounding all graphics
* this view could possibly render. Views with view bounds that don't
* overlap their view frames may be culled from rendering and hit testing.
*/
declare readonly viewBounds: R2Box; // getter defined below to work around useDefineForClassFields lunacy
get ownViewBounds(): R2Box | null {
return null;
}
deriveViewBounds(): R2Box {
let viewBounds: R2Box | undefined;
let child = this.firstChild;
while (child !== null) {
if (child instanceof GraphicsView && !child.hidden && !child.unbounded) {
const childViewBounds = child.viewBounds;
if (childViewBounds.isDefined()) {
if (viewBounds !== void 0) {
viewBounds = viewBounds.union(childViewBounds);
} else {
viewBounds = childViewBounds;
}
}
}
child = child.nextSibling;
}
if (viewBounds === void 0) {
viewBounds = this.viewFrame;
}
return viewBounds;
}
/**
* The self-defined view-coordinate bounding box surrounding all hit regions
* in this view.
*/
get hitBounds(): R2Box {
return this.viewBounds;
}
deriveHitBounds(): R2Box {
let hitBounds: R2Box | undefined;
let child = this.firstChild;
while (child !== null) {
if (child instanceof GraphicsView && !child.hidden && !child.intangible) {
const childHitBounds = child.hitBounds;
if (hitBounds === void 0) {
hitBounds = childHitBounds;
} else {
hitBounds = hitBounds.union(childHitBounds);
}
}
child = child.nextSibling;
}
if (hitBounds === void 0) {
hitBounds = this.viewBounds;
}
return hitBounds;
}
cascadeHitTest(x: number, y: number, baseViewContext: ViewContext): GraphicsView | null {
if (!this.hidden && !this.culled && !this.intangible) {
const hitBounds = this.hitBounds;
if (hitBounds.contains(x, y)) {
const viewContext = this.extendViewContext(baseViewContext);
let hit = this.hitTestChildren(x, y, viewContext);
if (hit === null) {
const outerViewContext = ViewContext.current;
try {
ViewContext.current = viewContext;
this.setFlags(this.flags | View.ContextualFlag);
hit = this.hitTest(x, y, viewContext);
} finally {
this.setFlags(this.flags & ~View.ContextualFlag);
ViewContext.current = outerViewContext;
}
}
return hit;
}
}
return null;
}
protected hitTest(x: number, y: number, viewContext: ViewContextType<this>): GraphicsView | null {
return null;
}
protected hitTestChildren(x: number, y: number, viewContext: ViewContextType<this>): GraphicsView | null {
let child = this.firstChild;
while (child !== null) {
if (child instanceof GraphicsView) {
const hit = this.hitTestChild(child, x, y, viewContext);
if (hit !== null) {
return hit;
}
}
child = child.nextSibling;
}
return null;
}
protected hitTestChild(child: GraphicsView, x: number, y: number,
viewContext: ViewContextType<this>): GraphicsView | null {
return child.cascadeHitTest(x, y, viewContext);
}
override get parentTransform(): Transform {
return Transform.identity();
}
override get clientBounds(): R2Box {
const inverseClientTransform = this.clientTransform.inverse();
return this.viewBounds.transform(inverseClientTransform);
}
override get popoverFrame(): R2Box {
const inversePageTransform = this.pageTransform.inverse();
return this.viewBounds.transform(inversePageTransform);
}
/** @internal */
readonly eventHandlers: {[type: string]: ViewEventHandler[] | undefined} | null;
override on<K extends keyof GraphicsViewEventMap>(type: K, listener: (this: this, event: GraphicsViewEventMap[K]) => unknown,
options?: AddEventListenerOptions | boolean): this;
override on(type: string, listener: EventListenerOrEventListenerObject, options?: AddEventListenerOptions | boolean): this;
override on(type: string, listener: EventListenerOrEventListenerObject, options?: AddEventListenerOptions | boolean): this {
let eventHandlers = this.eventHandlers;
if (eventHandlers === null) {
eventHandlers = {};
(this as Mutable<this>).eventHandlers = eventHandlers;
}
let handlers = eventHandlers[type];
const capture = typeof options === "boolean" ? options
: typeof options === "object" && options !== null && options.capture || false;
const passive = options && typeof options === "object" && options.passive || false;
const once = options && typeof options === "object" && options.once || false;
let handler: ViewEventHandler | undefined;
if (handlers === void 0) {
handler = {listener, capture, passive, once};
handlers = [handler];
eventHandlers[type] = handlers;
} else {
const n = handlers.length;
let i = 0;
while (i < n) {
handler = handlers[i]!;
if (handler.listener === listener && handler.capture === capture) {
break;
}
i += 1;
}
if (i < n) {
handler!.passive = passive;
handler!.once = once;
} else {
handler = {listener, capture, passive, once};
handlers.push(handler);
}
}
return this;
}
override off<K extends keyof GraphicsViewEventMap>(type: K, listener: (this: View, event: GraphicsViewEventMap[K]) => unknown,
options?: EventListenerOptions | boolean): this;
override off(type: string, listener: EventListenerOrEventListenerObject, options?: EventListenerOptions | boolean): this;
override off(type: string, listener: EventListenerOrEventListenerObject, options?: EventListenerOptions | boolean): this {
const eventHandlers = this.eventHandlers;
if (eventHandlers !== null) {
const handlers = eventHandlers[type];
if (handlers !== void 0) {
const capture = typeof options === "boolean" ? options
: typeof options === "object" && options !== null && options.capture || false;
const n = handlers.length;
let i = 0;
while (i < n) {
const handler = handlers[i]!;
if (handler.listener === listener && handler.capture === capture) {
handlers.splice(i, 1);
if (handlers.length === 0) {
delete eventHandlers[type];
}
break;
}
i += 1;
}
}
}
return this;
}
/** @internal */
handleEvent(event: ViewEvent): void {
const type = event.type;
const eventHandlers = this.eventHandlers;
if (eventHandlers !== null) {
const handlers = eventHandlers[type];
if (handlers !== void 0) {
let i = 0;
while (i < handlers.length) {
const handler = handlers[i]!;
if (!handler.capture) {
const listener = handler.listener;
if (typeof listener === "function") {
listener.call(this, event);
} else if (typeof listener === "object" && listener !== null) {
listener.handleEvent(event);
}
if (handler.once) {
handlers.splice(i, 1);
continue;
}
}
i += 1;
}
if (handlers.length === 0) {
delete eventHandlers[type];
}
}
}
if (type === "mouseover") {
this.onMouseOver(event as ViewMouseEvent);
} else if (type === "mouseout") {
this.onMouseOut(event as ViewMouseEvent);
} else if (type === "pointerover") {
this.onPointerOver(event as ViewPointerEvent);
} else if (type === "pointerout") {
this.onPointerOut(event as ViewPointerEvent);
}
}
/**
* Invokes event handlers registered with this `View` before propagating the
* `event` up the view hierarchy. Returns a `View`, without invoking any
* registered event handlers, on which `dispatchEvent` should be called to
* continue event propagation.
* @internal
*/
bubbleEvent(event: ViewEvent): View | null {
this.handleEvent(event);
let next: View | null;
if (event.bubbles && !event.cancelBubble) {
const parent = this.parent;
if (parent instanceof GraphicsView || parent instanceof CanvasView) {
next = parent.bubbleEvent(event);
} else {
next = parent;
}
} else {
next = null;
}
return next;
}
override dispatchEvent(event: ViewEvent): boolean {
event.targetView = this;
const next = this.bubbleEvent(event);
if (next !== null) {
return next.dispatchEvent(event);
} else {
return !event.cancelBubble;
}
}
/** @internal */
readonly hoverSet: {[id: string]: null | undefined} | null;
isHovering(): boolean {
const hoverSet = this.hoverSet;
return hoverSet !== null && Object.keys(hoverSet).length !== 0;
}
/** @internal */
protected onMouseOver(event: ViewMouseEvent): void {
let hoverSet = this.hoverSet;
if (hoverSet === null) {
hoverSet = {};
(this as Mutable<this>).hoverSet = hoverSet;
}
if (hoverSet.mouse === void 0) {
hoverSet.mouse = null;
const eventHandlers = this.eventHandlers;
if (eventHandlers !== null && eventHandlers.mouseenter !== void 0) {
const enterEvent = new MouseEvent("mouseenter", {
bubbles: false,
button: event.button,
buttons: event.buttons,
altKey: event.altKey,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
shiftKey: event.shiftKey,
clientX: event.clientX,
clientY: event.clientY,
screenX: event.screenX,
screenY: event.screenY,
movementX: event.movementX,
movementY: event.movementY,
view: event.view,
detail: event.detail,
relatedTarget: event.relatedTarget,
}) as ViewMouseEvent;
enterEvent.targetView = this;
enterEvent.relatedTargetView = event.relatedTargetView;
this.handleEvent(enterEvent);
}
}
}
/** @internal */
protected onMouseOut(event: ViewMouseEvent): void {
const hoverSet = this.hoverSet;
if (hoverSet !== null && hoverSet.mouse !== void 0) {
delete hoverSet.mouse;
const eventHandlers = this.eventHandlers;
if (eventHandlers !== null && eventHandlers.mouseleave !== void 0) {
const leaveEvent = new MouseEvent("mouseleave", {
bubbles: false,
button: event.button,
buttons: event.buttons,
altKey: event.altKey,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
shiftKey: event.shiftKey,
clientX: event.clientX,
clientY: event.clientY,
screenX: event.screenX,
screenY: event.screenY,
movementX: event.movementX,
movementY: event.movementY,
view: event.view,
detail: event.detail,
relatedTarget: event.relatedTarget,
}) as ViewMouseEvent;
leaveEvent.targetView = this;
leaveEvent.relatedTargetView = event.relatedTargetView;
this.handleEvent(leaveEvent);
}
}
}
/** @internal */
protected onPointerOver(event: ViewPointerEvent): void {
let hoverSet = this.hoverSet;
if (hoverSet === null) {
hoverSet = {};
(this as Mutable<this>).hoverSet = hoverSet;
}
const id = "" + event.pointerId;
if (hoverSet[id] === void 0) {
hoverSet[id] = null;
const eventHandlers = this.eventHandlers;
if (eventHandlers !== null && eventHandlers.pointerenter !== void 0) {
const enterEvent = new PointerEvent("pointerenter", {
bubbles: false,
pointerId: event.pointerId,
pointerType: event.pointerType,
isPrimary: event.isPrimary,
button: event.button,
buttons: event.buttons,
altKey: event.altKey,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
shiftKey: event.shiftKey,
clientX: event.clientX,
clientY: event.clientY,
screenX: event.screenX,
screenY: event.screenY,
movementX: event.movementX,
movementY: event.movementY,
tiltX: event.tiltX,
tiltY: event.tiltY,
twist: event.twist,
width: event.width,
height: event.height,
pressure: event.pressure,
tangentialPressure: event.tangentialPressure,
view: event.view,
detail: event.detail,
relatedTarget: event.relatedTarget,
}) as ViewPointerEvent;
enterEvent.targetView = this;
enterEvent.relatedTargetView = event.relatedTargetView;
this.handleEvent(enterEvent);
}
}
}
/** @internal */
protected onPointerOut(event: ViewPointerEvent): void {
const hoverSet = this.hoverSet;
if (hoverSet !== null) {
const id = "" + event.pointerId;
if (hoverSet[id] !== void 0) {
delete hoverSet[id];
const eventHandlers = this.eventHandlers;
if (eventHandlers !== null && eventHandlers.pointerleave !== void 0) {
const leaveEvent = new PointerEvent("pointerleave", {
bubbles: false,
pointerId: event.pointerId,
pointerType: event.pointerType,
isPrimary: event.isPrimary,
button: event.button,
buttons: event.buttons,
altKey: event.altKey,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
shiftKey: event.shiftKey,
clientX: event.clientX,
clientY: event.clientY,
screenX: event.screenX,
screenY: event.screenY,
movementX: event.movementX,
movementY: event.movementY,
tiltX: event.tiltX,
tiltY: event.tiltY,
twist: event.twist,
width: event.width,
height: event.height,
pressure: event.pressure,
tangentialPressure: event.tangentialPressure,
view: event.view,
detail: event.detail,
relatedTarget: event.relatedTarget,
}) as ViewPointerEvent;
leaveEvent.targetView = this;
leaveEvent.relatedTargetView = event.relatedTargetView;
this.handleEvent(leaveEvent);
}
}
}
}
override init(init: GraphicsViewInit): void {
super.init(init);
if (init.hidden !== void 0) {
this.setHidden(init.hidden);
}
}
static override readonly UncullFlags: ViewFlags = View.UncullFlags | View.NeedsRender;
static override readonly UnhideFlags: ViewFlags = View.UnhideFlags | View.NeedsRender;
static override readonly InsertChildFlags: ViewFlags = View.InsertChildFlags | View.NeedsRender;
static override readonly RemoveChildFlags: ViewFlags = View.RemoveChildFlags | View.NeedsRender;
}
Object.defineProperty(GraphicsView.prototype, "renderer", {
get(this: GraphicsView): GraphicsRenderer | null {
const parent = this.parent;
if (parent instanceof GraphicsView || parent instanceof CanvasView) {
return parent.renderer;
} else {
return null;
}
},
configurable: true,
});
Object.defineProperty(GraphicsView.prototype, "viewBounds", {
get(this: GraphicsView): R2Box {
return this.viewFrame;
},
configurable: true,
}); | the_stack |
import BTreeNode from './b-tree-node'
import * as utils from '../../utils'
class BTree<T> {
root: BTreeNode<T> | null
// The branching factor of the BTree. B <= # of Children per node <= 2B
private B: number
private maxValues: number
private maxChildren: number
private h: number
private sz: number
private compare: utils.CompareFunction<T> // comparison function if generic type T isn't primitive
constructor(B: number, compareFunction?: utils.CompareFunction<T>) {
if (B < 2) throw new Error('Branching factor must be greater than or equal to 2.')
this.root = null
this.B = B
this.maxValues = this.B * 2 - 1 // maxChildren = 2B ==> maxValues = 2B - 1
this.maxChildren = this.B * 2
this.sz = 0
this.h = 0
this.compare = compareFunction || utils.defaultCompare
}
/*****************************************************************************
INSPECTION
*****************************************************************************/
/**
* Returns the number of nodes in the tree - O(1)
* @return {number}
*/
size(): number {
return this.sz
}
/**
* Returns true if the B-tree is empty, and false otherwise - O(1)
* @return {boolean}
*/
isEmpty(): boolean {
return this.size() === 0
}
/**
* Returns the height of the tree - O(1)
* @return {number}
*/
height(): number {
return this.h
}
/*****************************************************************************
SEARCHING
*****************************************************************************/
/**
* Returns a [BTreeNode, number] pair, where number is the index of the value in the node. If the
* value doesn't exist in the tree, the return type is null.
* @param {T} value
* @return {[BTreeNode<T>, number] | null}
*/
find(value: T): [BTreeNode<T>, number] | null {
if (!this.root) return null
return this.findHelper(this.root, value)
}
private findHelper(root: BTreeNode<T>, k: T): [BTreeNode<T>, number] | null {
const values = root.values
let i = values.length - 1
if (k > values[i]) {
i += 1
} else {
// use linear search to find the smallest index such that value <= root.values[i]
while (i > 0 && this.compare(k, values[i]) < 0) {
i -= 1
}
if (k > values[i]) i += 1
}
// if our index, i, is not out of bounds and we indeed have root.values[i] === value then return the value found
if (i < values.length && this.compare(values[i], k) === 0) {
return [root, i]
} else if (root.isLeaf) {
// otherwise, there was no match in this node
// but root.isLeaf ==> we reached bottom of tree, so value is not in our tree
// so we return null
return null
} else {
// otherwise, there was no match in this node BUT we still have subtree to search
// hope is not lost! let us recurse.
return this.findHelper(root.children[i], k)
}
}
/*****************************************************************************
INSERTION/DELETION
*****************************************************************************/
/**
* Inserts value into tree - O(logn)
* @param {T} value
* @return {void}
*/
insert(value: T): void {
// Like BSTs, we trace a path down the tree until we find a leaf in which to insert the new key
// However, we can't create a new leaf node. The resulting tree would not be a B-tree since all
// leaves must be at the same level. Creating a new leaf would create a new level.
// Splitting the root is the only way to increase the height of a B-tree.
// Unlike the BST, a B-tree increases height at the top, not the bottom.
// insertNotFull() recurses as necessary down the tree, at all times guaranteeing
// that the node to which it recurses is not full by calling splitChild as necessary
// if root is full, split it before recursing
if (this.root && this.root.values.length === this.maxValues) {
// create new root node
const newRoot = new BTreeNode<T>()
newRoot.isLeaf = false
newRoot.children.push(this.root)
this.root = newRoot
// split newRoot, which promotes median value of root into newRoot
this.splitChild(newRoot, 0)
this.h += 1
// then proceed with the insert
this.insertHelper(newRoot, value)
// otherwise, root is not full
// if root exists then...
} else if (this.root) {
// perform an insert
this.insertHelper(this.root, value)
// otherwise root doesn't exist
} else {
// so create a new node
this.root = new BTreeNode<T>()
this.root.isLeaf = true
this.root.values.push(value)
// increment the height
this.h += 1
}
this.sz += 1
}
// Assumes root is not full. This invariant is needed because if we insert our value into
// root, we can't have it overflow.
private insertHelper(root: BTreeNode<T>, value: T) {
// if root is leaf
if (root.isLeaf) {
let i = root.values.length - 1
if (this.compare(value, root.values[i]) > 0) {
// insert at end
root.values.splice(i + 1, 0, value)
} else {
// insert in middle
while (i > 0 && this.compare(value, root.values[i]) < 0) {
i -= 1
}
if (value > root.values[i]) i += 1
root.values.splice(i, 0, value)
}
} else {
// root is not leaf, so find correct child to recurse into
let i = root.values.length - 1
while (i >= 0 && this.compare(value, root.values[i]) < 0) {
i -= 1
}
i += 1
// if the node we are about to recurse in is full, split it first
// this maintains the invariant that we don't recurse to a full node, and hence overflow it
// if insertion occurs
if (root.children[i].values.length === this.maxValues) {
this.splitChild(root, i)
if (value > root.values[i]) i += 1
}
this.insertHelper(root.children[i], value)
}
}
// Takes a nonfull internal node, (call it x), and an index, i, where
// x.children[i] is a full child. The method splits the child, y into two (y and z)
// and promotes the median value in the child up to the x. The length of y and z
// children will now go from 2B to B
private splitChild(x: BTreeNode<T>, i: number) {
const y = x.children[i]
const medianValue = y.values[this.B - 1]
const z = new BTreeNode<T>()
z.isLeaf = y.isLeaf // if y is a leaf, so is z
// copy paste the second half of y's values into z in O(B) time
const firstValueAfterMiddle = this.B
for (let j = firstValueAfterMiddle; j < this.maxValues; j++) {
z.values.push(y.values[j])
}
// if y is not a leaf, copy paste the second half of y's children into z in O(B) time
if (!y.isLeaf) {
const firstChildOfSecondHalf = this.B
for (let j = firstChildOfSecondHalf; j < this.maxChildren; j++) {
z.children.push(y.children[j])
}
}
// cut the second half of y's values and children
y.values.length = this.B - 1
if (!y.isLeaf) y.children.length = this.B
// now insert z into x's children
// z belongs at i+1 because y is at i (the original child)
x.children.splice(i + 1, 0, z) // O(B)
// now promote the middle element of old y up to x
x.values.splice(i, 0, medianValue) // O(B)
}
/**
* Deletes node with supplied value, if it exists - O(logn)
* @param {T} value
* @return {void}
*/
remove(value: T): void {
if (!this.root) return
this.removeNode(this.root, value)
if (this.root.values.length === 0) {
this.root = this.root.children[0]
this.h -= 1
}
}
// Deletion is analagous to insertion but a bit more complicated. We can delete
// from any node, not just a leaf. During insertion, we had to ensure nodes
// did not overflow before recursing. In deletion, we have to ensure nodes
// don't underflow before recursing.
private removeNode(x: BTreeNode<T>, k: T): void {
let i = x.values.length - 1
// if k is greater than the last value in x, i = x.values.length, so add
// 1 back to it
if (this.compare(k, x.values[i]) > 0) {
i += 1
} else {
while (i > 0 && this.compare(k, x.values[i]) < 0) {
i -= 1
}
}
const valueIsInX = i < x.values.length && x.values[i] === k
// case 1: value is in x, and x is leaf
// We can freely remove value from x since we don't have to worry about
// any children.
if (valueIsInX && x.isLeaf) {
x.values.splice(i, 1)
return
// case 2: value is in x but x is not leaf
// This means when we remove the value, we will have 1 extra child
} else if (valueIsInX && !x.isLeaf) {
const y = x.children[i]
const z = x.children[i + 1]
// x
// y z
// case 2a
// If y has at least B values, let k's predecessor which is in y
// be lifted up to x, and replace k. This is allowed because a node only
// needs minimum k-1 values, which y will have.
if (y.values.length >= this.B) {
// paste k's predecessor from y into x
x.values[i] = y.values[y.values.length - 1]
// delete k's predecessor from y
y.values.length -= 1
} else if (z.values.length >= this.B) {
// case 2b: y has B-1 values, so we cannot steal any from y, but z
// has at least B values, so we can steal k's sucessor from z.
// paste k's predecessor from z into x
x.values[i] = z.values[0]
// delete k's predecessor from z
z.values.splice(0, 1) // O(n) operation TODO: use tombstones to mark deleted values
} else {
// case 2c: both y and z don't have enough values to steal in order to replace k
// ==> len(y.values) = B - 1 = len(z.values) => y+z = 2B - 2
// notice that 2B - 2 < max values allowed = 2B.
// This gives us the idea of merging y and z into one child
// Now, when we delete k from x.values, k's left child and k's right child
// will merge into one.
// copy all of z values over into y, so y is now y + z (merged)
for (const value of z.values) {
y.values.push(value)
}
// delete k from x.values
x.values.splice(i, 1)
// delete z from x.children
x.children.splice(i + 1, 1)
}
}
// otherwise the value is not in x
// if x is a leaf, we can no longer search and recurse, so return
if (x.isLeaf) return
// case 3: x is not a leaf, so we are able to recurse, so lets recurse into x.children[i]
// before we recurse, if the child we recurse into has the minimum number of values (B-1) then...
if (x.children[i].values.length === this.B - 1) {
// execute step 3a or 3b to guaranteee it has B values. We need the node to have at least B values
// because if the deletion does so happen to occur at that child, we want to make sure it doesn't underflow.
// So in worst case the child will have B-1 values, which is OK. We do this with rotations.
// case 3a: right sibling has at least B values, do a rotate left on root value
const childHasRightSibling = i < x.children.length - 1
const rightSiblingHasValuesToGive = x.children[i + 1].values.length >= this.B
if (childHasRightSibling && rightSiblingHasValuesToGive) {
// left rotate on parent
x.children[i].values.push(x.values[i])
const firstValueOfRightSibling = x.children[i + 1].values.shift() // TODO: go from O(n) -> O(1) by using tombstones
if (firstValueOfRightSibling === undefined) throw new Error()
x.values[i] = firstValueOfRightSibling
}
const childHasLeftSibling = i > 0
const leftSiblingHasValuesToGive = x.children[i - 1].values.length >= this.B
// case 3a: left sibling has at least B values, do a rotate right on right value
if (childHasLeftSibling && leftSiblingHasValuesToGive) {
// right rotate on parent
x.children[i].values.push(x.values[i])
const lastValueOfLeftSibling = x.children[i + 1].values.pop()
if (lastValueOfLeftSibling === undefined) throw new Error()
x.values[i] = lastValueOfLeftSibling
}
// case 3b: left and right siblings don't have values to donate, so merge child we're going to
// recurse into with either sibling
if (childHasRightSibling) {
const child = x.children[i]
const rightSibling = x.children[i + 1]
// push parent down
child.values.push(x.values[i])
// copy over all values from rightSibling into the merging child
for (const value of rightSibling.values) {
child.values.push(value)
}
// delete parent from x.values since we pushed it down
x.values.splice(i, 1)
// delete rightSibling from x.children
x.children.splice(i + 1, 1)
} else {
// childHasLeftSibling
const child = x.children[i]
const leftSibling = x.children[i - 1]
// push parent down
child.values.push(x.values[i])
// copy over all values from leftSibling into the merging child
for (const value of leftSibling.values) {
child.values.push(value)
}
// delete parent from x.values since we pushed it down
x.values.splice(i, 1)
// delete leftSibling from x.children
x.children.splice(i - 1, 1)
}
}
this.removeNode(x.children[i], k)
}
}
export default BTree | the_stack |
import * as chai from 'chai'
import * as chaiAsPromised from 'chai-as-promised'
import 'mocha'
import { ExposedPromise, ExposedPromiseStatus } from '../../src/utils/exposed-promise'
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason)
})
// use chai-as-promised plugin
chai.use(chaiAsPromised)
const expect = chai.expect
const WAIT_TIME = 0
const cancelTimeoutAndSettle = (
timeout: NodeJS.Timeout,
settleFunction: (result?: any) => void
) => {
if (timeout) {
clearTimeout(timeout)
}
return settleFunction
}
const getExpectedPromiseOutcome = (
exposed: ExposedPromise<any, any>,
expectedStatus: ExposedPromiseStatus
) => {
const resolvePredicate = expectedStatus === ExposedPromiseStatus.RESOLVED
const rejectPredicate = expectedStatus === ExposedPromiseStatus.REJECTED
const finallyPredicate =
expectedStatus === ExposedPromiseStatus.RESOLVED ||
expectedStatus === ExposedPromiseStatus.REJECTED
const promises: Promise<any>[] = []
promises.push(
// Resolve
new Promise((resolve, reject) => {
exposed.promise
.then((result) => {
cancelTimeoutAndSettle(timeout, resolvePredicate ? resolve : reject)(result)
})
.catch(() => undefined)
const timeout = global.setTimeout(() => {
;(resolvePredicate ? reject : resolve)()
}, WAIT_TIME)
}).catch(() => undefined)
)
promises.push(
// Reject
new Promise((resolve, reject) => {
exposed.promise.catch((result) => {
cancelTimeoutAndSettle(timeout, rejectPredicate ? resolve : reject)(result)
})
const timeout = global.setTimeout(() => {
;(rejectPredicate ? reject : resolve)()
}, WAIT_TIME)
}).catch(() => undefined)
)
promises.push(
// Finally
new Promise((resolve, reject) => {
exposed.promise
.catch(() => undefined)
.finally(() => {
cancelTimeoutAndSettle(timeout, finallyPredicate ? resolve : reject)()
})
const timeout = global.setTimeout(() => {
;(finallyPredicate ? reject : resolve)()
}, WAIT_TIME)
}).catch(() => undefined)
)
return promises
}
describe(`ExposedPromise`, () => {
it(`should create an empty ExposedPromise`, async () => {
const exposed = new ExposedPromise()
const promises = getExpectedPromiseOutcome(exposed, ExposedPromiseStatus.PENDING)
expect(exposed instanceof ExposedPromise, 'is instanceof ExposedPromise').to.be.true
expect(exposed.isPending(), 'isPending').to.be.true
expect(exposed.isResolved(), 'isResolved').to.be.false
expect(exposed.isRejected(), 'isRejected').to.be.false
expect(exposed.isSettled(), 'isSettled').to.be.false
expect(typeof exposed.promise, 'promise').to.equal('object')
expect(exposed.promiseResult, 'promiseResult').to.be.undefined
expect(exposed.promiseError, 'promiseError').to.be.undefined
expect(exposed.status, 'status').to.equal(ExposedPromiseStatus.PENDING)
expect(typeof exposed.resolve, 'resolve').to.equal('function')
expect(typeof exposed.reject, 'reject').to.equal('function')
expect(await Promise.all(promises)).to.deep.equal([undefined, undefined, undefined])
})
it(`should correctly resolve an ExposedPromise`, async () => {
const exposed = new ExposedPromise()
const successMessage = 'success message!'
exposed.resolve(successMessage)
const promises = getExpectedPromiseOutcome(exposed, ExposedPromiseStatus.RESOLVED)
expect(exposed instanceof ExposedPromise, 'is instanceof ExposedPromise').to.be.true
expect(exposed.isPending(), 'isPending').to.be.false
expect(exposed.isResolved(), 'isResolved').to.be.true
expect(exposed.isRejected(), 'isRejected').to.be.false
expect(exposed.isSettled(), 'isSettled').to.be.true
expect(typeof exposed.promise, 'promise').to.equal('object')
expect(exposed.promiseResult, 'promiseResult').to.equal(successMessage)
expect(exposed.promiseError, 'promiseError').to.be.undefined
expect(exposed.status, 'status').to.equal(ExposedPromiseStatus.RESOLVED)
expect(typeof exposed.resolve, 'resolve').to.equal('function')
expect(typeof exposed.reject, 'reject').to.equal('function')
expect(await Promise.all(promises)).to.deep.equal(['success message!', undefined, undefined])
})
it(`should create a resolved ExposedPromise when calling the static resolve`, async () => {
const exposed = ExposedPromise.resolve()
const promises = getExpectedPromiseOutcome(exposed, ExposedPromiseStatus.RESOLVED)
expect(exposed instanceof ExposedPromise, 'is instanceof ExposedPromise').to.be.true
expect(exposed.isPending(), 'isPending').to.be.false
expect(exposed.isResolved(), 'isResolved').to.be.true
expect(exposed.isRejected(), 'isRejected').to.be.false
expect(exposed.isSettled(), 'isSettled').to.be.true
expect(typeof exposed.promise, 'promise').to.equal('object')
expect(exposed.promiseResult, 'promiseResult').to.be.undefined
expect(exposed.promiseError, 'promiseError').to.be.undefined
expect(exposed.status, 'status').to.equal(ExposedPromiseStatus.RESOLVED)
expect(typeof exposed.resolve, 'resolve').to.equal('function')
expect(typeof exposed.reject, 'reject').to.equal('function')
expect(await Promise.all(promises)).to.deep.equal([undefined, undefined, undefined])
})
it(`should create a resolved ExposedPromise when calling the static resolve with data`, async () => {
const successMessage = 'success message!'
const exposed = ExposedPromise.resolve(successMessage)
const promises = getExpectedPromiseOutcome(exposed, ExposedPromiseStatus.RESOLVED)
expect(exposed instanceof ExposedPromise, 'is instanceof ExposedPromise').to.be.true
expect(exposed.isPending(), 'isPending').to.be.false
expect(exposed.isResolved(), 'isResolved').to.be.true
expect(exposed.isRejected(), 'isRejected').to.be.false
expect(exposed.isSettled(), 'isSettled').to.be.true
expect(typeof exposed.promise, 'promise').to.equal('object')
expect(exposed.promiseResult, 'promiseResult').to.equal(successMessage)
expect(exposed.promiseError, 'promiseError').to.be.undefined
expect(exposed.status, 'status').to.equal(ExposedPromiseStatus.RESOLVED)
expect(typeof exposed.resolve, 'resolve').to.equal('function')
expect(typeof exposed.reject, 'reject').to.equal('function')
expect(await Promise.all(promises)).to.deep.equal(['success message!', undefined, undefined])
})
it(`should not change its state after it has been resolved`, async () => {
const exposed = new ExposedPromise()
const successMessage1 = 'success message!'
const successMessage2 = 'success message!'
exposed.resolve(successMessage1)
exposed.resolve(successMessage2)
const promises = getExpectedPromiseOutcome(exposed, ExposedPromiseStatus.RESOLVED)
expect(exposed instanceof ExposedPromise, 'is instanceof ExposedPromise').to.be.true
expect(exposed.isPending(), 'isPending').to.be.false
expect(exposed.isResolved(), 'isResolved').to.be.true
expect(exposed.isRejected(), 'isRejected').to.be.false
expect(exposed.isSettled(), 'isSettled').to.be.true
expect(typeof exposed.promise, 'promise').to.equal('object')
expect(exposed.promiseResult, 'promiseResult').to.equal(successMessage1)
expect(exposed.promiseError, 'promiseError').to.be.undefined
expect(exposed.status, 'status').to.equal(ExposedPromiseStatus.RESOLVED)
expect(typeof exposed.resolve, 'resolve').to.equal('function')
expect(typeof exposed.reject, 'reject').to.equal('function')
expect(await Promise.all(promises)).to.deep.equal(['success message!', undefined, undefined])
})
it(`should not resolve a promise in an ExposedPromise`, async () => {
const exposed = new ExposedPromise<Promise<string>>()
const successMessage = 'success message!'
exposed.resolve(Promise.resolve(successMessage))
const promises = getExpectedPromiseOutcome(exposed, ExposedPromiseStatus.RESOLVED)
expect(exposed instanceof ExposedPromise, 'is instanceof ExposedPromise').to.be.true
expect(exposed.isPending(), 'isPending').to.be.false
expect(exposed.isResolved(), 'isResolved').to.be.true
expect(exposed.isRejected(), 'isRejected').to.be.false
expect(exposed.isSettled(), 'isSettled').to.be.true
expect(typeof exposed.promise, 'promise').to.equal('object')
expect(await exposed.promiseResult, 'promiseResult').to.equal(successMessage)
expect(exposed.promiseError, 'promiseError').to.be.undefined
expect(exposed.status, 'status').to.equal(ExposedPromiseStatus.RESOLVED)
expect(typeof exposed.resolve, 'resolve').to.equal('function')
expect(typeof exposed.reject, 'reject').to.equal('function')
expect(await Promise.all(promises)).to.deep.equal(['success message!', undefined, undefined])
})
it(`should resolve options.result immediately`, async () => {
const successMessage = 'success message!'
const exposed = ExposedPromise.resolve(successMessage)
const promises = getExpectedPromiseOutcome(exposed, ExposedPromiseStatus.RESOLVED)
expect(exposed instanceof ExposedPromise, 'is instanceof ExposedPromise').to.be.true
expect(exposed.isPending(), 'isPending').to.be.false
expect(exposed.isResolved(), 'isResolved').to.be.true
expect(exposed.isRejected(), 'isRejected').to.be.false
expect(exposed.isSettled(), 'isSettled').to.be.true
expect(typeof exposed.promise, 'promise').to.equal('object')
expect(exposed.promiseResult, 'promiseResult').to.equal(successMessage)
expect(exposed.promiseError, 'promiseError').to.be.undefined
expect(exposed.status, 'status').to.equal(ExposedPromiseStatus.RESOLVED)
expect(typeof exposed.resolve, 'resolve').to.equal('function')
expect(typeof exposed.reject, 'reject').to.equal('function')
expect(await Promise.all(promises)).to.deep.equal(['success message!', undefined, undefined])
})
it(`should resolve options.result (undefined) immediately`, async () => {
const successMessage = undefined
const exposed = ExposedPromise.resolve(successMessage)
const promises = getExpectedPromiseOutcome(exposed, ExposedPromiseStatus.RESOLVED)
expect(exposed instanceof ExposedPromise, 'is instanceof ExposedPromise').to.be.true
expect(exposed.isPending(), 'isPending').to.be.false
expect(exposed.isResolved(), 'isResolved').to.be.true
expect(exposed.isRejected(), 'isRejected').to.be.false
expect(exposed.isSettled(), 'isSettled').to.be.true
expect(typeof exposed.promise, 'promise').to.equal('object')
expect(exposed.promiseResult, 'promiseResult').to.equal(successMessage)
expect(exposed.promiseError, 'promiseError').to.be.undefined
expect(exposed.status, 'status').to.equal(ExposedPromiseStatus.RESOLVED)
expect(typeof exposed.resolve, 'resolve').to.equal('function')
expect(typeof exposed.reject, 'reject').to.equal('function')
expect(await Promise.all(promises)).to.deep.equal([undefined, undefined, undefined])
})
it(`should correctly reject an ExposedPromise`, async () => {
const exposed = new ExposedPromise()
exposed.promise.catch(() => undefined) // We need to add a catch here or it will trigger an unhandled rejection error
const failure = 'failure message!'
exposed.reject(failure)
const promises = getExpectedPromiseOutcome(exposed, ExposedPromiseStatus.REJECTED)
expect(exposed instanceof ExposedPromise, 'is instanceof ExposedPromise').to.be.true
expect(exposed.isPending(), 'isPending').to.be.false
expect(exposed.isResolved(), 'isResolved').to.be.false
expect(exposed.isRejected(), 'isRejected').to.be.true
expect(exposed.isSettled(), 'isSettled').to.be.true
expect(typeof exposed.promise, 'promise').to.equal('object')
expect(exposed.promiseResult, 'promiseResult').to.be.undefined
expect(exposed.promiseError, 'promiseError').to.equal(failure)
expect(exposed.status, 'status').to.equal(ExposedPromiseStatus.REJECTED)
expect(typeof exposed.resolve, 'resolve').to.equal('function')
expect(typeof exposed.reject, 'reject').to.equal('function')
expect(await Promise.all(promises)).to.deep.equal([undefined, 'failure message!', undefined])
})
it(`should not change its state after it has been rejected`, async () => {
const exposed = new ExposedPromise()
exposed.promise.catch(() => undefined) // We need to add a catch here or it will trigger an unhandled rejection error
const failureMessage1 = 'failure message 1!'
const failureMessage2 = 'failure message 2!'
exposed.reject(failureMessage1)
exposed.reject(failureMessage2)
const promises = getExpectedPromiseOutcome(exposed, ExposedPromiseStatus.REJECTED)
expect(exposed instanceof ExposedPromise, 'is instanceof ExposedPromise').to.be.true
expect(exposed.isPending(), 'isPending').to.be.false
expect(exposed.isResolved(), 'isResolved').to.be.false
expect(exposed.isRejected(), 'isRejected').to.be.true
expect(exposed.isSettled(), 'isSettled').to.be.true
expect(typeof exposed.promise, 'promise').to.equal('object')
expect(exposed.promiseResult, 'promiseResult').to.be.undefined
expect(exposed.promiseError, 'promiseError').to.equal(failureMessage1)
expect(exposed.status, 'status').to.equal(ExposedPromiseStatus.REJECTED)
expect(typeof exposed.resolve, 'resolve').to.equal('function')
expect(typeof exposed.reject, 'reject').to.equal('function')
expect(await Promise.all(promises)).to.deep.equal([undefined, 'failure message 1!', undefined])
})
it(`should reject options.reject immediately`, async () => {
const failureMessage = 'failure message!'
const exposed = ExposedPromise.reject<unknown>(failureMessage)
exposed.promise.catch(() => undefined) // We need to add a catch here or it will trigger an unhandled rejection error
const promises = getExpectedPromiseOutcome(exposed, ExposedPromiseStatus.REJECTED)
expect(exposed instanceof ExposedPromise, 'is instanceof ExposedPromise').to.be.true
expect(exposed.isPending(), 'isPending').to.be.false
expect(exposed.isResolved(), 'isResolved').to.be.false
expect(exposed.isRejected(), 'isRejected').to.be.true
expect(exposed.isSettled(), 'isSettled').to.be.true
expect(typeof exposed.promise, 'promise').to.equal('object')
expect(exposed.promiseResult, 'promiseResult').to.be.undefined
expect(exposed.promiseError, 'promiseError').to.equal(failureMessage)
expect(exposed.status, 'status').to.equal(ExposedPromiseStatus.REJECTED)
expect(typeof exposed.resolve, 'resolve').to.equal('function')
expect(typeof exposed.reject, 'reject').to.equal('function')
expect(await Promise.all(promises)).to.deep.equal([undefined, 'failure message!', undefined])
})
it(`should reject options.reject (undefined) immediately`, async () => {
const failureMessage = 'failure message!'
const exposed = ExposedPromise.reject<unknown>(failureMessage)
exposed.promise.catch(() => undefined) // We need to add a catch here or it will trigger an unhandled rejection error
const promises = getExpectedPromiseOutcome(exposed, ExposedPromiseStatus.REJECTED)
expect(exposed instanceof ExposedPromise, 'is instanceof ExposedPromise').to.be.true
expect(exposed.isPending(), 'isPending').to.be.false
expect(exposed.isResolved(), 'isResolved').to.be.false
expect(exposed.isRejected(), 'isRejected').to.be.true
expect(exposed.isSettled(), 'isSettled').to.be.true
expect(typeof exposed.promise, 'promise').to.equal('object')
expect(exposed.promiseResult, 'promiseResult').to.be.undefined
expect(exposed.promiseError, 'promiseError').to.equal(failureMessage)
expect(exposed.status, 'status').to.equal(ExposedPromiseStatus.REJECTED)
expect(typeof exposed.resolve, 'resolve').to.equal('function')
expect(typeof exposed.reject, 'reject').to.equal('function')
expect(await Promise.all(promises)).to.deep.equal([undefined, 'failure message!', undefined])
})
}) | the_stack |
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest';
import * as models from '../models';
/**
* @class
* Partner
* __NOTE__: An instance of this class is automatically created for an
* instance of the ACEProvisioningManagementPartnerAPI.
*/
export interface Partner {
/**
* @summary Get a specific `Partner`.
*
* Get the management partner using the partnerId, objectId and tenantId.
*
* @param {string} partnerId Id of the Partner
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<PartnerResponse>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(partnerId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PartnerResponse>>;
/**
* @summary Get a specific `Partner`.
*
* Get the management partner using the partnerId, objectId and tenantId.
*
* @param {string} partnerId Id of the Partner
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {PartnerResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {PartnerResponse} [result] - The deserialized result object if an error did not occur.
* See {@link PartnerResponse} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(partnerId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PartnerResponse>;
get(partnerId: string, callback: ServiceCallback<models.PartnerResponse>): void;
get(partnerId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PartnerResponse>): void;
/**
* @summary Create a specific `Partner`.
*
* Create a management partner for the objectId and tenantId.
*
* @param {string} partnerId Id of the Partner
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<PartnerResponse>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createWithHttpOperationResponse(partnerId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PartnerResponse>>;
/**
* @summary Create a specific `Partner`.
*
* Create a management partner for the objectId and tenantId.
*
* @param {string} partnerId Id of the Partner
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {PartnerResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {PartnerResponse} [result] - The deserialized result object if an error did not occur.
* See {@link PartnerResponse} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
create(partnerId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PartnerResponse>;
create(partnerId: string, callback: ServiceCallback<models.PartnerResponse>): void;
create(partnerId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PartnerResponse>): void;
/**
* @summary Update a specific `Partner`.
*
* Update the management partner for the objectId and tenantId.
*
* @param {string} partnerId Id of the Partner
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<PartnerResponse>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(partnerId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PartnerResponse>>;
/**
* @summary Update a specific `Partner`.
*
* Update the management partner for the objectId and tenantId.
*
* @param {string} partnerId Id of the Partner
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {PartnerResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {PartnerResponse} [result] - The deserialized result object if an error did not occur.
* See {@link PartnerResponse} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(partnerId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PartnerResponse>;
update(partnerId: string, callback: ServiceCallback<models.PartnerResponse>): void;
update(partnerId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PartnerResponse>): void;
/**
* @summary Delete a specific `Partner`.
*
* Delete the management partner for the objectId and tenantId.
*
* @param {string} partnerId Id of the Partner
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(partnerId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* @summary Delete a specific `Partner`.
*
* Delete the management partner for the objectId and tenantId.
*
* @param {string} partnerId Id of the Partner
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(partnerId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(partnerId: string, callback: ServiceCallback<void>): void;
deleteMethod(partnerId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
}
/**
* @class
* Operation
* __NOTE__: An instance of this class is automatically created for an
* instance of the ACEProvisioningManagementPartnerAPI.
*/
export interface Operation {
/**
* @summary Get operations.
*
* List all the operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<OperationList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationList>>;
/**
* @summary Get operations.
*
* List all the operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {OperationList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {OperationList} [result] - The deserialized result object if an error did not occur.
* See {@link OperationList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationList>;
list(callback: ServiceCallback<models.OperationList>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationList>): void;
/**
* @summary Get operations.
*
* List all the operations.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<OperationList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationList>>;
/**
* @summary Get operations.
*
* List all the operations.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {OperationList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {OperationList} [result] - The deserialized result object if an error did not occur.
* See {@link OperationList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.OperationList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationList>): void;
} | the_stack |
import { EwsServiceXmlWriter } from "../Core/EwsServiceXmlWriter";
import { EwsUtilities } from "../Core/EwsUtilities";
import { ExchangeService } from "../Core/ExchangeService";
import { IRefParam } from "../Interfaces/IRefParam";
import { ISearchStringProvider } from "../Interfaces/ISearchStringProvider";
import { ItemId } from "./ItemId";
import { MailboxType } from "../Enumerations/MailboxType";
import { StringHelper } from "../ExtensionMethods";
import { XmlElementNames } from "../Core/XmlElementNames";
import { XmlNamespace } from "../Enumerations/XmlNamespace";
import { ComplexProperty } from "./ComplexProperty";
/**
* Represents an e-mail address.
*/
export class EmailAddress extends ComplexProperty implements ISearchStringProvider {
/**
* SMTP routing type.
*/
static SmtpRoutingType: string = "SMTP";
/**
* Display name.
*/
private name: string = null;
/**
* Email address.
*/
private address: string = null;
/**
* Routing type.
*/
private routingType: string = null;
/**
* Mailbox type.
*/
private mailboxType: MailboxType = null;
/**
* ItemId - Contact or PDL.
*/
private id: ItemId = null;
/**
* Gets or sets the name associated with the e-mail address.
*/
get Name(): string {
return this.name;
}
set Name(value: string) {
this.SetFieldValue<string>({ getValue: () => this.name, setValue: (updateValue) => { this.name = updateValue } }, value);
}
/**
* Gets or sets the actual address associated with the e-mail address. The type of the Address property must match the specified routing type. If RoutingType is not set, Address is assumed to be an SMTP address.
*/
get Address(): string {
return this.address;
}
set Address(value: string) {
this.SetFieldValue<string>({ getValue: () => this.address, setValue: (updateValue) => { this.address = updateValue } }, value);
}
/**
* Gets or sets the routing type associated with the e-mail address. If RoutingType is not set, Address is assumed to be an SMTP address.
*/
get RoutingType(): string {
return this.routingType;
}
set RoutingType(value: string) {
this.SetFieldValue<string>({ getValue: () => this.routingType, setValue: (updateValue) => { this.routingType = updateValue } }, value);
}
/**
* Gets or sets the type of the e-mail address.
*/
get MailboxType(): MailboxType {
return this.mailboxType;
}
set MailboxType(value: MailboxType) {
this.SetFieldValue<MailboxType>({ getValue: () => this.mailboxType, setValue: (updateValue) => { this.mailboxType = updateValue } }, value);
}
/**
* Gets or sets the Id of the contact the e-mail address represents. When Id is specified, Address should be set to null.
*/
get Id(): ItemId {
return this.id;
}
set Id(value: ItemId) {
this.SetFieldValue<ItemId>({ getValue: () => this.id, setValue: (updateValue) => { this.id = updateValue } }, value);
}
/**
* Initializes a new instance of the **EmailAddress** class.
*/
constructor();
/**
* Initializes a new instance of the **EmailAddress** class.
*
* @param {string} name The name used to initialize the EmailAddress.
*/
constructor(smtpAddress: string);
/**
* Initializes a new instance of the **EmailAddress** class.
*
* @param {string} name The name used to initialize the EmailAddress.
* @param {string} address The address used to initialize the EmailAddress.
*/
constructor(name: string, smtpAddress: string);
/**
* Initializes a new instance of the **EmailAddress** class.
*
* @param {string} name The name used to initialize the EmailAddress.
* @param {string} address The address used to initialize the EmailAddress.
* @param {string} routingType The routing type used to initialize the EmailAddress.
*/
constructor(name: string, address: string, routingType: string);
/**
* Initializes a new instance of the **EmailAddress** class.
*
* @param {string} name The name used to initialize the EmailAddress.
* @param {string} address The address used to initialize the EmailAddress.
* @param {string} routingType The routing type used to initialize the EmailAddress.
* @param {MailboxType} mailboxType Mailbox type of the participant.
*/
constructor(name: string, address: string, routingType: string, mailboxType: MailboxType);
/**
* Initializes a new instance of the **EmailAddress** class.
*
* @param {string} name The name used to initialize the EmailAddress.
* @param {string} address The address used to initialize the EmailAddress.
* @param {string} routingType The routing type used to initialize the EmailAddress.
* @param {MailboxType} mailboxType Mailbox type of the participant.
* @param {ItemId} itemId ItemId of a Contact or PDL.
*/
constructor(name: string, address: string, routingType: string, mailboxType: MailboxType, itemId: ItemId);
/**
* Initializes a new instance of the **EmailAddress** class from another EmailAddress instance.
*
* @param {EmailAddress} mailbox EMailAddress instance to copy.
*/
constructor(mailbox: EmailAddress);
constructor(smtpAddressOrMailbox: string | EmailAddress); //for Attendee to call super() easily
constructor(smtpAddressOrNameOrMailbox?: EmailAddress | string, smtpAddressOrAddress?: string, routingType?: string, mailboxType?: MailboxType, itemId?: ItemId) {
super();
if (smtpAddressOrNameOrMailbox instanceof EmailAddress) {
EwsUtilities.ValidateParam(smtpAddressOrNameOrMailbox, "mailbox");
this.Name = smtpAddressOrNameOrMailbox.Name;
this.Address = smtpAddressOrNameOrMailbox.Address;
this.RoutingType = smtpAddressOrNameOrMailbox.RoutingType;
this.MailboxType = smtpAddressOrNameOrMailbox.MailboxType;
this.Id = smtpAddressOrNameOrMailbox.Id;
}
else {
let argsLength = arguments.length;
if (argsLength === 1) {
this.address = <string>smtpAddressOrNameOrMailbox;
}
else if (argsLength > 1) {
this.name = <string>smtpAddressOrNameOrMailbox;
this.address = smtpAddressOrAddress;
if (argsLength >= 3) {
this.routingType = routingType;
}
if (argsLength >= 4) {
this.mailboxType = mailboxType;
}
if (argsLength === 5) {
this.id = itemId;
}
}
}
}
/**
* Get a string representation for using this instance in a search filter.
* ISearchStringProvider.GetSearchString
*
* @return {string} String representation of instance.
*/
GetSearchString(): string {
return this.Address;
}
ReadElementsFromXmlJsObject(reader: any): boolean { throw new Error("EmailAddress.ts - TryReadElementFromXmlJsObject : Not implemented."); }
//todo: implement UpdateFromXmlJsObject
/**
* @internal Loads service object from XML.
*
* @param {any} jsObject Json Object converted from XML.
* @param {ExchangeService} service The service.
*/
LoadFromXmlJsObject(jsObject: any, service: ExchangeService): void {
for (let key in jsObject) {
switch (key) {
case XmlElementNames.Name:
this.name = jsObject[key];
break;
case XmlElementNames.EmailAddress:
this.address = jsObject[key];
break;
case XmlElementNames.RoutingType:
this.routingType = jsObject[key];
break;
case XmlElementNames.MailboxType:
this.mailboxType = MailboxType.FromEwsEnumString(jsObject[key])
break;
case XmlElementNames.ItemId:
this.id = new ItemId();
this.id.LoadFromXmlJsObject(jsObject[key], service);
break;
default:
break;
}
}
}
/**
* Returns a **string** that represents the current **object**.
*
* @return {string} A **string** that represents the current **object**.
*/
ToString(): string {
let addressPart: string = null;
if (StringHelper.IsNullOrEmpty(this.Address)) {
return StringHelper.Empty;
}
if (!StringHelper.IsNullOrEmpty(this.RoutingType)) {
addressPart = this.RoutingType + ":" + this.Address;
}
else {
addressPart = this.Address;
}
if (!StringHelper.IsNullOrEmpty(this.Name)) {
return this.Name + " <" + addressPart + ">";
}
else {
return addressPart;
}
}
toString(): string {
return this.ToString();
}
/**
* @internal Writes elements to XML.
*
* @param {EwsServiceXmlWriter} writer The writer.
*/
WriteElementsToXml(writer: EwsServiceXmlWriter): void {
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Name, this.Name);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.EmailAddress, this.Address);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.RoutingType, this.RoutingType);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.MailboxType, MailboxType.ToEwsEnumString(this.MailboxType));
if (this.Id != null) {
this.Id.WriteToXml(writer);//, XmlElementNames.ItemId);
}
}
} | the_stack |
import React, { useState, useEffect } from 'react';
import { FormComponentProps } from 'antd/lib/form';
import { Row, Col, Select, Form, Input, InputNumber, Radio, Button, AutoComplete } from 'antd';
import { flowUnitList } from '../../constants/common';
import { ILabelValue } from '../../interface/common';
import { yyyyMMDDHHMMss, HHmmssSSS, yyyyMMDDHHMMssSSS, yyyyMMDDHHMMssSS, fuhao } from './dateRegAndGvar'
import './index.less';
import { lastIndexOf } from 'lodash';
import { regLogSliceTimestampPrefixString } from '../../constants/reg';
interface ILogRepeatForm extends FormComponentProps {
getKey?: number | string,
logType: string,
slicingRuleLog: number;
addFileLog?: any;
}
const { TextArea } = Input;
const { Option } = AutoComplete;
const LogRepeatForm = (props: ILogRepeatForm) => {
const { getFieldDecorator, setFieldsValue, getFieldValue } = props.form;
const editUrl = window.location.pathname.includes('/edit-task');
const [slicingRuleLog, setSlicingRuleLog] = useState(0);
const initial = props?.addFileLog && !!Object.keys(props?.addFileLog)?.length;
const [contents, setContents] = useState<any>(null); // 鼠标选取内容正则匹配结果
const [isShow, setShow] = useState(false); // 是否显示日志切片框
const [slicePre, setSlicePre] = useState<string[]>([]); // 日志切片列表
const [start, setStart] = useState(0)
const onSlicingRuleLogChange = (e: any) => {
setSlicingRuleLog(e.target.value);
}
// 匹配时间格式
const regYymdhmsSSS = new RegExp(yyyyMMDDHHMMssSSS)
const regYymdhmsSS = new RegExp(yyyyMMDDHHMMssSS)
const regYymdhms = new RegExp(yyyyMMDDHHMMss)
const regHmsS = new RegExp(HHmmssSSS)
// const regYymd = new RegExp(yyyyMMDD)
// const regYmd = new RegExp(yyMMDD)
const dateType: any = {
"yyyy-MM-dd HH:mm:ss.SSS": regYymdhmsSSS,
"yyyy-MM-dd HH:mm:ss,SSS": regYymdhmsSS,
"yyyy-MM-dd HH:mm:ss": regYymdhms,
'HH:mm:ss.SSS': regHmsS,
// 'YYYY-MM-DD': regYymd,
// 'YY-MM-DD': regYmd,
}
// 获取选中的内容,并将内容匹配对应规则放入时间戳表单中
let sliceTimestampPrefixString: string = '';
let sliceTimestampFormat = ''
let sliceTimestampPrefixStringIndex = 0
/**
* @method cheageSliceTypeReg 正则匹配日志时间类型
* @param reg 需要匹配的正则
* @param dateType 匹配的时间格式
* @param selObj 鼠标选中的字符串
* @param userCopyContent 文本框的内容
*/
const cheageSliceTypeReg = (reg: any, dateType: string, selObj: string, userCopyContent: string) => {
sliceTimestampPrefixString = selObj.split(selObj?.match(reg)[0])[0].slice(-1);
sliceTimestampFormat = dateType
let aNewlineIs = userCopyContent.slice(0, userCopyContent.indexOf(selObj) + selObj.indexOf(selObj?.match(reg)[0])).lastIndexOf('\n')
if (sliceTimestampPrefixString === '') {
if (aNewlineIs === -1) {
sliceTimestampPrefixStringIndex = userCopyContent.slice(0, userCopyContent.indexOf(selObj) + selObj.indexOf(selObj?.match(reg)[0])).split(`${sliceTimestampPrefixString}`).length - 1
} else {
sliceTimestampPrefixStringIndex = userCopyContent.slice(aNewlineIs, userCopyContent.indexOf(selObj) + selObj.indexOf(selObj?.match(reg)[0])).split(sliceTimestampPrefixString).length - 1
}
} else {
if (aNewlineIs === -1) {
sliceTimestampPrefixStringIndex = userCopyContent.slice(0, userCopyContent.indexOf(selObj) + selObj.indexOf(selObj?.match(reg)[0])).split(`${sliceTimestampPrefixString}`).length - 2
} else {
sliceTimestampPrefixStringIndex = userCopyContent.slice(aNewlineIs, userCopyContent.indexOf(selObj) + selObj.indexOf(selObj?.match(reg)[0])).split(sliceTimestampPrefixString).length - 2
}
}
// setContents(selObj?.match(reg)[0])
}
const getSelectionType = () => {
let selObj = window?.getSelection()?.toString() || document.getSelection()?.toString();
const userCopyContent = getFieldValue(`step2_${props.logType}_selectionType`)
setShow(false)
if (selObj === '') return
if (!!userCopyContent) {
/*
12$2018-04-08 asdsad
$123$123$2018-04-09 sqrwqrq
$123$33$2018-01-08 sqrwqrq
yyyy-MM-dd HH:mm:ss.SSS
yyyy-MM-dd HH:mm:ss
HH:mm:ss.SSS
2021-06-25 14:51:31.798 [main] ERROR logger3 - 4191185 1624603891798
2021-06-25 14:51:31.798 [main] ERROR logger3 - 4191185 1624603891798
*/
if (selObj?.match(regYymdhmsSSS)) {
cheageSliceTypeReg(regYymdhmsSSS, "yyyy-MM-dd HH:mm:ss.SSS", selObj, userCopyContent)
} else if (selObj?.match(regYymdhmsSS)) {
cheageSliceTypeReg(regYymdhmsSS, "yyyy-MM-dd HH:mm:ss,SSS", selObj, userCopyContent)
} else if (selObj?.match(regYymdhms)) {
cheageSliceTypeReg(regYymdhms, "yyyy-MM-dd HH:mm:ss", selObj, userCopyContent)
} else if (selObj?.match(regHmsS)) {
cheageSliceTypeReg(regHmsS, "HH:mm:ss.SSS", selObj, userCopyContent)
}
setFieldsValue({
[`step2_${props.logType}_sliceTimestampPrefixString`]: sliceTimestampPrefixString || '',
[`step2_${props.logType}_sliceTimestampFormat`]: sliceTimestampFormat,
[`step2_${props.logType}_sliceTimestampPrefixStringIndex`]: sliceTimestampPrefixStringIndex
})
return
}
}
/**
* @method getStrCount:boolean[] 获取字符串中符合条件的字符串并返回布尔值
* @param content 需要处理的内容
* @param sliceSymbol 截取的符号内容
* @param symbolIndex 截取的符号的下标
* @param sliceFormat 符合的时间格式
* @param { {[x: string]: any;} } dateType 时间格式类型集合
*/
const getStrCount = (content: any, sliceSymbol: string, symbolIndex: number, sliceFormat: string, dateType: { [x: string]: any; }): boolean[] => {
const conformSlice = []
const userInterceptionContent = content.split('\n')
const conformSliceBoolean = userInterceptionContent.map((item: string) => {
return item.split(sliceSymbol).length - 2 === symbolIndex
})
for (let index = 0; index < userInterceptionContent.length; index++) {
if (conformSliceBoolean[index] || userInterceptionContent[index]?.match(dateType[sliceFormat])) {
conformSlice.push(...userInterceptionContent[index]?.match(dateType[sliceFormat]))
}
}
return conformSlice
}
// 日志预览按钮
const slicePreview = () => {
const userCopyContent = getFieldValue(`step2_${props.logType}_selectionType`)
const slicePrefixString = getFieldValue(`step2_${props.logType}_sliceTimestampPrefixString`)
const sliceFormat = getFieldValue(`step2_${props.logType}_sliceTimestampFormat`)
let slicePrefixStringIndex = getFieldValue(`step2_${props.logType}_sliceTimestampPrefixStringIndex`)
// let newVal = userCopyContent.slice(start < 0 ? 0 : start)
if (slicePrefixStringIndex < 0) {
slicePrefixStringIndex = 0
}
let contentList = userCopyContent.split('\n')
let resContentLists: any = []
for (let i = 0; i < contentList.length; i++) {
if (contentList[i].match(dateType[sliceFormat])) {
let regStr = contentList[i].match(dateType[sliceFormat])[0]
let startTimeIndex = contentList[i].indexOf(regStr) //时间格式开始的下标
let startStr = contentList[i].slice(0, startTimeIndex) // 时间格式前面的字符串
if (slicePrefixString === '' && slicePrefixStringIndex === 0 && startTimeIndex === 0) {
resContentLists.push(contentList[i])
} else if (!!slicePrefixString && startStr.slice(-1) === slicePrefixString && startStr.split(slicePrefixString).length - 2 === slicePrefixStringIndex) {
// if (resContentLists.length > 0) {
// resContentLists[resContentLists.length - 1] += contentList[i].split(regStr)[0]
// } else {
// resContentLists[0] = contentList[i].split(regStr)[0]
// }
resContentLists.push(contentList[i].split(regStr)[0] + regStr + contentList[i].split(regStr)[1])
} else {
if (resContentLists.length > 0) {
resContentLists[resContentLists.length - 1] += contentList[i]
} else {
resContentLists[0] = contentList[i]
}
}
} else {
if (resContentLists.length > 0) {
resContentLists[resContentLists.length - 1] += contentList[i]
} else {
resContentLists[0] = contentList[i]
}
}
}
if (userCopyContent && sliceFormat && slicePrefixStringIndex >= 0 && resContentLists.length > 0 && dateType[sliceFormat]) {
// setSlicePre(handleArray(userCopyContent, getStrCount(userCopyContent, slicePrefixString, slicePrefixStringIndex, sliceFormat, dateType)))
setSlicePre(resContentLists)
setShow(true)
} else {
setSlicePre([])
setShow(false)
}
}
/**
* @method interStrhToArray 将字符串按照筛选条件进行截取,符合返回出一个截取之后的数组
* @param {string} str 要截取的字符串
* @param {string[]} rules 截取字符串的
*/
const handleArray = (str: string, rules: any[]) => {
let arr: any = []
let brr: any = []
if (str.trim().length < 1) {
return
}
if (rules.length < 1) {
return
}
for (let index = 0; index < rules.length; index++) {
let pos = str.indexOf(rules[index])
while (pos > -1) {
arr.push(pos);
pos = str.indexOf(rules[index], pos + 1);
}
}
arr = [...new Set(arr)]
if (arr.length < 1) return
if (arr[0] !== 0) {
arr.unshift(0)
}
for (let index = 0; index < arr.length; index++) {
brr.push(str.slice(arr[index], arr[index + 1]))
}
return brr
}
useEffect(() => {
if (editUrl) {
setSlicingRuleLog(props.slicingRuleLog);
}
}, [props.slicingRuleLog]);
const options = Object.keys(dateType).map((group, index) => (
<Option key={index} value={group}>
{group}
</Option>
))
return (
<div className='log-repeat-form'>
{/* <Form.Item label="单条日志大小上限" className='col-unit-log'>
<Row>
<Col span={13}>
{getFieldDecorator(`step2_${props.logType}_maxBytesPerLogEvent_${props.getKey}`, {
initialValue: initial ? props?.addFileLog[`step2_file_maxBytesPerLogEvent_${props.getKey}`] : 2,
rules: [{ required: true, message: '请输入单条日志大小上限' }],
})(
<InputNumber className='w-300' min={1} placeholder='请输入数字' />,
)}
</Col>
<Col span={3}>
<Form.Item>
{getFieldDecorator(`step2_${props.logType}_flowunit_${props.getKey}`, {
initialValue: initial ? props?.addFileLog[`step2_file_flowunit_${props.getKey}`] : flowUnitList[1]?.value,
rules: [{ required: true, message: '请选择' }],
})(
<Select className='w-100'>
{flowUnitList.map((v: ILabelValue, index: number) => (
<Select.Option key={index} value={v.value}>
{v.label}
</Select.Option>
))}
</Select>,
)}
</Form.Item>
</Col>
</Row>
</Form.Item> */}
{/* <Form.Item label='日志切片规则'>
{getFieldDecorator(`step2_${props.logType}_sliceType_${props.getKey}`, {
initialValue: initial ? props?.addFileLog[`step2_file_sliceType_${props.getKey}`] : 0,
rules: [{ required: true, message: '请选择日志切片规则' }],
})(
<Radio.Group onChange={onSlicingRuleLogChange}>
<Radio value={0}>时间戳</Radio>
<Radio value={1}>正则匹配</Radio>
</Radio.Group>,
)}
</Form.Item> */}
{/* {slicingRuleLog === 0 ? */}
<Form.Item className='col-time-stramp' extra='注:填写时间戳,或复制日志文本并通过划取时间戳自动填写,复制文本时,为保证正确性,需从日志任一段落行首开始' label='日志切片规则'>
<Row>
<Col span={6}>
左起第 {getFieldDecorator(`step2_${props.logType}_sliceTimestampPrefixStringIndex`, {
initialValue: 0,
rules: [{
required: true,
message: '请输入',
validator: (rule: any, value: any, cb) => {
if (value != 0 && value == '') {
console.log(value)
rule.message = '请输入'
cb('请输入')
} else if (!new RegExp(regLogSliceTimestampPrefixString).test(value)) {
rule.message = '最大长度限制8位'
cb('最大长度限制8位')
} else {
cb()
}
},
}],
})(<InputNumber style={{ margin: '0 5px', width: '65px' }} min={0} max={99999999} precision={0} />)} 个匹配上
</Col>
<Col span={6} style={{ margin: '0 10px' }} >
<Form.Item>
{getFieldDecorator(`step2_${props.logType}_sliceTimestampPrefixString`, {
// initialValue: contents,
initialValue: '',
rules: [{
// required: true,
// message: '请输入',
validator: (rule: any, value: string, cb) => {
if (!value) {
cb()
} else if (!new RegExp(regLogSliceTimestampPrefixString).test(value)) {
rule.message = '前缀字符串最大长度为8位'
cb('前缀字符串最大长度为8位')
} else {
cb()
}
},
}],
})(<Input onChange={() => setStart(-1)} className='w-200' placeholder='请输入切片时间戳前缀字符串' />)} {/* ,如yyyy-MM-ddMM-dd HH-mm-ss */}
</Form.Item>
</Col>
<Col span={6} style={{ margin: '0 10px' }} >
{/* <Form.Item>
{getFieldDecorator(`step2_${props.logType}_sliceTimestampFormat_${props.getKey}`, {
initialValue: initial ? props?.addFileLog[`step2_file_sliceTimestampFormat_${props.getKey}`] : '',
rules: [{ required: true, message: '请输入' }],
})(<Input className='w-200' placeholder='请输入时间戳格式' />)}
</Form.Item> */}
{/* <Form.Item>
{getFieldDecorator(`step2_${props.logType}_sliceTimestampFormat`, {
initialValue: initial ? props?.addFileLog[`step2_file_sliceTimestampFormat`] : Object.keys(dateType)[0],
rules: [{ required: true, message: '请选择或者输入时间格式' }],
})(<Select className='w-200' placeholder="请选择或者输入时间格式">
{Object.keys(dateType).map((v: any, index: number) => {
return (<Select.Option key={index} value={v}>
{v}
</Select.Option>)
})}
</Select>)}
</Form.Item> */}
<Form.Item>
{getFieldDecorator(`step2_${props.logType}_sliceTimestampFormat`, {
initialValue: Object.keys(dateType)[0],
rules: [{ required: true, message: '请选择或者输入时间格式' }],
})(<AutoComplete
dataSource={options}
style={{ width: 180 }}
className='step2_file_sliceTimestampFormat'
onChange={() => setStart(-1)}
// onSelect={onSelect}
// onSearch={this.onSearch}
// placeholder="input here"
/>)}
</Form.Item>
</Col>
<Col span={3} style={{ margin: '0 10px' }} >
<Button type='primary' onClick={slicePreview}>切片预览</Button>
</Col>
</Row>
</Form.Item>
<Row style={{ marginLeft: '16.5%' }}>
<Col span={8} >
{getFieldDecorator(`step2_${props.logType}_selectionType`, {
// initialValue: initial ? props?.addFileLog[`step2_file_selectionType_${props.getKey}`] : '',
rules: [{ message: '请输入正则表达式,如.\d+' }],
})(<TextArea style={{ height: '120px' }} onBlur={e => {
setStart(e.target.selectionStart)
}} onClick={getSelectionType} className='w-300' placeholder='请复制日志文本并通过划取时间戳自动填写,复制文本时,为保证正确性,需从日志任一段落行首开始' />)}
</Col>
<Col span={8} style={{ display: 'block' }}>
{
isShow && <div className='w-300 slicePreview' style={{ height: '120px', border: '1px solid #CCC' }} >
{
slicePre && slicePre.map((item: string, key) => {
if (item === '') {
return null
}
return <span key={key}>{item}</span>
})
}
</div>
}
</Col>
</Row>
</div>
);
};
export default LogRepeatForm; | the_stack |
import { grpc } from '@improbable-eng/grpc-web'
import { ContextInterface } from '@textile/context'
import { GrpcConnection } from '@textile/grpc-connection'
import { Client, GetThreadResponse, Update } from '@textile/hub-threads-client'
import { ThreadID } from '@textile/threads-id'
import {
DeleteInboxMessageRequest,
DeleteSentboxMessageRequest,
GetThreadRequest,
GetThreadResponse as _GetThreadResponse,
GetUsageRequest,
GetUsageResponse as _GetUsageResponse,
ListInboxMessagesRequest,
ListInboxMessagesResponse,
ListSentboxMessagesRequest,
ListSentboxMessagesResponse,
ListThreadsRequest,
ListThreadsResponse as _ListThreadsResponse,
Message,
ReadInboxMessageRequest,
ReadInboxMessageResponse,
SendMessageRequest,
SendMessageResponse,
SetupMailboxRequest,
SetupMailboxResponse,
} from '@textile/users-grpc/api/usersd/pb/usersd_pb'
import { APIService } from '@textile/users-grpc/api/usersd/pb/usersd_pb_service'
import log from 'loglevel'
const logger = log.getLogger('users-api')
/**
* Global settings for mailboxes
*/
export const MailConfig = {
ThreadName: 'hubmail',
InboxCollectionName: 'inbox',
SentboxCollectionName: 'sentbox',
}
/**
* The status query filter of an inbox message.
*/
export enum Status {
ALL,
READ,
UNREAD,
}
/**
* Sentbox query options
*/
export interface SentboxListOptions {
seek?: string
limit?: number
ascending?: boolean
}
/**
* Inbox query options
*/
export interface InboxListOptions {
seek?: string
limit?: number
ascending?: boolean
status?: Status
}
/**
* @deprecated
*/
export type GetThreadResponseObj = GetThreadResponse
export interface Usage {
description: string
units: number
total: number
free: number
grace: number
cost: number
period?: Period
}
export interface CustomerUsage {
usageMap: [string, Usage][]
}
/**
* GetUsage options
*/
export interface UsageOptions {
/**
* Public key of the user. Only available when authenticated using an account key.
*/
dependentUserKey?: string
}
export interface Period {
unixStart: number
unixEnd: number
}
/**
* The response type from getUsage
*/
export interface CustomerResponse {
key: string
customerId: string
parentKey: string
email: string
accountType: number
accountStatus: string
subscriptionStatus: string
balance: number
billable: boolean
delinquent: boolean
createdAt: number
gracePeriodEnd: number
invoicePeriod?: Period
dailyUsageMap: Array<[string, Usage]>
dependents: number
}
export interface GetUsageResponse {
customer?: CustomerResponse
usage?: CustomerUsage
}
/**
* The message format returned from inbox or sentbox
*/
export interface UserMessage {
id: string
to: string
from: string
body: Uint8Array
signature: Uint8Array
createdAt: number
readAt?: number
}
/**
* The mailbox event type. CREATE, SAVE, or DELETE
*/
export enum MailboxEventType {
CREATE,
SAVE,
DELETE,
}
/**
* The event type returned from inbox and sentbox subscriptions
*/
export interface MailboxEvent {
type: MailboxEventType
messageID: string
message?: UserMessage
}
interface IntermediateMessage {
_id: string
from: string
to: string
body: string
signature: string
created_at: number
read_at: number
}
function convertMessageObj(input: Message): UserMessage {
return {
body: input.getBody_asU8(),
signature: input.getSignature_asU8(),
from: input.getFrom(),
id: input.getId(),
to: input.getTo(),
createdAt: input.getCreatedAt(),
readAt: input.getReadAt(),
}
}
/**
* @internal
*/
export async function listThreads(
api: GrpcConnection,
ctx?: ContextInterface,
): Promise<Array<GetThreadResponse>> {
logger.debug('list threads request')
const req = new ListThreadsRequest()
const res: _ListThreadsResponse = await api.unary(
APIService.ListThreads,
req,
ctx,
)
return res.getListList().map((value: _GetThreadResponse) => {
return {
isDb: value.getIsDb(),
name: value.getName(),
id: ThreadID.fromBytes(value.getId_asU8()).toString(),
}
})
}
/**
* @internal
*/
export async function getThread(
api: GrpcConnection,
name: string,
ctx?: ContextInterface,
): Promise<GetThreadResponse> {
logger.debug('get thread request')
const req = new GetThreadRequest()
req.setName(name)
const res: _GetThreadResponse = await api.unary(
APIService.GetThread,
req,
ctx,
)
return {
name: res.getName(),
id: ThreadID.fromBytes(res.getId_asU8()).toString(),
}
}
/**
* @internal
*/
export async function setupMailbox(
api: GrpcConnection,
ctx?: ContextInterface,
): Promise<string> {
logger.debug('setup mailbox request')
const req = new SetupMailboxRequest()
const res: SetupMailboxResponse = await api.unary(
APIService.SetupMailbox,
req,
ctx,
)
const mailboxID = ThreadID.fromBytes(res.getMailboxId_asU8())
return mailboxID.toString()
}
/**
* @internal
*/
export async function getMailboxID(
api: GrpcConnection,
ctx?: ContextInterface,
): Promise<string> {
logger.debug('setup mailbox request')
const thread = await getThread(api, MailConfig.ThreadName, ctx)
return thread.id.toString()
}
/**
* @internal
*/
export async function sendMessage(
api: GrpcConnection,
from: string,
to: string,
toBody: Uint8Array,
toSignature: Uint8Array,
fromBody: Uint8Array,
fromSignature: Uint8Array,
ctx?: ContextInterface,
): Promise<UserMessage> {
logger.debug('send message request')
const req = new SendMessageRequest()
req.setTo(to)
req.setToBody(toBody)
req.setToSignature(toSignature)
req.setFromBody(fromBody)
req.setFromSignature(fromSignature)
const res: SendMessageResponse = await api.unary(
APIService.SendMessage,
req,
ctx,
)
return {
id: res.getId(),
createdAt: res.getCreatedAt(),
body: fromBody,
signature: fromSignature,
to,
from,
}
}
/**
* @internal
*/
export async function listInboxMessages(
api: GrpcConnection,
opts?: InboxListOptions,
ctx?: ContextInterface,
): Promise<Array<UserMessage>> {
logger.debug('list inbox message request')
const req = new ListInboxMessagesRequest()
if (opts && opts.seek) req.setSeek(opts.seek)
if (opts && opts.limit) req.setLimit(opts.limit)
if (opts && opts.ascending) req.setAscending(opts.ascending)
if (opts && opts.status) {
switch (opts.status) {
case Status.READ:
req.setStatus(ListInboxMessagesRequest.Status.STATUS_READ)
case Status.UNREAD:
req.setStatus(ListInboxMessagesRequest.Status.STATUS_UNREAD)
}
}
const res: ListInboxMessagesResponse = await api.unary(
APIService.ListInboxMessages,
req,
ctx,
)
return res.getMessagesList().map(convertMessageObj)
}
/**
* @internal
*/
export async function listSentboxMessages(
api: GrpcConnection,
opts?: SentboxListOptions,
ctx?: ContextInterface,
): Promise<Array<UserMessage>> {
logger.debug('list sentbox message request')
const req = new ListSentboxMessagesRequest()
if (opts && opts.seek) req.setSeek(opts.seek)
if (opts && opts.limit) req.setLimit(opts.limit)
if (opts && opts.ascending) req.setAscending(opts.ascending)
const res: ListSentboxMessagesResponse = await api.unary(
APIService.ListSentboxMessages,
req,
ctx,
)
return res.getMessagesList().map(convertMessageObj)
}
/**
* @internal
*/
export async function readInboxMessage(
api: GrpcConnection,
id: string,
ctx?: ContextInterface,
): Promise<{ readAt: number }> {
logger.debug('read inbox message request')
const req = new ReadInboxMessageRequest()
req.setId(id)
const res: ReadInboxMessageResponse = await api.unary(
APIService.ReadInboxMessage,
req,
ctx,
)
return { readAt: res.toObject().readAt }
}
/**
* @internal
*/
export async function deleteInboxMessage(
api: GrpcConnection,
id: string,
ctx?: ContextInterface,
): Promise<void> {
logger.debug('delete inbox message request')
const req = new DeleteInboxMessageRequest()
req.setId(id)
await api.unary(APIService.DeleteInboxMessage, req, ctx)
return
}
/**
* @internal
*/
export async function deleteSentboxMessage(
api: GrpcConnection,
id: string,
ctx?: ContextInterface,
): Promise<void> {
logger.debug('delete sentbox message request')
const req = new DeleteSentboxMessageRequest()
req.setId(id)
await api.unary(APIService.DeleteSentboxMessage, req, ctx)
return
}
/**
* @internal
*/
export function watchMailbox(
api: GrpcConnection,
id: string,
box: 'inbox' | 'sentbox',
callback: (reply?: MailboxEvent, err?: Error) => void,
ctx?: ContextInterface,
): grpc.Request {
logger.debug('new watch inbox request')
const client = new Client(ctx || api.context)
const threadID = ThreadID.fromString(id)
const retype = (reply?: Update<IntermediateMessage>, err?: Error): void => {
if (!reply) {
callback(reply, err)
} else {
const type = reply.action as number
const result: MailboxEvent = {
type,
messageID: reply.instanceID,
}
const instance = reply.instance
if (instance) {
result.message = {
id: reply.instanceID,
from: instance.from,
to: instance.to,
body: new Uint8Array(Buffer.from(instance.body, 'base64')),
signature: new Uint8Array(Buffer.from(instance.signature, 'base64')),
createdAt: instance.created_at,
readAt: instance.read_at,
}
}
callback(result)
}
}
const collectionName =
box === 'inbox'
? MailConfig.InboxCollectionName
: MailConfig.SentboxCollectionName
return client.listen<IntermediateMessage>(
threadID,
[{ collectionName }],
retype,
)
}
/**
* @internal
*/
export async function getUsage(
api: GrpcConnection,
options?: UsageOptions,
ctx?: ContextInterface,
): Promise<GetUsageResponse> {
logger.debug('get usage request')
const req = new GetUsageRequest()
if (options && options.dependentUserKey) {
req.setKey(options.dependentUserKey)
}
const res: _GetUsageResponse = await api.unary(APIService.GetUsage, req, ctx)
const usage = res.toObject()
return {
customer: usage.customer,
usage: usage.usage,
}
} | the_stack |
import { Component, updateComponent } from "./component";
import { ComponentFlags } from "./misc";
import { VNode } from "./vnode";
export type SchedulerTask = () => void;
/**
* Scheduler flags.
*/
const enum SchedulerFlags {
/// Microtasks are pending for execution in microtasks queue.
MicrotaskPending = 1,
/// Macrotasks are pending for execution in macrotasks queue.
MacrotaskPending = 1 << 1,
/// Frametasks are pending for execution in frametasks queue.
FrametaskPending = 1 << 2,
/// Mounting is enabled.
EnabledMounting = 1 << 3,
}
const enum FrameTasksGroupFlags {
Component = 1,
Write = 1 << 1,
Read = 1 << 2,
After = 1 << 3,
RWLock = 1 << 4,
}
/**
* Frame tasks group contains tasks for updating components, read dom and write dom tasks, and tasks that should be
* executed after all other tasks are finished.
*
* To get access to the frame tasks group, use: `currentFrame()` and `nextFrame()` scheduler methods.
*
* scheduler.currentFrame().read(() => {
* console.log(element.clientWidth);
* });
*
* @final
*/
export class FrameTasksGroup {
/**
* See `FrameTasksGroupFlags` for details.
*/
_flags: number;
/**
* Array of component arrays indexed by their depth.
*/
_componentTasks: Array<Component<any, any>[] | null>;
/**
* Write DOM task queue.
*/
_writeTasks: SchedulerTask[] | null;
/**
* Read DOM task queue.
*/
_readTasks: SchedulerTask[] | null;
/**
* Tasks that should be executed when all other tasks are finished.
*/
_afterTasks: SchedulerTask[] | null;
/**
* Element that should be focused.
*/
_focus: Element | VNode | null;
constructor() {
this._flags = 0;
this._componentTasks = [];
this._writeTasks = null;
this._readTasks = null;
this._afterTasks = null;
this._focus = null;
}
/**
* Add Component to the components queue.
*/
updateComponent(component: Component<any, any>): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & FrameTasksGroupFlags.RWLock) !== 0) {
throw new Error("Failed to add update component task to the current frame, current frame is locked for read" +
" and write tasks.");
}
}
if ((component.flags & ComponentFlags.InUpdateQueue) === 0) {
component.flags |= ComponentFlags.InUpdateQueue;
const priority = component.depth;
this._flags |= FrameTasksGroupFlags.Component;
while (priority >= this._componentTasks.length) {
this._componentTasks.push(null);
}
const group = this._componentTasks[priority];
if (group === null) {
this._componentTasks[priority] = [component];
} else {
group.push(component);
}
}
}
/**
* Add new task to the write DOM task queue.
*/
write(callback: SchedulerTask): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & FrameTasksGroupFlags.RWLock) !== 0) {
throw new Error("Failed to add update component task to the current frame, current frame is locked for read" +
" and write tasks.");
}
}
this._flags |= FrameTasksGroupFlags.Write;
if (this._writeTasks === null) {
this._writeTasks = [];
}
this._writeTasks.push(callback);
}
/**
* Add new task to the read DOM task queue.
*/
read(callback: SchedulerTask): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & FrameTasksGroupFlags.RWLock) !== 0) {
throw new Error("Failed to add update component task to the current frame, current frame is locked for read" +
" and write tasks.");
}
}
this._flags |= FrameTasksGroupFlags.Read;
if (this._readTasks === null) {
this._readTasks = [];
}
this._readTasks.push(callback);
}
/**
* Add new task to the task queue that will execute tasks when all DOM tasks are finished.
*/
after(callback: SchedulerTask): void {
this._flags |= FrameTasksGroupFlags.After;
if (this._afterTasks === null) {
this._afterTasks = [];
}
this._afterTasks.push(callback);
}
/**
* Set a focus on an element when all DOM tasks are finished.
*/
focus(node: Element | VNode): void {
this._focus = node;
}
/**
* Place a lock on adding new read and write task.
*
* Works in DEBUG mode only.
*/
_rwLock(): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
this._flags |= FrameTasksGroupFlags.RWLock;
}
}
/**
* Remove a lock from adding new read and write tasks.
*
* Works in DEBUG mode only.
*/
_rwUnlock(): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
this._flags &= ~FrameTasksGroupFlags.RWLock;
}
}
}
/**
* Global scheduler variables.
*
* Scheduler supports animation frame tasks, macrotasks and microtasks.
*
* Animation frame tasks will be executed in batches, switching between write and read tasks until there
* are no tasks left. Write tasks are sorted by their priority, tasks with the lowest priority value are
* executed first, so the lowest depth of the Component in the components tree has highest priority.
*
* Scheduler also have monotonically increasing internal clock, it increments each time scheduler goes
* from one animation frame to another, or starts executing macrotasks or microtasks.
*/
const scheduler = {
/**
* See `SchedulerFlags` for details.
*/
flags: 0,
clock: 0,
time: 0,
microtasks: [] as SchedulerTask[],
macrotasks: [] as SchedulerTask[],
currentFrame: new FrameTasksGroup(),
nextFrame: new FrameTasksGroup(),
updateComponents: [] as Component<any, any>[],
microtaskNode: document.createTextNode(""),
microtaskToggle: 0,
macrotaskMessage: "__kivi" + Math.random(),
};
// Microtask scheduler based on mutation observer
const microtaskObserver = new MutationObserver(runMicrotasks);
microtaskObserver.observe(scheduler.microtaskNode, { characterData: true });
// Macrotask scheduler based on postMessage
window.addEventListener("message", handleWindowMessage);
scheduler.currentFrame._rwLock();
/**
* Returns current monotonically increasing clock.
*/
export function clock(): number {
return scheduler.clock;
}
function requestMicrotaskExecution(): void {
if ((scheduler.flags & SchedulerFlags.MicrotaskPending) === 0) {
scheduler.flags |= SchedulerFlags.MicrotaskPending;
scheduler.microtaskToggle ^= 1;
scheduler.microtaskNode.nodeValue = scheduler.microtaskToggle ? "1" : "0";
}
}
function requestMacrotaskExecution(): void {
if ((scheduler.flags & SchedulerFlags.MacrotaskPending) === 0) {
scheduler.flags |= SchedulerFlags.MacrotaskPending;
window.postMessage(scheduler.macrotaskMessage, "*");
}
}
function requestNextFrame(): void {
if ((scheduler.flags & SchedulerFlags.FrametaskPending) === 0) {
scheduler.flags |= SchedulerFlags.FrametaskPending;
requestAnimationFrame(handleNextFrame);
}
}
function handleWindowMessage(e: MessageEvent): void {
if (e.source === window && e.data === scheduler.macrotaskMessage) {
runMacrotasks();
}
}
function handleNextFrame(t: number): void {
const updateComponents = scheduler.updateComponents;
let tasks: SchedulerTask[];
let i: number;
let j: number;
scheduler.flags &= ~SchedulerFlags.FrametaskPending;
scheduler.time = Date.now();
const frame = scheduler.nextFrame;
scheduler.nextFrame = scheduler.currentFrame;
scheduler.currentFrame = frame;
scheduler.currentFrame._rwUnlock();
scheduler.nextFrame._rwUnlock();
// Mark all update components as dirty. But don't update until all write tasks are finished. It is possible that we
// won't need to update component if it is removed.
for (i = 0; i < updateComponents.length; i++) {
updateComponents[i].flags |= ComponentFlags.Dirty;
}
// Perform read/write batching. Start with executing read DOM tasks, then update components, execute write DOM tasks
// and repeat until all read and write tasks are executed.
do {
while ((frame._flags & FrameTasksGroupFlags.Read) !== 0) {
frame._flags &= ~FrameTasksGroupFlags.Read;
tasks = frame._readTasks!;
frame._readTasks = null;
for (i = 0; i < tasks.length; i++) {
tasks[i]();
}
}
while ((frame._flags & (FrameTasksGroupFlags.Component | FrameTasksGroupFlags.Write)) !== 0) {
if ((frame._flags & FrameTasksGroupFlags.Component) !== 0) {
frame._flags &= ~FrameTasksGroupFlags.Component;
const componentGroups = frame._componentTasks;
for (i = 0; i < componentGroups.length; i++) {
const componentGroup = componentGroups[i];
if (componentGroup !== null) {
componentGroups[i] = null;
for (j = 0; j < componentGroup.length; j++) {
updateComponent(componentGroup[j]);
}
}
}
}
if ((frame._flags & FrameTasksGroupFlags.Write) !== 0) {
frame._flags &= ~FrameTasksGroupFlags.Write;
tasks = frame._writeTasks!;
frame._writeTasks = null;
for (i = 0; i < tasks.length; i++) {
tasks[i]();
}
}
}
// Update components registered for updating on each frame.
// Remove components that doesn't have UPDATE_EACH_FRAME flag.
i = 0;
j = updateComponents.length;
while (i < j) {
const component = updateComponents[i++];
if ((component.flags & ComponentFlags.UpdateEachFrame) === 0) {
component.flags &= ~ComponentFlags.InUpdateEachFrameQueue;
if (i === j) {
updateComponents.pop();
} else {
updateComponents[--i] = updateComponents.pop() !;
}
} else {
updateComponent(component);
}
}
} while ((frame._flags & (FrameTasksGroupFlags.Component |
FrameTasksGroupFlags.Write |
FrameTasksGroupFlags.Read)) !== 0);
// Lock current from adding read and write tasks in debug mode.
scheduler.currentFrame._rwLock();
// Perform tasks that should be executed when all DOM ops are finished.
while ((frame._flags & FrameTasksGroupFlags.After) !== 0) {
frame._flags &= ~FrameTasksGroupFlags.After;
tasks = frame._afterTasks!;
frame._afterTasks = null;
for (i = 0; i < tasks.length; i++) {
tasks[i]();
}
}
// Set focus on an element.
if (frame._focus !== null) {
if (frame._focus.constructor === VNode) {
((frame._focus as VNode).ref as HTMLElement).focus();
} else {
(frame._focus as HTMLElement).focus();
}
frame._focus = null;
}
if (updateComponents.length > 0) {
requestNextFrame();
}
scheduler.clock++;
}
function runMicrotasks(): void {
scheduler.time = Date.now();
while (scheduler.microtasks.length > 0) {
const tasks = scheduler.microtasks;
scheduler.microtasks = [];
for (let i = 0; i < tasks.length; i++) {
tasks[i]();
}
scheduler.clock++;
}
scheduler.flags &= ~SchedulerFlags.MicrotaskPending;
}
function runMacrotasks(): void {
scheduler.flags &= ~SchedulerFlags.MacrotaskPending;
scheduler.time = Date.now();
let tasks = scheduler.macrotasks;
scheduler.macrotasks = [];
for (let i = 0; i < tasks.length; i++) {
tasks[i]();
}
scheduler.clock++;
}
/**
* Add task to the microtask queue.
*/
export function scheduleMicrotask(task: () => void): void {
requestMicrotaskExecution();
scheduler.microtasks.push(task);
}
/**
* Add task to the macrotask queue.
*/
export function scheduleMacrotask(task: () => void): void {
requestMacrotaskExecution();
scheduler.macrotasks.push(task);
}
/**
* Get task list for the current frame.
*/
export function currentFrame(): FrameTasksGroup {
return scheduler.currentFrame;
}
/**
* Get task list for the next frame.
*/
export function nextFrame(): FrameTasksGroup {
requestNextFrame();
return scheduler.nextFrame;
}
/**
* Add component to the list of components that should be updated each frame.
*/
export function startUpdateComponentEachFrame(component: Component<any, any>): void {
requestNextFrame();
scheduler.updateComponents.push(component);
}
/**
* Returns true if UI state is in mounting phase.
*/
export function isMounting(): boolean {
return ((scheduler.flags & SchedulerFlags.EnabledMounting) !== 0);
}
/**
* Start UI mounting phase.
*/
export function startMounting(): void {
scheduler.flags |= SchedulerFlags.EnabledMounting;
}
/**
* Finish UI mounting phase.
*/
export function finishMounting(): void {
scheduler.flags &= ~SchedulerFlags.EnabledMounting;
} | the_stack |
import * as vscode from 'vscode';
import { JackBase } from './jack';
import { JobTreeItem, JobTreeItemType } from './jobTree';
import { ext } from './extensionVariables';
import { withProgressOutputParallel } from './utils';
import { NodeTreeItem } from './nodeTree';
import { SelectionFlows } from './selectionFlows';
export class BuildJack extends JackBase {
static JobBuild = class {
public build: any;
public job: any;
};
constructor() {
super('Build Jack', 'extension.jenkins-jack.build');
ext.context.subscriptions.push(vscode.commands.registerCommand('extension.jenkins-jack.build.abort', async (item?: any | JobTreeItem | NodeTreeItem, items?: any[]) => {
if (item instanceof JobTreeItem) {
items = !items ? [item] : items.filter((item: JobTreeItem) => JobTreeItemType.Build === item.type);
} else if (item instanceof NodeTreeItem) {
// HACKERY: For every NodeTreeItem "executor", parse the job name and build number
// from the build "url"
items = (items ?? [item]).map((i: any) => {
return this.getJobBuildFromUrl(i.executor.currentExecutable.url);
});
} else {
let job = await SelectionFlows.jobs(undefined, false);
if (undefined === job) { return; }
let builds = await SelectionFlows.builds(job, (build: any) => build.building, true);
if (undefined === builds) { return; }
items = builds.map((b: any) => { return { job: job, build: b }; } );
}
if (undefined === items) { return; }
let buildNames = items.map((i: any) => `${i.job.fullName}: #${i.build.number}`);
let r = await this.showInformationModal(
`Are you sure you want to abort these builds?\n\n${buildNames.join('\n')}`,
{ title: "Yes"} );
if (undefined === r) { return undefined; }
let output = await withProgressOutputParallel('Build Jack Output(s)', items, async (item) => {
await ext.connectionsManager.host.client.build.stop(item.job.fullName, item.build.number);
return `Abort signal sent to ${item.job.fullName}: #${item.build.number}`;
});
this.outputChannel.clear();
this.outputChannel.show();
this.outputChannel.appendLine(output);
ext.jobTree.refresh();
ext.nodeTree.refresh(2);
}));
ext.context.subscriptions.push(vscode.commands.registerCommand('extension.jenkins-jack.build.delete', async (item?: any | JobTreeItem, items?: JobTreeItem[]) => {
if (item instanceof JobTreeItem) {
items = !items ? [item] : items.filter((item: JobTreeItem) => JobTreeItemType.Build === item.type);
}
else {
let job = await SelectionFlows.jobs();
if (undefined === job) { return; }
let builds = await SelectionFlows.builds(job, undefined, true, 'Select a build');
if (undefined === builds) { return; }
items = builds.map((b: any) => { return { job: job, build: b }; } );
}
if (undefined === items) { return; }
let buildNames = items.map((i: any) => `${i.job.fullName}: #${i.build.number}`);
let r = await this.showInformationModal(
`Are you sure you want to delete these builds?\n\n${buildNames.join('\n')}`,
{ title: "Yes"} );
if (undefined === r) { return undefined; }
let output = await withProgressOutputParallel('Build Jack Output(s)', items, async (item) => {
await ext.connectionsManager.host.deleteBuild(item.job, item.build.number);
return `Deleted build ${item.job.fullName}: #${item.build.number}`;
});
this.outputChannel.clear();
this.outputChannel.show();
this.outputChannel.appendLine(output);
ext.jobTree.refresh();
}));
ext.context.subscriptions.push(vscode.commands.registerCommand('extension.jenkins-jack.build.downloadLog', async (item?: any | JobTreeItem, items?: JobTreeItem[] | any[]) => {
let targetItems: any[] = null;
if (item instanceof JobTreeItem && null != items) {
targetItems = items.filter((item: JobTreeItem) => JobTreeItemType.Build === item.type).map((i: any) => {
return { job: i.job, build: i.build };
});
}
else if (item instanceof JobTreeItem) {
targetItems = [{ job: item.job, build: item.build }];
}
else if (item instanceof NodeTreeItem) {
// Filter only on non-idle executor tree items
targetItems = !items ? [item] : items.filter((i: NodeTreeItem) => i.executor && !i.executor.idle);
// HACK?: Because Jenkins queue api doesn't have a strong link to an executor's build,
// we must extract the job/build information from the url.
// @ts-ignore
targetItems = targetItems.map((i: any) => { return this.getJobBuildFromUrl(i.executor.currentExecutable.url); });
}
await this.downloadLog(targetItems);
}));
ext.context.subscriptions.push(vscode.commands.registerCommand('extension.jenkins-jack.build.downloadReplayScript', async (item?: any | JobTreeItem, items?: JobTreeItem[] | any[]) => {
let targetItems: any[] = null;
if (item instanceof JobTreeItem && null != items) {
targetItems = items.filter((item: JobTreeItem) => JobTreeItemType.Build === item.type).map((i: any) => {
return { job: i.job, build: i.build };
});
}
else if (item instanceof JobTreeItem) {
targetItems = [{ job: item.job, build: item.build }];
}
else if (item instanceof NodeTreeItem) {
// Filter only on non-idle executor tree items
targetItems = !items ? [item] : items.filter((i: NodeTreeItem) => i.executor && !i.executor.idle);
// HACK?: Because Jenkins queue api doesn't have a strong link to an executor's build,
// we must extract the job/build information from the url.
// @ts-ignore
targetItems = targetItems.map((i: any) => { return this.getJobBuildFromUrl(i.executor.currentExecutable.url); });
}
await this.downloadReplayScript(targetItems);
}));
ext.context.subscriptions.push(vscode.commands.registerCommand('extension.jenkins-jack.build.open', async (item?: any | JobTreeItem, items?: any[]) => {
let urls = [];
if (item instanceof JobTreeItem) {
urls = items ? items.filter((item: JobTreeItem) => JobTreeItemType.Build === item.type).map((i: any) => i.build.url) : [item.build.url];
}
else if (item instanceof NodeTreeItem) {
urls = (items ?? [item]).map((i: any) => { return i.executor.currentExecutable.url });
}
else {
urls = (await SelectionFlows.builds(undefined, undefined, true))?.map((b: any) => b.url);
if (undefined === urls) { return; }
}
for (let url of urls) {
ext.connectionsManager.host.openBrowserAt(url);
}
}));
}
public get commands(): any[] {
return [
{
label: "$(stop) Build: Abort",
description: "Select a job and builds to abort.",
target: () => vscode.commands.executeCommand('extension.jenkins-jack.build.abort')
},
{
label: "$(circle-slash) Build: Delete",
description: "Select a job and builds to delete.",
target: () => vscode.commands.executeCommand('extension.jenkins-jack.build.delete')
},
{
label: "$(cloud-download) Build: Download Log",
description: "Select a job and build to download the log.",
target: () => vscode.commands.executeCommand('extension.jenkins-jack.build.downloadLog')
},
{
label: "$(cloud-download) Build: Download Replay Script",
description: "Pulls a pipeline replay script of a previous build into the editor.",
target: () => vscode.commands.executeCommand('extension.jenkins-jack.build.downloadReplayScript')
},
{
label: "$(browser) Build: Open",
description: "Opens the targeted builds in the user's browser.",
target: () => vscode.commands.executeCommand('extension.jenkins-jack.build.open')
}
];
}
/**
* Downloads a build log for the user by first presenting a list
* of jobs to select from, and then a list of build numbers for
* the selected job.
* @param job Optional job to target. If none, job selection will be presented.
* @param builds Optional builds to target. If none, build selection will be presented.
*/
public async delete(job?: any, builds?: any[]) {
job = job ? job : await SelectionFlows.jobs();
if (undefined === job) { return; }
builds = builds ? builds : await SelectionFlows.builds(job, undefined, true);
if (undefined === builds) { return; }
let items = builds.map((b: any) => { return { job: job, build: b }; } );
let output = await withProgressOutputParallel('Build Jack Output(s)', items, async (item) => {
await ext.connectionsManager.host.deleteBuild(item.job.fullName, item.build.number);
return `Deleted build ${item.job.fullName}: #${item.build.number}`;
});
this.outputChannel.clear();
this.outputChannel.show();
this.outputChannel.appendLine(output);
}
/**
* Downloads a build log for the user by first presenting a list
* of jobs to select from, and then a list of build numbers for
* the selected job.
* @param job Optional job to target. If none, job selection will be presented.
* @param build Optional build to target. If none, build selection will be presented.
*/
public async downloadLog(items?: { job: any, build: any }[]) {
if (!items) {
let job = items ? items[0].job : await SelectionFlows.jobs(undefined, false);
if (undefined === job) { return; }
let builds = items ? items.map((i: any) => i.build) : await SelectionFlows.builds(job, null, true);
if (undefined === builds) { return; }
items = builds.map((b: any) => { return { job: job, build: b } } );
}
// If this is a single item, use this instance's output channel to stream the build.
if (1 === items.length) {
ext.connectionsManager.host.streamBuildOutput(items[0].job.fullName, items[0].build.number, this.outputChannel);
return
}
// If there are multiple items to download, create a new document for each build.
for (let item of items) {
let documentName = `${item.job.fullName.replaceAll('/', '-')}-${item.build.number}`;
let outputPanel = ext.outputPanelProvider.get(documentName);
// Stream it. Stream it until the editor crashes.
ext.connectionsManager.host.streamBuildOutput(item.job.fullName, item.build.number, outputPanel);
}
}
public async downloadReplayScript(items?: { job?: any, build?: any }[]) {
if (!items) {
let job = items ? items[0].job : await SelectionFlows.jobs(undefined, false);
if (undefined === job) { return; }
let builds = items ? items.map((i: any) => i.build) : await SelectionFlows.builds(job, null, true);
if (undefined === builds) { return; }
items = builds.map((b: any) => { return { job: job, build: b } } );
}
await Promise.all(items.map(async (item: any) => {
let script = await ext.connectionsManager.host.getReplayScript(item.job, item.build);
if (undefined === script) { return; }
let doc = await vscode.workspace.openTextDocument({
content: script,
language: 'groovy'
});
await vscode.window.showTextDocument(doc);
}));
}
private getJobBuildFromUrl(url: string) {
let jenkinsUri = ext.connectionsManager.host.connection.uri;
url = url.replace(`${jenkinsUri}/`, '');
url = url.replace(/job\//g, '');
let urlParts = url.split('/').filter((c: string) => c !== '' );
return {
job: { fullName: urlParts.slice(0, -1).join('/') },
build: { number: urlParts.slice(-1)[0] }
};
}
} | the_stack |
import React, {
memo,
ReactNode,
useCallback,
useMemo,
useRef,
useState,
MouseEvent,
useEffect,
useContext
} from 'react';
import moment, { Moment } from 'moment';
import { TDate } from '@z-r/calendar/types/interface';
import useUncontrolled from 'src/hooks/useUncontrolled';
import useLocale from 'src/components/LocaleProvider/useLocale';
import ControllerContext from 'src/components/Form/ControllerContext';
import useDidMount from 'src/hooks/useDidMount';
import isArray from 'src/utils/isArray';
import isNumber from 'src/utils/isNumber';
import pick from 'src/utils/pick';
import Picker, { RangePickerRef } from './RangePicker';
import LOCALE from './locale/zh_CN';
import { isRangeDateValid } from './utils';
import { RangeSelect, RangeDateSeparator, RangeContainer, SRangeInputWrap } from './style';
import { TShortcut } from './Footer';
interface RangeProps {
/** 当前值,受控 */
value?: [TDate | null, TDate | null];
/** 默认值,非受控 */
defaultValue?: [TDate | null, TDate | null];
/** 修改回调,返回 moment 对象数组 */
onChange?: (v: [Moment | null, Moment | null]) => void;
/** 初始化回调函数,传入 option 的情况下会输出 option 对应的值,配合 option 或者 defaultOption 使用 */
onInitialChange?: (v: [Moment | null, Moment | null]) => void;
/** 选项 */
options?: {
label: ReactNode;
value: string;
disabled?: boolean;
range?: {
start?: TDate;
end?: TDate;
};
}[];
/** 当前选项,受控 */
option?: string;
/** 默认选项,非受控 */
defaultOption?: string;
/** 选项变化回调 */
onOptionChange?: (option: string) => void;
/**
* @deprecated 不传入 options 即可隐藏
* 隐藏快捷选项
*/
hideOptions?: boolean;
/** 是否可为空 */
nullable?: [boolean | undefined, boolean | undefined] | [boolean | undefined] | [];
/** 输入和展示的字符串格式,为数组时,第一个用作展示 */
format?: string | string[];
/**
* @deprecated 使用 format 替换
* 展示格式,会传入 DatePicker 和 Month 中(按照 type)
*/
display?: {
date?: {
/** @deprecated 设置日期展示格式,使用 format 替换 */
format?: string;
/** @deprecated 是否展示日期选择,仅时间选择需求使用 TimePicker 替换 */
show?: boolean;
};
/** 设置为 false,隐藏时 */
hour?: boolean;
/** 设置为 false,隐藏分 */
minute?: boolean;
/** 设置为 false,隐藏秒 */
second?: boolean;
range?: {
/** @deprecated 新版无用 */
format?: string;
};
};
/** 自定义规则 */
rules?: {
range?: [TDate | void, TDate | void];
maxRange?: any;
minRange?: any;
};
/** 状态 */
status?: 'default' | 'error';
/** placeholder */
placeholder?: [string | undefined, string | undefined] | [string | undefined] | [];
/** picker 类型 */
type?: 'date' | 'month';
/** 面板快捷内容 */
shortcuts?: [TShortcut[] | null, TShortcut[] | null] | [TShortcut[] | null];
/** 控件尺寸 */
size?: 'sm' | 'md' | 'lg';
/** 是否禁用 */
disabled?: boolean;
/** 弹出层的 z-index */
zIndex?: number;
/** 自定义默认选项 props */
selectProps?: any;
/** 自定义时间选择框弹出层props */
popoverProps?: any;
/** 自定义渲染 */
customRender?: {
/** 自定义渲染只读时(非自定义选项)的展示内容(时间区域) */
readonlyDisplay?: (value: [TDate | null, TDate | null]) => ReactNode;
};
/**
* @ignore
* 自定义 datePicker 的 props
*/
// datePickerProps?: any;
/** 提示信息,展示在时间选择弹窗中 */
rangeTip?: ReactNode;
/** @ignore */
locale?: typeof LOCALE;
}
type RangeValue = [TDate | null, TDate | null];
type CallbackRangeValue = [Moment | null, Moment | null];
const formatValue = (v: TDate | null, nullable = false, defaultV: TDate) => {
return v == null ? (nullable ? null : moment(+defaultV)) : moment(+v);
};
const formatRangeValue = (
value: RangeValue,
nullable: RangeProps['nullable'] = [],
d: TDate
): [Moment | null, Moment | null] => {
return [formatValue(value[0], nullable[0], d), formatValue(value[1], nullable[1], d)];
};
const getDateFromOption = (option: TDate | any) => {
if (option === null) return null;
if (moment.isDate(option) || moment.isMoment(option) || isNumber(option)) {
return moment(option);
} else {
return moment().add(option);
}
};
const getValueFromOption = (options: RangeProps['options'] = [], optionValue: string): CallbackRangeValue => {
const option = options.find(option => option.value === optionValue);
const { range = {} } = option || {};
const s = getDateFromOption(range.start);
const e = getDateFromOption(range.end);
return [s, e];
};
const Range = ({
options: _options,
option: _option,
defaultOption,
onOptionChange: _onOptionChange,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
hideOptions,
value: _value,
defaultValue,
onChange: _onChange,
onInitialChange,
nullable,
size = 'md',
display = {},
format,
rules = {},
type,
disabled,
zIndex,
locale: _locale,
selectProps,
popoverProps,
rangeTip,
status,
placeholder,
shortcuts,
customRender,
...rest
}: RangeProps) => {
const d = useMemo(() => new Date(), []);
const [activeS, setActiveS] = useState(false);
const [activeE, setActiveE] = useState(false);
const locale = useLocale(LOCALE, 'DatePicker', _locale);
const [option, onOptionChange] = useUncontrolled(_option, defaultOption || 'custom', _onOptionChange);
const options = useMemo(
() =>
_options
? _options.concat({
label: locale.custom,
value: 'custom'
})
: [],
[_options, locale.custom]
);
const [value, onChange, updateValueWithoutCallOnChange] = useUncontrolled<RangeValue, CallbackRangeValue>(
_value,
defaultValue || [null, null],
_onChange
);
const [cacheValue, setCacheValue] = useState(() => formatRangeValue(value, nullable, d));
const [rangeError, setRangeError] = useState<string>();
const inputRefS = useRef<RangePickerRef>();
const inputRefE = useRef<RangePickerRef>();
const { status: contextStatus } = useContext(ControllerContext);
const readonly = option !== 'custom';
const [nullableS, nullableE] = isArray(nullable) ? nullable : [];
const precision = type === 'month' ? 'month' : null;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { range: rangeDisplay, ...pickerDisplay } = display;
const [shortcutsS, shortcutsE] = isArray(shortcuts) ? shortcuts : [];
useDidMount(() => {
const [valueS, valueE] = isArray(value) ? value : [null, null];
let initialValue: CallbackRangeValue;
if (option !== 'custom') {
initialValue = getValueFromOption(options, option);
} else {
initialValue = [formatValue(valueS, nullableS, d), formatValue(valueE, nullableE, d)];
}
onInitialChange && onInitialChange(initialValue);
updateValueWithoutCallOnChange(initialValue);
});
const handleStartChange = useCallback(
(value: Moment | null) => {
const [, valueE] = cacheValue;
const newValue: CallbackRangeValue = [value, valueE];
const rangeDateValidResult = isRangeDateValid(newValue, rules, precision);
if (rangeDateValidResult !== true) {
setRangeError(rangeDateValidResult);
inputRefE.current && inputRefE.current.focus();
} else {
setRangeError(undefined);
onChange(newValue);
}
setCacheValue(newValue);
},
[onChange, precision, rules, cacheValue]
);
const handleEndChange = useCallback(
(value: Moment | null) => {
const [valueS] = cacheValue;
const newValue: CallbackRangeValue = [valueS, value];
const rangeDateValidResult = isRangeDateValid(newValue, rules, precision);
if (rangeDateValidResult !== true) {
setRangeError(rangeDateValidResult);
inputRefS.current && inputRefS.current.focus();
} else {
setRangeError(undefined);
onChange(newValue);
}
setCacheValue(newValue);
},
[onChange, precision, rules, cacheValue]
);
const handleOptionChange = useCallback(
(value: string) => {
if (value !== 'custom') onChange(getValueFromOption(options, value));
onOptionChange(value);
},
[onChange, onOptionChange, options]
);
const handleStartActiveChange = useCallback((active: boolean) => setActiveS(active), []);
const handleEndActiveChange = useCallback((active: boolean) => setActiveE(active), []);
const handleInputMouseDown = useCallback((e: MouseEvent) => {
if (e.target === e.currentTarget) e.preventDefault();
}, []);
useEffect(() => {
if (activeS || activeE) return;
setCacheValue(formatRangeValue(value, nullable, d));
}, [activeE, activeS, d, nullable, value]);
const rangeErrorTip = locale[`${rangeError}Tip` as keyof typeof LOCALE];
const sharedPickerProps = {
size,
format,
display: pickerDisplay,
disabled,
popoverProps,
zIndex,
type,
readonly,
tip: rangeTip,
error: rangeErrorTip,
rules
};
const [valueS, valueE] = cacheValue;
const [placeholderS = locale.placeholderRangeStart, placeholderE = locale.placeholderRangeEnd] = isArray(
placeholder
)
? placeholder
: [];
return (
<RangeContainer {...rest} disabled={disabled}>
{!!options.length && (
<RangeSelect
{...selectProps}
options={options.map(option => pick(option, ['label', 'value', 'disabled']))}
size={size}
value={option}
disabled={disabled}
onChange={handleOptionChange}
/>
)}
{readonly && customRender?.readonlyDisplay ? (
customRender.readonlyDisplay(cacheValue)
) : (
<SRangeInputWrap
size={size}
disabled={disabled}
focused={activeS || activeE}
readonly={readonly}
onMouseDown={handleInputMouseDown}
status={status || contextStatus}
>
<Picker
value={valueS}
onChange={handleStartChange}
nullable={nullableS}
prefix
ref={inputRefS}
onActiveChange={handleStartActiveChange}
placeholder={placeholderS}
shortcuts={shortcutsS}
footerTip={locale.chooseTipRangeStart}
{...sharedPickerProps}
/>
<RangeDateSeparator />
<Picker
value={valueE}
onChange={handleEndChange}
nullable={nullableE}
ref={inputRefE}
onActiveChange={handleEndActiveChange}
placeholder={placeholderE}
shortcuts={shortcutsE}
footerTip={locale.chooseTipRangeEnd}
{...sharedPickerProps}
/>
</SRangeInputWrap>
)}
</RangeContainer>
);
};
export default memo(Range); | the_stack |
import { useMutation, useQuery } from "@apollo/client";
import { Field, Formik } from "formik";
import { useRouter } from "next/router";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Grid,
Link,
List,
ListItem,
ListItemText,
makeStyles,
Typography,
} from "@material-ui/core";
import React, { FC, useState } from "react";
import { QUERY_PROJECTS_FOR_USER } from "../../apollo/queries/project";
import { CREATE_TABLE } from "../../apollo/queries/table";
import { TableSchemaKind } from "../../apollo/types/globalTypes";
import { ProjectsForUser, ProjectsForUserVariables } from "../../apollo/types/ProjectsForUser";
import { CreateTable, CreateTableVariables } from "../../apollo/types/CreateTable";
import useMe from "../../hooks/useMe";
import { toURLName, toBackendName } from "../../lib/names";
import { Form, handleSubmitMutation, SelectField as FormikSelectField, TextField as FormikTextField } from "../formik";
import SubmitControl from "../forms/SubmitControl";
import FormikCodeEditor from "components/formik/CodeEditor";
import { removeRedirectAfterAuth } from "lib/authRedirect";
import FormikCheckbox from "components/formik/Checkbox";
import FormikRadioGroup from "components/formik/RadioGroup";
import VSpace from "components/VSpace";
import Collapse from "components/Collapse";
import EXAMPLE_SCHEMAS from "lib/exampleSchemas";
import SchemaEditorFooter from "./SchemaEditorFooter";
import { makeTableAs, makeTableHref } from "./urls";
const useStyles = makeStyles((theme) => ({
list: {
width: "100%",
paddingTop: theme.spacing(0),
paddingBottom: theme.spacing(0),
},
link: {
cursor: "pointer",
},
}));
interface Project {
organization: { name: string };
name: string;
displayName?: string;
}
interface Props {
preselectedProject?: Project;
}
const CreateTableView: FC<Props> = ({ preselectedProject }) => {
const me = useMe();
const router = useRouter();
const classes = useStyles();
const [examplesDialog, setExamplesDialog] = useState(false);
const [createTable] = useMutation<CreateTable, CreateTableVariables>(CREATE_TABLE, {
onCompleted: (data) => {
if (data?.createTable) {
router.replace(makeTableHref(data.createTable), makeTableAs(data.createTable), { shallow: true });
}
},
});
const { data, loading, error } = useQuery<ProjectsForUser, ProjectsForUserVariables>(QUERY_PROJECTS_FOR_USER, {
variables: { userID: me?.personalUserID || "" },
skip: !me,
});
if (typeof window !== "undefined") {
removeRedirectAfterAuth();
}
const initialValues = {
project: data?.projectsForUser?.length ? (preselectedProject ? preselectedProject : data.projectsForUser[0]) : null,
name: "",
schemaKind: TableSchemaKind.GraphQL,
schema: "",
useLog: true,
useIndex: true,
useWarehouse: true,
isLogRetentionFinite: "false",
isIndexRetentionFinite: "false",
isWarehouseRetentionFinite: "false",
logRetentionHours: "",
indexRetentionHours: "",
warehouseRetentionHours: "",
};
return (
<Formik
initialStatus={error?.message}
initialValues={initialValues}
onSubmit={async (values, actions) =>
handleSubmitMutation(
values,
actions,
createTable({
variables: {
input: {
organizationName: toBackendName(values.project?.organization.name || ""),
projectName: toBackendName(values.project?.name || ""),
tableName: toBackendName(values.name),
schemaKind: values.schemaKind,
schema: values.schema,
allowManualWrites: true,
useLog: values.useLog,
useIndex: values.useIndex,
useWarehouse: values.useWarehouse,
logRetentionSeconds:
values.logRetentionHours !== "" ? Number(values.logRetentionHours) * 60 * 60 : null,
indexRetentionSeconds:
values.indexRetentionHours !== "" ? Number(values.indexRetentionHours) * 60 * 60 : null,
warehouseRetentionSeconds:
values.warehouseRetentionHours !== "" ? Number(values.warehouseRetentionHours) * 60 * 60 : null,
},
},
})
)
}
>
{({ values, setFieldValue, isSubmitting, status }) => (
<Form title="Create table">
<Typography gutterBottom>
Tables are how you store data in Beneath. You can replay and subscribe to tables, run OLAP queries with SQL,
and look up specific records by key. Learn more about tables in the{" "}
<Link href="https://about.beneath.dev/docs/concepts/">Concepts</Link> docs.
</Typography>
<Typography>
You may also be interested in:
<ul>
<li>
<Link href="https://about.beneath.dev/docs/quick-starts/create-table/">
How to create a real-time table from Python
</Link>
</li>
<li>
<Link href="https://about.beneath.dev/docs/quick-starts/publish-pandas-dataframe/">
How to publish a Pandas DataFrame
</Link>
</li>
</ul>
</Typography>
{/* TEMPORARY: Hide this dropdown while there's only one option */}
{/* <Grid container>
<Grid item xs={6} sm={4} md={3}>
<Field
name="schemaKind"
validate={(kind?: string) => {
if (!kind) {
return "Select a schema kind for the table";
}
}}
component={FormikSelectField}
label="Schema language"
required
disableClearable
options={[TableSchemaKind.GraphQL]}
/>
</Grid>
</Grid> */}
<Field
name="schema"
component={FormikCodeEditor}
label="GraphQL schema"
required
multiline
rows={20}
language={"graphql"}
helperText={
<>
Tables need a predefined schema. Check out the{" "}
<Link href="https://about.beneath.dev/docs/reading-writing-data/schema-definition/" target="_blank">
schema docs
</Link>{" "}
or start with an{" "}
<Link onClick={() => setExamplesDialog(true)} className={classes.link}>
example schema
</Link>
.
</>
}
/>
<SchemaEditorFooter schemaKind={values.schemaKind} schema={values.schema} />
<Dialog open={examplesDialog} onBackdropClick={() => setExamplesDialog(false)} maxWidth="xs" fullWidth>
<DialogTitle>
Load example schema
<Typography variant="body2">Select a template to modify</Typography>
</DialogTitle>
<DialogContent>
<List className={classes.list}>
{EXAMPLE_SCHEMAS.map((exampleSchema) => (
<ListItem
key={exampleSchema.name}
button
onClick={() => {
setFieldValue("schema", exampleSchema.schema);
setExamplesDialog(false);
}}
>
<ListItemText primary={exampleSchema.name} secondary={exampleSchema.language} />
</ListItem>
))}
</List>
</DialogContent>
<DialogActions>
<Button onClick={() => setExamplesDialog(false)}>Close</Button>
</DialogActions>
</Dialog>
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<Field
name="project"
validate={(proj?: Project) => {
if (!proj) {
return "Select a project for the table";
}
}}
component={FormikSelectField}
label="Project"
required
loading={loading}
options={data?.projectsForUser || []}
getOptionLabel={(option: Project) => `${toURLName(option.organization.name)}/${toURLName(option.name)}`}
getOptionSelected={(option: Project, value: Project) => {
return option.name === value.name;
}}
/>
</Grid>
<Grid item xs={12} sm={6}>
<Field
name="name"
validate={(val: string) => {
if (!val || val.length < 3 || val.length > 40) {
return "Table names should be between 3 and 40 characters long";
}
if (!val.match(/^[_\-a-z][_\-a-z0-9]+$/)) {
return "Table names should consist of lowercase letters, numbers, underscores and dashes (cannot start with a number)";
}
}}
component={FormikTextField}
label="Table name"
required
/>
</Grid>
</Grid>
<Typography>
URL preview: https://beneath.dev/
{values.project?.organization.name ? toURLName(values.project?.organization.name) : "USERNAME"}/
{values.project?.name ? toURLName(values.project?.name) : "PROJECT"}/table:
{values.name ? toURLName(values.name) : ""}
</Typography>
<VSpace units={3} />
<Collapse title="Advanced settings">
<Field name="useIndex" component={FormikCheckbox} type="checkbox" label="Enable indexing" />
<Field name="useWarehouse" component={FormikCheckbox} type="checkbox" label="Enable SQL (warehouse)" />
<Field
name="isLogRetentionFinite"
component={FormikRadioGroup}
label="Log retention"
required
options={[
{ value: "false", label: "Infinite" },
{ value: "true", label: "Finite" },
]}
row
/>
{values.isLogRetentionFinite === "true" && (
<Grid item xs={12} sm={6} md={3}>
<Field
name="logRetentionHours"
component={FormikTextField}
label="Hours"
required
validate={(val: string) => {
if (!val.match(/^[0-9]*$/)) {
return "Numbers only";
}
}}
/>
</Grid>
)}
{values.useIndex && (
<>
<Field
name="isIndexRetentionFinite"
component={FormikRadioGroup}
label="Index retention"
required
options={[
{ value: "false", label: "Infinite" },
{ value: "true", label: "Finite" },
]}
row
/>
{values.isIndexRetentionFinite === "true" && (
<Grid item xs={12} sm={6} md={3}>
<Field
name="indexRetentionHours"
component={FormikTextField}
label="Hours"
required
validate={(val: string) => {
if (!val.match(/^[0-9]*$/)) {
return "Numbers only";
}
}}
/>
</Grid>
)}
</>
)}
{values.useWarehouse && (
<>
<Field
name="isWarehouseRetentionFinite"
component={FormikRadioGroup}
label="Warehouse retention"
required
options={[
{ value: "false", label: "Infinite" },
{ value: "true", label: "Finite" },
]}
row
/>
{values.isWarehouseRetentionFinite === "true" && (
<Grid item xs={12} sm={6} md={3}>
<Field
name="warehouseRetentionHours"
component={FormikTextField}
label="Hours"
required
validate={(val: string) => {
if (!val.match(/^[0-9]*$/)) {
return "Numbers only";
}
}}
/>
</Grid>
)}
</>
)}
</Collapse>
<SubmitControl
label="Create table"
errorAlert={status}
disabled={isSubmitting || !values.schema || !values.name}
/>
</Form>
)}
</Formik>
);
};
export default CreateTableView; | the_stack |
import { select as d3Select } from "d3-selection";
import "d3-transition";
import { Field, Grid } from "./Database";
import { } from "./Platform";
import { PropertyExt } from "./PropertyExt";
import { debounce, textRect, TextRect, textSize, TextSize } from "./Utility";
import "../src/Widget.css";
export type IPrimative = boolean | number | string | object;
export type IFieldType = "boolean" | "number" | "string" | "dataset" | "object" | "any";
export interface InputField {
id: string;
type: IFieldType;
multi?: boolean;
default?: IPrimative | InputField[];
children?: InputField[];
}
export interface IPos {
x: number;
y: number;
}
export interface ISize {
width: number;
height: number;
}
export interface BBox {
x: number;
y: number;
width: number;
height: number;
}
export interface DataMetaT {
min?: number;
max?: number;
mean?: number;
stdDev?: number;
sum?: number;
}
let widgetID = 0;
export abstract class Widget extends PropertyExt {
_idSeed: string;
protected _tag: string;
protected _isRootNode: boolean = true;
protected _db = new Grid();
protected _pos;
protected _prevPos;
protected _size;
protected _widgetScale;
protected _visible;
protected _display;
protected _dataMeta: DataMetaT = {};
protected _target: null | HTMLElement | SVGElement;
protected _placeholderElement;
protected _parentWidget;
protected _element;
protected _renderCount;
protected _overlayElement;
constructor() {
super();
this._class = Object.getPrototypeOf(this)._class;
this._id = this._idSeed + widgetID++;
this._db = new Grid();
this._pos = { x: 0, y: 0 };
this._size = { width: 0, height: 0 };
this._widgetScale = 1;
this._visible = true;
this._target = null;
this._placeholderElement = null;
this._parentWidget = null;
this._element = d3Select(null);
this._renderCount = 0;
if ((window as any).__hpcc_debug) {
if ((window as any).g_all === undefined) {
(window as any).g_all = {};
}
(window as any).g_all[this._id] = this;
}
if ((window as any).__hpcc_theme) {
this.applyTheme((window as any).__hpcc_theme);
}
}
importJSON(_: string | object): this {
this._db.json(_);
return this;
}
export(_: "JSON" | "CSV" | "TSV" = "JSON") {
switch (_) {
case "CSV":
return this._db.csv();
case "TSV":
return this._db.tsv();
case "JSON":
default:
return this._db.json();
}
}
leakCheck(newNode) {
const context = this;
const watchArray = [newNode];
const destructObserver = new MutationObserver(function (mutations) {
let leaks = false;
mutations.forEach(function (mutation) {
for (let i = 0; i < mutation.removedNodes.length; ++i) {
const node = mutation.removedNodes.item(i);
if (watchArray.indexOf(node) >= 0 && context._target) {
leaks = true;
destructObserver.disconnect();
}
}
});
if (leaks) {
console.log("leak: " + context.id() + " - " + context.classID() + "\t\twidget.target(null); was not called for this widget before it was removed from the page.");
}
});
let pNode = newNode.parentNode;
while (pNode) {
destructObserver.observe(pNode, { childList: true });
watchArray.push(pNode);
pNode = pNode.parentNode;
}
}
renderCount(): number {
return this._renderCount;
}
// Implementation ---
columns(): string[];
columns(_: string[], asDefault?: boolean): this;
columns(_?: string[], asDefault?: boolean): string[] | this {
if (!arguments.length) return this._db.legacyColumns();
this._db.legacyColumns(_, asDefault);
return this;
}
protected columnIdx(column: string): number {
return this.columns().indexOf(column);
}
protected cellIdxFunc<T>(colIdx: number, defValue?: T): (row: any) => T {
return colIdx < 0 ? () => defValue : row => row[colIdx];
}
protected cellFunc<T>(column: string, defValue?: T): (row: any) => T {
return this.cellIdxFunc<T>(this.columnIdx(column), defValue);
}
parsedData() {
return this._db.parsedData();
}
formattedData() {
return this._db.formattedData();
}
data(): any;
data(_: any): this;
data(_?: any): any | this {
if (!arguments.length) return this._db.legacyData();
this._db.legacyData(_);
return this;
}
cloneData() {
return this.data().map(function (row) { return row.slice(0); });
}
flattenData(columns: string[] = this.columns(), data: any = this.data()) {
const retVal = [];
data.forEach(function (row, rowIdx) {
columns.filter(function (_col, idx) { return idx > 0; }).forEach(function (_col, idx) {
const val = row[idx + 1];
if (typeof val !== "undefined") {
const newItem = {
rowIdx,
colIdx: idx + 1,
label: row[0],
value: val
};
retVal.push(newItem);
}
}, this);
}, this);
return retVal;
}
rowToObj(row: any[]): object {
if (!row) return {};
const retVal: any = {};
this.fields().forEach(function (field, idx) {
retVal[field.label_default() || field.label()] = row[idx];
});
if (row.length === this.columns().length + 1) {
retVal.__lparam = row[this.columns().length];
}
return retVal;
}
pos(): IPos;
pos(_: IPos): this;
pos(_?: IPos): IPos | this {
if (!arguments.length) return this._pos;
this._pos = _;
if (this._overlayElement) {
this._overlayElement
.attr("transform", "translate(" + _.x + "," + _.y + ")scale(" + this._widgetScale + ")")
;
}
return this;
}
x(): number;
x(_): this;
x(_?): number | this {
if (!arguments.length) return this._pos.x;
this.pos({ x: _, y: this._pos.y });
return this;
}
y(): number;
y(_): this;
y(_?): number | this {
if (!arguments.length) return this._pos.y;
this.pos({ x: this._pos.x, y: _ });
return this;
}
size(): ISize;
size(_): this;
size(_?): ISize | this {
if (!arguments.length) return this._size;
this._size = _;
if (this._overlayElement) {
this._overlayElement
.attr("width", _.width)
.attr("height", _.height)
;
}
return this;
}
width(): number;
width(_): this;
width(_?): number | this {
if (!arguments.length) return this._size.width;
this.size({ width: _, height: this._size.height });
return this;
}
height(): number;
height(_): this;
height(_?): number | this {
if (!arguments.length) return this._size.height;
this.size({ width: this._size.width, height: _ });
return this;
}
resize(size?: ISize, delta: ISize = { width: 0, height: 0 }) {
let width;
let height;
if (size && size.width && size.height) {
width = size.width;
height = size.height;
} else {
const style = window.getComputedStyle(this._target, null);
width = parseFloat(style.getPropertyValue("width")) - delta.width;
height = parseFloat(style.getPropertyValue("height")) - delta.height;
}
this.size({
width,
height
});
return this;
}
scale(): number;
scale(_): Widget;
scale(_?): number | Widget {
if (!arguments.length) return this._widgetScale;
this._widgetScale = _;
if (this._overlayElement) {
this._overlayElement
.attr("transform", "translate(" + _.x + "," + _.y + ")scale(" + this._widgetScale + ")")
;
}
return this;
}
visible(): boolean;
visible(_): this;
visible(_?): boolean | this {
if (!arguments.length) return this._visible;
this._visible = _;
if (this._element) {
this._element
.style("visibility", this._visible ? null : "hidden")
.style("opacity", this._visible ? null : 0)
;
}
return this;
}
display(): boolean;
display(_): this;
display(_?): boolean | this {
if (!arguments.length) return this._display;
this._display = _;
if (this._element) {
this._element.style("display", this._display ? null : "none");
}
return this;
}
dataMeta(): DataMetaT;
dataMeta(_): this;
dataMeta(_?): DataMetaT | this {
if (!arguments.length) return this._dataMeta;
this._dataMeta = _;
return this;
}
private _appData = new Object({});
appData(key: string): any;
appData(key: string, value: any): this;
appData(key: string, value?: any): any | this {
if (arguments.length < 2) return this._appData[key];
this._appData[key] = value;
return this;
}
calcSnap(snapSize) {
function snap(x, gridSize) {
function snapDelta(x2, gridSize2) {
let dx = x2 % gridSize2;
if (Math.abs(dx) > gridSize2 - Math.abs(dx)) {
dx = (gridSize2 - Math.abs(dx)) * (dx < 0 ? 1 : -1);
}
return dx;
}
return x - snapDelta(x, gridSize);
}
const l = snap(this._pos.x - this._size.width / 2, snapSize);
const t = snap(this._pos.y - this._size.height / 2, snapSize);
const r = snap(this._pos.x + this._size.width / 2, snapSize);
const b = snap(this._pos.y + this._size.height / 2, snapSize);
const w = r - l;
const h = b - t;
return [{ x: l + w / 2, y: t + h / 2 }, { width: w, height: h }];
}
// DOM/SVG Node Helpers ---
toWidget(domNode): Widget | null {
if (!domNode) {
return null;
}
const element = d3Select(domNode);
if (element) {
const widget = element.datum();
if (widget && widget instanceof Widget) {
return widget;
}
}
return null;
}
parentOverlay() {
return null;
}
locateParentWidget(domNode?): Widget | null {
domNode = domNode || (this._target ? this._target.parentNode : null);
if (domNode) {
const widget = this.toWidget(domNode);
if (widget) {
return widget;
} else if (domNode.parentNode) {
return this.locateParentWidget(domNode.parentNode);
}
}
return null;
}
locateSVGNode(domNode): SVGSVGElement | null {
if (!domNode) {
return null;
}
if (domNode.tagName === "svg") {
return domNode;
}
return this.locateSVGNode(domNode.parentNode);
}
locateOverlayNode() {
let widget = this.locateParentWidget(this._target);
while (widget) {
const retVal = widget.parentOverlay();
if (retVal) {
return retVal;
}
widget = this.locateParentWidget(widget._target.parentNode);
}
return null;
}
locateAncestor(classID): Widget | null {
return this.locateClosestAncestor([classID]);
}
locateClosestAncestor(classIDArr): Widget | null {
let widget = this.locateParentWidget(this._target);
while (widget) {
if (classIDArr.indexOf(widget.classID()) !== -1) {
return widget;
}
widget = this.locateParentWidget(widget._target.parentNode);
}
return null;
}
getAbsolutePos(domNode, w, h) {
const root = this.locateSVGNode(domNode);
if (!root) {
return null;
}
let pos = root.createSVGPoint();
const ctm = domNode.getCTM();
pos = pos.matrixTransform(ctm);
const retVal: any = {
x: pos.x,
y: pos.y
};
if (w !== undefined && h !== undefined) {
let size = root.createSVGPoint();
size.x = w;
size.y = h;
size = size.matrixTransform(ctm);
retVal.width = size.x - pos.x;
retVal.height = size.y - pos.y;
}
return retVal;
}
hasOverlay() {
return this._overlayElement;
}
syncOverlay() {
if (this._size.width && this._size.height) {
const newPos = this.getAbsolutePos(this._overlayElement.node(), this._size.width, this._size.height);
if (newPos && (!this._prevPos || newPos.x !== this._prevPos.x || newPos.y !== this._prevPos.y || newPos.width !== this._prevPos.width || newPos.height !== this._prevPos.height)) {
const xScale = newPos.width / this._size.width;
const yScale = newPos.height / this._size.height;
this._placeholderElement
.style("left", newPos.x - (newPos.width / xScale) / 2 + "px")
.style("top", newPos.y - (newPos.height / yScale) / 2 + "px")
.style("width", newPos.width / xScale + "px")
.style("height", newPos.height / yScale + "px")
;
const transform = "scale(" + xScale + "," + yScale + ")";
this._placeholderElement
.style("transform", transform)
.style("-moz-transform", transform)
.style("-ms-transform", transform)
.style("-webkit-transform", transform)
.style("-o-transform", transform)
;
}
this._prevPos = newPos;
}
}
getBBox(refresh = false, round = false): BBox {
return {
x: 0,
y: 0,
width: 0,
height: 0
};
}
textSize(_text: string | string[], fontName: string = "Verdana", fontSize: number = 12, bold: boolean = false): Readonly<TextSize> {
return textSize(_text, fontName, fontSize, bold);
}
textRect(_text: string, fontName: string = "Verdana", fontSize: number = 12, bold: boolean = false): Readonly<TextRect> {
return textRect(_text, fontName, fontSize, bold);
}
element() {
return this._element;
}
node() {
return this._element.node();
}
target(): null | HTMLElement | SVGElement;
target(_: null | string | HTMLElement | SVGElement): this;
target(_?: null | string | HTMLElement | SVGElement): null | HTMLElement | SVGElement | this {
if (!arguments.length) return this._target;
if (this._target && _) {
throw new Error("Target can only be assigned once.");
}
if (_ === null) {
this._target = null;
if (this.renderCount()) {
this.exit();
}
} else if (typeof _ === "string") {
this._target = document.getElementById(_);
} else if (_ instanceof HTMLElement || _ instanceof SVGElement) {
this._target = _;
}
return this;
}
isDOMHidden(): boolean {
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetParent
// Note: Will return false for visible===hidden (which is ok as it still takes up space on the page)
return this._isRootNode && this._placeholderElement.node().offsetParent === null;
}
hasSize() {
return !isNaN(this.width()) && !isNaN(this.height());
}
protected publishedWidgets(): Widget[] {
let widgets = [];
this.publishedProperties(true).forEach(function (meta) {
if (!meta.ext || meta.ext.render !== false) {
switch (meta.type) {
case "widget":
const widget = this[meta.id]();
if (widget) {
widgets.push(widget);
}
break;
case "widgetArray":
widgets = widgets.concat(this[meta.id]());
break;
}
}
}, this);
return widgets;
}
// Render ---
private _prevNow = 0;
render(callback?: (w: Widget) => void) {
if ((window as any).__hpcc_debug) {
const now = Date.now();
if (now - this._prevNow < 500) {
console.log("Double Render: " + (now - this._prevNow) + " - " + this.id() + " - " + this.classID());
}
this._prevNow = now;
}
callback = callback || function () { };
if (!this._placeholderElement || !this.visible() || this.isDOMHidden() || !this.hasSize()) {
callback(this);
return this;
}
if (this._placeholderElement) {
if (!this._tag)
throw new Error("No DOM tag specified");
const elements = this._placeholderElement.selectAll("#" + this._id).data([this], function (d) { return d._id; });
elements.enter().append(this._tag)
.classed(this._class, true)
.attr("id", this._id)
// .attr("opacity", 0.50) // Uncomment to debug position offsets ---
.each(function (context2) {
context2._element = d3Select(this);
context2.enter(this, context2._element);
if ((window as any).__hpcc_debug) {
context2.leakCheck(this);
}
})
.merge(elements)
.each(function (context2) {
const element = d3Select(this);
const classed = context2.classed();
for (const key in classed) {
element.classed(key, classed[key]);
}
context2.preUpdate(this, context2._element);
context2.update(this, context2._element);
context2.postUpdate(this, context2._element);
})
;
elements.exit()
.each(function (context2) {
d3Select(this).datum(null);
context2.exit(this, context2._element);
})
.remove()
;
this._renderCount++;
}
// ASync Render Contained Widgets ---
const widgets = this.publishedWidgets();
const context = this;
switch (widgets.length) {
case 0:
callback(this);
break;
case 1:
widgets[0].render(function () {
callback(context);
});
break;
default:
let renderCount = widgets.length;
widgets.forEach(function (widget, _idx) {
setTimeout(function () {
widget.render(function () {
if (--renderCount === 0) {
callback(context);
}
});
}, 0);
});
break;
}
return this;
}
renderPromise(): Promise<Widget> {
return new Promise((resolve, reject) => {
this.render((w: Widget) => {
resolve(w);
});
});
}
private _lazyRender = debounce(function (debouncedCallback?: (w: Widget) => void) {
this.render(debouncedCallback);
}, 100);
lazyRender(callback?: (w: Widget) => void): this {
this._lazyRender(callback);
return this;
}
animationFrameRender(): this {
if (requestAnimationFrame) {
requestAnimationFrame(() => {
this.render();
});
} else {
// Not a real replacement for requestAnimationFrame ---
this.renderPromise();
}
return this;
}
enter(_domNode: HTMLElement, _element) { }
preUpdate(_domNode: HTMLElement, _element) { }
update(_domNode: HTMLElement, _element) { }
postUpdate(_domNode: HTMLElement, _element) { }
exit(_domNode?: HTMLElement, _element?) {
this.publishedWidgets().forEach(w => w.target(null));
}
}
Widget.prototype._class += " common_Widget";
export interface Widget {
fields(): Field[];
fields(_: Field[]): this;
classed(classID: string): boolean;
classed(classID: string, _: boolean): this;
classed(): { [classID: string]: boolean };
classed(_: { [classID: string]: boolean }): this;
}
Widget.prototype._idSeed = "_w";
Widget.prototype.publishProxy("fields", "_db", "fields");
Widget.prototype.publish("classed", {}, "object", "HTML Classes", null, { tags: ["Private"] });
const origClassed = Widget.prototype.classed;
Widget.prototype.classed = function (this: Widget, str_obj?: string | { [classID: string]: boolean }, _?: boolean) {
if (typeof str_obj === "string") {
if (arguments.length === 1) return origClassed.call(this)[str_obj];
const classed = origClassed.call(this);
origClassed.call(this, { ...classed, [str_obj]: _ });
return this;
}
return origClassed.apply(this, arguments);
}; | the_stack |
'use strict';
import { Store as RelayModernStore, RecordSource, Environment as RelayModernEnvironment } from '../src';
import { Network as RelayNetwork, Observable as RelayObservable, createOperationDescriptor, getSingularSelector } from 'relay-runtime';
import { createPersistedStorage } from './Utils';
const { generateAndCompile } = require('./TestCompiler');
const RelayRecordSource = {
create: (data?: any) => new RecordSource({ storage: createPersistedStorage(), initialState: { ...data } }),
};
const nullthrows = require('fbjs/lib/nullthrows');
const { getHandleStorageKey } = require('relay-runtime/lib/store/RelayStoreUtils');
describe('@connection', () => {
let callbacks;
let complete;
let dataSource;
let environment;
let error;
let fetch;
let fragment;
let next;
let operation;
let paginationQuery;
let query;
let source;
let store;
beforeEach(async () => {
jest.resetModules();
//jest.mock('warning');
jest.spyOn(console, 'warn').mockImplementation(() => undefined);
({ FeedbackQuery: query, FeedbackFragment: fragment, PaginationQuery: paginationQuery } = generateAndCompile(`
query FeedbackQuery($id: ID!) {
node(id: $id) {
...FeedbackFragment
}
}
query PaginationQuery(
$id: ID!
$count: Int!
$cursor: ID!
) {
node(id: $id) {
...FeedbackFragment @arguments(count: $count, cursor: $cursor)
}
}
fragment FeedbackFragment on Feedback @argumentDefinitions(
count: {type: "Int", defaultValue: 2},
cursor: {type: "ID"}
) {
id
comments(after: $cursor, first: $count, orderby: "date") @connection(
key: "FeedbackFragment_comments"
filters: ["orderby"]
) {
edges {
node {
id
}
}
}
}
`));
const variables = {
id: '<feedbackid>',
};
operation = createOperationDescriptor(query, variables);
complete = jest.fn();
error = jest.fn();
next = jest.fn();
callbacks = { complete, error, next };
fetch = jest.fn((_query, _variables, _cacheConfig) => {
return RelayObservable.create((sink) => {
dataSource = sink;
});
});
source = RelayRecordSource.create();
store = new RelayModernStore(source);
environment = new RelayModernEnvironment({
network: RelayNetwork.create(fetch),
store,
});
await environment.hydrate();
});
it('publishes initial results to the store', () => {
const operationSnapshot = environment.lookup(operation.fragment);
const operationCallback = jest.fn();
environment.subscribe(operationSnapshot, operationCallback);
environment.execute({ operation }).subscribe(callbacks);
const payload = {
data: {
node: {
__typename: 'Feedback',
id: '<feedbackid>',
comments: {
edges: [
{
cursor: 'cursor-1',
node: {
__typename: 'Comment',
id: 'node-1',
},
},
{
cursor: 'cursor-2',
node: {
__typename: 'Comment',
id: 'node-2',
},
},
],
pageInfo: {
hasNextPage: true,
endCursor: 'cursor-2',
},
},
},
},
};
dataSource.next(payload);
jest.runAllTimers();
expect(operationCallback).toBeCalledTimes(1);
const nextOperationSnapshot = operationCallback.mock.calls[0][0];
expect(nextOperationSnapshot.isMissingData).toBe(false);
expect(nextOperationSnapshot.data).toEqual({
node: {
__id: '<feedbackid>',
__fragments: {
FeedbackFragment: {},
},
__fragmentOwner: operation.request,
},
});
const selector = nullthrows(
getSingularSelector(fragment, nextOperationSnapshot.data ? nextOperationSnapshot.data.node : undefined),
);
const snapshot = environment.lookup(selector);
expect(snapshot.isMissingData).toBe(false);
expect(snapshot.data).toEqual({
id: '<feedbackid>',
comments: {
edges: [
{ cursor: 'cursor-1', node: { id: 'node-1', __typename: 'Comment' } },
{ cursor: 'cursor-2', node: { id: 'node-2', __typename: 'Comment' } },
],
pageInfo: {
hasNextPage: true,
endCursor: 'cursor-2',
},
},
});
});
describe('after initial data has been fetched and subscribed', () => {
let callback;
beforeEach(() => {
environment.execute({ operation }).subscribe(callbacks);
const payload = {
data: {
node: {
__typename: 'Feedback',
id: '<feedbackid>',
comments: {
edges: [
{
cursor: 'cursor-1',
node: {
__typename: 'Comment',
id: 'node-1',
},
},
{
cursor: 'cursor-2',
node: {
__typename: 'Comment',
id: 'node-2',
},
},
],
pageInfo: {
hasNextPage: true,
endCursor: 'cursor-2',
},
},
},
},
};
dataSource.next(payload);
dataSource.complete();
fetch.mockClear();
jest.runAllTimers();
const operationSnapshot = environment.lookup(operation.fragment);
const selector = nullthrows(getSingularSelector(fragment, operationSnapshot.data ? operationSnapshot.data.node : undefined));
const snapshot = environment.lookup(selector);
callback = jest.fn();
environment.subscribe(snapshot, callback);
});
it('updates when paginated', () => {
const paginationOperation = createOperationDescriptor(paginationQuery, {
id: '<feedbackid>',
count: 2,
cursor: 'cursor-2',
});
environment.execute({ operation: paginationOperation }).subscribe({});
const paginationPayload = {
data: {
node: {
__typename: 'Feedback',
id: '<feedbackid>',
comments: {
edges: [
{
cursor: 'cursor-3',
node: {
__typename: 'Comment',
id: 'node-3',
},
},
{
cursor: 'cursor-4',
node: {
__typename: 'Comment',
id: 'node-4',
},
},
],
pageInfo: {
hasNextPage: true,
endCursor: 'cursor-4',
},
},
},
},
};
dataSource.next(paginationPayload);
jest.runAllTimers();
expect(callback).toBeCalledTimes(1);
const nextSnapshot = callback.mock.calls[0][0];
expect(nextSnapshot.isMissingData).toBe(false);
expect(nextSnapshot.data).toEqual({
id: '<feedbackid>',
comments: {
edges: [
{ cursor: 'cursor-1', node: { id: 'node-1', __typename: 'Comment' } },
{ cursor: 'cursor-2', node: { id: 'node-2', __typename: 'Comment' } },
{ cursor: 'cursor-3', node: { id: 'node-3', __typename: 'Comment' } },
{ cursor: 'cursor-4', node: { id: 'node-4', __typename: 'Comment' } },
],
pageInfo: {
hasNextPage: true,
endCursor: 'cursor-4',
},
},
});
});
it('updates when paginated if the connection field is unset but the record exists', () => {
const variables = {
id: '<feedbackid>',
count: 2,
cursor: 'cursor-2',
};
environment.commitUpdate((storeProxy) => {
const handleField = paginationQuery.operation.selections
.find((selection) => selection.kind === 'LinkedField' && selection.name === 'node')
.selections.find((selection) => selection.kind === 'InlineFragment' && selection.type === 'Feedback')
.selections.find((selection) => selection.kind === 'LinkedHandle' && selection.name === 'comments');
expect(handleField).toBeTruthy();
const handleKey = getHandleStorageKey(handleField, variables);
const feedback = storeProxy.get('<feedbackid>');
expect(feedback).toBeTruthy();
if (feedback != null) {
feedback.setValue(null, handleKey);
}
});
expect(callback).toBeCalledTimes(1);
const nextSnapshot = callback.mock.calls[0][0];
expect(nextSnapshot.isMissingData).toBe(false);
expect(nextSnapshot.data).toEqual({
id: '<feedbackid>',
comments: null,
});
const paginationOperation = createOperationDescriptor(paginationQuery, variables);
environment.execute({ operation: paginationOperation }).subscribe({});
const paginationPayload = {
data: {
node: {
__typename: 'Feedback',
id: '<feedbackid>',
comments: {
edges: [
{
cursor: 'cursor-3',
node: {
__typename: 'Comment',
id: 'node-3',
},
},
{
cursor: 'cursor-4',
node: {
__typename: 'Comment',
id: 'node-4',
},
},
],
pageInfo: {
hasNextPage: true,
endCursor: 'cursor-4',
},
},
},
},
};
dataSource.next(paginationPayload);
jest.runAllTimers();
expect(callback).toBeCalledTimes(2);
const nextSnapshot2 = callback.mock.calls[1][0];
expect(nextSnapshot2.isMissingData).toBe(false);
expect(nextSnapshot2.data).toEqual({
id: '<feedbackid>',
comments: {
edges: [
{ cursor: 'cursor-1', node: { id: 'node-1', __typename: 'Comment' } },
{ cursor: 'cursor-2', node: { id: 'node-2', __typename: 'Comment' } },
{ cursor: 'cursor-3', node: { id: 'node-3', __typename: 'Comment' } },
{ cursor: 'cursor-4', node: { id: 'node-4', __typename: 'Comment' } },
],
pageInfo: {
hasNextPage: true,
endCursor: 'cursor-4',
},
},
});
});
});
}); | the_stack |
import { range, Viewport } from "adapter/viewport"
import { chance } from "_/helpers"
import {
mockViewportConfiguration,
mockViewportContext
} from "_/mocks/adapter/viewport"
import { mockQuerySelector } from "_/mocks/vendor/document"
/* ----------------------------------------------------------------------------
* Tests
* ------------------------------------------------------------------------- */
/* Viewport */
describe("Viewport", () => {
/* Viewport configuration and context */
const config = mockViewportConfiguration()
/* Viewport context */
let context: HTMLIFrameElement
/* Setup fixtures */
beforeAll(() => {
fixture.setBase("fixtures")
})
/* Create and attach context */
beforeEach(() => {
context = mockViewportContext()
document.body.appendChild(context)
/* Hack: Internet Explorer doesn't initialize the document for an empty
iframe, so we have to do it by ourselves, see https://bit.ly/2GaF6Iw */
context.contentDocument!.write("<body></body>")
})
/* Detach context */
afterEach(() => {
document.body.removeChild(context)
})
/* range */
describe("range", () => {
/* Test: should return first breakpoint */
it("should return first breakpoint", () => {
const breakpoints = range(config.breakpoints, "mobile")
expect(breakpoints).toEqual(jasmine.any(Array))
expect(breakpoints.length).toEqual(1)
expect(breakpoints[0]).toEqual(config.breakpoints[0])
})
/* Test: should return middle breakpoint */
it("should return middle breakpoint", () => {
const breakpoints = range(config.breakpoints, "tablet")
expect(breakpoints).toEqual(jasmine.any(Array))
expect(breakpoints.length).toEqual(1)
expect(breakpoints[0]).toEqual(config.breakpoints[1])
})
/* Test: should return last breakpoint */
it("should return last breakpoint", () => {
const breakpoints = range(config.breakpoints, "screen")
expect(breakpoints).toEqual(jasmine.any(Array))
expect(breakpoints.length).toEqual(1)
expect(breakpoints[0]).toEqual(config.breakpoints[2])
})
/* Test: should return first to first breakpoint */
it("should return first to first breakpoint", () => {
const breakpoints = range(config.breakpoints, "mobile", "mobile")
expect(breakpoints).toEqual(jasmine.any(Array))
expect(breakpoints.length).toEqual(1)
expect(breakpoints[0]).toEqual(config.breakpoints[0])
})
/* Test: should return first to last breakpoint */
it("should return first to last breakpoint", () => {
const breakpoints = range(config.breakpoints, "mobile", "screen")
expect(breakpoints).toEqual(jasmine.any(Array))
expect(breakpoints.length).toEqual(3)
expect(breakpoints).toEqual(config.breakpoints)
})
/* Test: should return last to last breakpoint */
it("should return last to last breakpoint", () => {
const breakpoints = range(config.breakpoints, "screen", "screen")
expect(breakpoints).toEqual(jasmine.any(Array))
expect(breakpoints.length).toEqual(1)
expect(breakpoints[0]).toEqual(config.breakpoints[2])
})
/* Test: should throw on invalid breakpoint */
it("should throw on invalid breakpoint", () => {
expect(() => {
range([], "invalid")
}).toThrow(
new ReferenceError("Invalid breakpoint: 'invalid'"))
})
})
/* #constructor */
describe("#constructor", () => {
/* Test: should set configuration */
it("should set configuration", () => {
const viewport = new Viewport(config, window)
expect(viewport.config).toBe(config)
})
/* Test: should resolve context */
it("should resolve context", () => {
const querySelector = mockQuerySelector(context)
const viewport = new Viewport(config, window)
expect(viewport.context).toBe(context)
expect(querySelector)
.toHaveBeenCalledWith(config.context)
})
/* Test: should throw on missing context */
it("should throw on missing context", () => {
// tslint:disable-next-line no-null-keyword
mockQuerySelector(null)
expect(() => {
new Viewport(config, window)
}).toThrow(new TypeError(`No match for selector: '${config.context}'`))
})
})
/* #load */
describe("#load", () => {
/* Test: should set context source */
it("should set context source", done => {
const viewport = new Viewport(config, window)
viewport.load("/debug.html", () => {
expect(context.src).toContain("/debug.html")
done()
})
})
/* Test: should set context source and return promise */
it("should set context source and return promise", done => {
const viewport = new Viewport(config, window)
viewport.load("/debug.html")
.then(() => {
expect(context.src).toContain("/debug.html")
done()
})
})
})
/* #offset */
describe("#offset", () => {
/* Test: should set horizontal offset */
it("should set horizontal offset", () => {
const viewport = new Viewport(config, window)
const x = chance.integer({ min: 10, max: 100 })
context.contentDocument!.body.style.width =
`${context.contentWindow!.innerWidth + x}px`
context.contentDocument!.body.style.height =
`${context.contentWindow!.innerHeight}px`
viewport.offset(x)
expect(viewport.context.contentWindow!.pageXOffset).toEqual(x)
})
/* Test: should set horizontal and vertical offset */
it("should set horizontal and vertical offset", () => {
const viewport = new Viewport(config, window)
const x = chance.integer({ min: 10, max: 100 })
const y = chance.integer({ min: 10, max: 100 })
context.contentDocument!.body.style.width =
`${context.contentWindow!.innerWidth + x}px`
context.contentDocument!.body.style.height =
`${context.contentWindow!.innerHeight + y}px`
viewport.offset(x, y)
expect(viewport.context.contentWindow!.pageXOffset).toEqual(x)
expect(viewport.context.contentWindow!.pageYOffset).toEqual(y)
})
})
/* #set */
describe("#set", () => {
/* Test: should set width */
it("should set width", () => {
const viewport = new Viewport(config, window)
const width = chance.integer({ min: 100, max: 400 })
viewport.set(width)
expect(context.style.width).toEqual(`${width}px`)
expect(context.style.height).toEqual("")
})
/* Test: should set width and height */
it("should set width and height", () => {
const viewport = new Viewport(config, window)
const width = chance.integer({ min: 100, max: 400 })
const height = chance.integer({ min: 100, max: 400 })
viewport.set(width, height)
expect(context.style.width).toEqual(`${width}px`)
expect(context.style.height).toEqual(`${height}px`)
})
/* Test: should set width and height of breakpoint */
it("should set width and height of breakpoint", () => {
const viewport = new Viewport(config, window)
viewport.set("tablet")
expect(context.style.width)
.toEqual(`${config.breakpoints[1].size.width}px`)
expect(context.style.height)
.toEqual(`${config.breakpoints[1].size.height}px`)
})
/* Test: should force layout */
it("should force layout", () => {
spyOn(context.contentDocument!.body, "getBoundingClientRect")
const viewport = new Viewport(config, window)
const width = chance.integer({ min: 100, max: 400 })
viewport.set(width)
expect(context.contentDocument!.body.getBoundingClientRect)
.toHaveBeenCalled()
})
/* Test: should throw on invalid breakpoint */
it("should throw on invalid breakpoint", () => {
const viewport = new Viewport(config, window)
expect(() => {
viewport.set("invalid")
}).toThrow(new ReferenceError("Invalid breakpoint: 'invalid'"))
})
/* Test: should throw on invalid width */
it("should throw on invalid width", () => {
const viewport = new Viewport(config, window)
const width = chance.integer({ min: -400, max: -100 })
expect(() => {
viewport.set(width)
}).toThrow(new TypeError(`Invalid breakpoint width: ${width}`))
})
/* Test: should throw on invalid width and height */
it("should throw on invalid width and height", () => {
const viewport = new Viewport(config, window)
const width = chance.integer({ min: -400, max: -100 })
const height = chance.integer({ min: -400, max: -100 })
expect(() => {
viewport.set(width, height)
}).toThrow(new TypeError(`Invalid breakpoint width: ${width}`))
})
/* Test: should throw on invalid width */
it("should throw on invalid height", () => {
const viewport = new Viewport(config, window)
const width = chance.integer({ min: 100, max: 400 })
const height = chance.integer({ min: -400, max: -100 })
expect(() => {
viewport.set(width, height)
}).toThrow(new TypeError(`Invalid breakpoint height: ${height}`))
})
})
/* #reset */
describe("#reset", () => {
/* Test: should reset width and height */
it("should reset offset", () => {
const viewport = new Viewport(config, window)
const x = chance.integer({ min: 10, max: 100 })
const y = chance.integer({ min: 10, max: 100 })
context.contentDocument!.body.style.width =
`${context.contentWindow!.innerWidth + x}`
context.contentDocument!.body.style.height =
`${context.contentWindow!.innerHeight + y}`
viewport.offset(x, y)
viewport.reset()
expect(viewport.context.contentWindow!.pageXOffset).toEqual(0)
expect(viewport.context.contentWindow!.pageYOffset).toEqual(0)
})
/* Test: should reset width and height */
it("should reset width and height", () => {
const viewport = new Viewport(config, window)
const width = chance.integer({ min: 100, max: 400 })
const height = chance.integer({ min: 100, max: 400 })
viewport.set(width, height)
viewport.reset()
expect(context.style.width).toEqual("")
expect(context.style.height).toEqual("")
})
/* Test: should force layout */
it("should force layout", () => {
spyOn(context.contentDocument!.body, "getBoundingClientRect")
const viewport = new Viewport(config, window)
viewport.reset()
expect(context.contentDocument!.body.getBoundingClientRect)
.toHaveBeenCalled()
})
})
/* #between */
describe("#between", () => {
/* Test: should invoke callback on breakpoints */
it("should invoke callback on breakpoints", () => {
const cb = jasmine.createSpy("callback")
const viewport = new Viewport(config, window)
viewport.between("mobile", "tablet", cb)
expect(cb).toHaveBeenCalledWith("mobile")
expect(cb).toHaveBeenCalledWith("tablet")
expect(cb).not.toHaveBeenCalledWith("screen")
})
/* Test: should invoke callback returning promise on breakpoints */
it("should invoke callback returning promise on breakpoints", async () => {
const cb = jasmine.createSpy("callback")
.and.returnValue(Promise.resolve())
const viewport = new Viewport(config, window)
await viewport.between("tablet", "screen", cb)
expect(cb).not.toHaveBeenCalledWith("mobile")
expect(cb).toHaveBeenCalledWith("tablet")
expect(cb).toHaveBeenCalledWith("screen")
})
})
/* #each */
describe("#each", () => {
/* Load fixtures */
beforeEach(() => {
fixture.load("default.html")
})
/* Test: should invoke callback on breakpoints */
it("should invoke callback on breakpoints", () => {
const cb = jasmine.createSpy("callback")
const viewport = new Viewport(config, window)
viewport.each(cb)
expect(cb).toHaveBeenCalledWith("mobile")
expect(cb).toHaveBeenCalledWith("tablet")
expect(cb).toHaveBeenCalledWith("screen")
})
/* Test: should set width and height of breakpoint */
it("should set width and height of breakpoint", () => {
const cb = jasmine.createSpy("callback")
.and.callFake((name: string) => {
const style = window.getComputedStyle(document.body)
switch (name) {
case "mobile": expect(style.fontSize).toEqual("16px"); break
case "tablet": expect(style.fontSize).toEqual("14px"); break
case "screen": expect(style.fontSize).toEqual("12px"); break
}
})
const viewport = new Viewport({ ...config, context: "#context" }, window)
viewport.each(cb)
expect(cb.calls.count()).toEqual(3)
})
})
/* #from */
describe("#from", () => {
/* Test: should invoke callback on breakpoints */
it("should invoke callback on breakpoints", () => {
const cb = jasmine.createSpy("callback")
const viewport = new Viewport(config, window)
viewport.from("tablet", cb)
expect(cb).not.toHaveBeenCalledWith("mobile")
expect(cb).toHaveBeenCalledWith("tablet")
expect(cb).toHaveBeenCalledWith("screen")
})
})
/* #to */
describe("#to", () => {
/* Test: should invoke callback on breakpoints */
it("should invoke callback on breakpoints", () => {
const cb = jasmine.createSpy("callback")
const viewport = new Viewport(config, window)
viewport.to("tablet", cb)
expect(cb).toHaveBeenCalledWith("mobile")
expect(cb).toHaveBeenCalledWith("tablet")
expect(cb).not.toHaveBeenCalledWith("screen")
})
})
}) | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormSalesOrder_Field_Service_Information {
interface Header extends DevKit.Controls.IHeader {
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
/** Shows whether the order is active, submitted, fulfilled, canceled, or invoiced. Only active orders can be edited. */
StateCode: DevKit.Controls.OptionSet;
/** Select the order's status. */
StatusCode: DevKit.Controls.OptionSet;
/** Shows the total amount due, calculated as the sum of the products, discounts, freight, and taxes for the order. */
TotalAmount: DevKit.Controls.Money;
}
interface tab_order_line_items_Sections {
ProductLinesSection: DevKit.Controls.Section;
ServiceLinesSection: DevKit.Controls.Section;
totals: DevKit.Controls.Section;
}
interface tab_summary_tab_Sections {
BillingPrintSetup: DevKit.Controls.Section;
order_line_items_section_4: DevKit.Controls.Section;
SocialPanTab: DevKit.Controls.Section;
Summary: DevKit.Controls.Section;
}
interface tab_order_line_items extends DevKit.Controls.ITab {
Section: tab_order_line_items_Sections;
}
interface tab_summary_tab extends DevKit.Controls.ITab {
Section: tab_summary_tab_Sections;
}
interface Tabs {
order_line_items: tab_order_line_items;
summary_tab: tab_summary_tab;
}
interface Body {
Tab: Tabs;
/** Shows the complete Bill To address. */
BillTo_Composite: DevKit.Controls.String;
/** Type the primary contact name at the customer's billing address. */
BillTo_ContactName: DevKit.Controls.String;
/** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */
CustomerId: DevKit.Controls.Lookup;
/** Enter the date that all or part of the order was shipped to the customer. */
DateFulfilled: DevKit.Controls.Date;
/** Type additional information to describe the order, such as the products or services offered or details about the customer's product preferences. */
Description: DevKit.Controls.String;
/** Type the discount amount for the order if the customer is eligible for special savings. */
DiscountAmount: DevKit.Controls.Money;
/** Type the discount rate that should be applied to the Detail Amount field to include additional savings for the customer in the order. */
DiscountPercentage: DevKit.Controls.Decimal;
/** Type the cost of freight or shipping for the products included in the order for use in calculating the Total Amount field. */
FreightAmount: DevKit.Controls.Money;
/** Select the freight terms to make sure shipping charges are processed correctly. */
FreightTermsCode: DevKit.Controls.OptionSet;
/** Select whether prices specified on the invoice are locked from any further updates. */
IsPriceLocked: DevKit.Controls.Boolean;
/** Customer Account associated with this Order */
msdyn_Account: DevKit.Controls.Lookup;
/** Internal use only */
msdyn_ordertype: DevKit.Controls.OptionSet;
/** Type a descriptive name for the order. */
Name: DevKit.Controls.String;
notescontrol: DevKit.Controls.Note;
/** Choose the related opportunity so that the data for the order and opportunity are linked for reporting and analytics. */
OpportunityId: DevKit.Controls.Lookup;
/** Shows the order number for customer reference and to use in search. The number cannot be modified. */
OrderNumber: DevKit.Controls.String;
/** Select the payment terms to indicate when the customer needs to pay the total amount. */
PaymentTermsCode: DevKit.Controls.OptionSet;
/** Choose the price list associated with this record to make sure the products associated with the campaign are offered at the correct prices. */
PriceLevelId: DevKit.Controls.Lookup;
/** Choose the related quote so that order data and quote data are linked for reporting and analytics. */
QuoteId: DevKit.Controls.Lookup;
/** Enter the delivery date requested by the customer for all products in the order. */
RequestDeliveryBy: DevKit.Controls.Date;
/** Select a shipping method for deliveries sent to this address. */
ShippingMethodCode: DevKit.Controls.OptionSet;
/** Shows the complete Ship To address. */
ShipTo_Composite: DevKit.Controls.String;
/** Shows whether the order is active, submitted, fulfilled, canceled, or invoiced. Only active orders can be edited. */
StateCode: DevKit.Controls.OptionSet;
/** Select the order's status. */
StatusCode: DevKit.Controls.OptionSet;
/** Shows the total amount due, calculated as the sum of the products, discounts, freight, and taxes for the order. */
TotalAmount: DevKit.Controls.Money;
/** Shows the total product amount for the order, minus any discounts. This value is added to freight and tax amounts in the calculation for the total amount due for the order. */
TotalAmountLessFreight: DevKit.Controls.Money;
/** Shows the sum of all existing and write-in products included on the order, based on the specified price list and quantities. */
TotalLineItemAmount: DevKit.Controls.Money;
/** Shows the Tax amounts specified on all products included in the order, included in the Total Amount due calculation for the order. */
TotalTax: DevKit.Controls.Money;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.Controls.Lookup;
/** Select whether the products included in the order should be shipped to the specified address or held until the customer calls with further pick-up or delivery instructions. */
WillCall: DevKit.Controls.Boolean;
}
interface Navigation {
nav_msdyn_salesorder_msdyn_orderinvoicingdate_Order: DevKit.Controls.NavigationItem,
nav_msdyn_salesorder_msdyn_orderinvoicingsetup_Order: DevKit.Controls.NavigationItem,
nav_msdyn_salesorder_msdyn_orderinvoicingsetupdate_Order: DevKit.Controls.NavigationItem,
navProducts: DevKit.Controls.NavigationItem
}
interface Grid {
salesorderdetailsGrid: DevKit.Controls.Grid;
OrderServicesGrid: DevKit.Controls.Grid;
}
}
class FormSalesOrder_Field_Service_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form SalesOrder_Field_Service_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form SalesOrder_Field_Service_Information */
Body: DevKit.FormSalesOrder_Field_Service_Information.Body;
/** The Header section of form SalesOrder_Field_Service_Information */
Header: DevKit.FormSalesOrder_Field_Service_Information.Header;
/** The Navigation of form SalesOrder_Field_Service_Information */
Navigation: DevKit.FormSalesOrder_Field_Service_Information.Navigation;
/** The Grid of form SalesOrder_Field_Service_Information */
Grid: DevKit.FormSalesOrder_Field_Service_Information.Grid;
}
namespace FormSalesOrder_Project_Information {
interface Header extends DevKit.Controls.IHeader {
/** Shows the current state of the project contract. */
msdyn_PSAState: DevKit.Controls.OptionSet;
/** Shows the reason for the project contract status. */
msdyn_PSAStatusReason: DevKit.Controls.OptionSet;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
/** Shows the total amount due, calculated as the sum of the products, discounts, freight, and taxes for the order. */
TotalAmount: DevKit.Controls.Money;
}
interface tab_LinesTab_Sections {
DynamicProperties: DevKit.Controls.Section;
ProductLinesSection: DevKit.Controls.Section;
ProjectLinesSection: DevKit.Controls.Section;
}
interface tab_ProjectPriceListsTab_Sections {
ProjectPriceListsSection: DevKit.Controls.Section;
}
interface tab_summary_tab_Sections {
addresses: DevKit.Controls.Section;
BillingPrintSetup: DevKit.Controls.Section;
shipping_information: DevKit.Controls.Section;
Social_Pane: DevKit.Controls.Section;
suggestionsection: DevKit.Controls.Section;
Summary: DevKit.Controls.Section;
}
interface tab_tab_ContractPerformance_Sections {
tab_ContractPerformance_section_2: DevKit.Controls.Section;
}
interface tab_LinesTab extends DevKit.Controls.ITab {
Section: tab_LinesTab_Sections;
}
interface tab_ProjectPriceListsTab extends DevKit.Controls.ITab {
Section: tab_ProjectPriceListsTab_Sections;
}
interface tab_summary_tab extends DevKit.Controls.ITab {
Section: tab_summary_tab_Sections;
}
interface tab_tab_ContractPerformance extends DevKit.Controls.ITab {
Section: tab_tab_ContractPerformance_Sections;
}
interface Tabs {
LinesTab: tab_LinesTab;
ProjectPriceListsTab: tab_ProjectPriceListsTab;
summary_tab: tab_summary_tab;
tab_ContractPerformance: tab_tab_ContractPerformance;
}
interface Body {
Tab: Tabs;
/** Shows the complete Bill To address. */
BillTo_Composite: DevKit.Controls.String;
/** Type the primary contact name at the customer's billing address. */
BillTo_ContactName: DevKit.Controls.String;
/** Type a name for the customer's billing address, such as "Headquarters" or "Field office", to identify the address. */
BillTo_Name: DevKit.Controls.String;
/** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */
CustomerId: DevKit.Controls.Lookup;
/** Select the freight terms to make sure shipping charges are processed correctly. */
FreightTermsCode: DevKit.Controls.OptionSet;
/** Select whether prices specified on the invoice are locked from any further updates. */
IsPriceLocked: DevKit.Controls.Boolean;
/** User responsible for managing the account referenced by this contract. */
msdyn_AccountManagerId: DevKit.Controls.Lookup;
/** Organizational unit responsible for this contract. */
msdyn_ContractOrganizationalUnitId: DevKit.Controls.Lookup;
/** Internal use only */
msdyn_ordertype: DevKit.Controls.OptionSet;
/** Shows the reason for the project contract status. */
msdyn_PSAStatusReason: DevKit.Controls.OptionSet;
/** Type a descriptive name for the order. */
Name: DevKit.Controls.String;
notescontrol: DevKit.Controls.Note;
/** Choose the related opportunity so that the data for the order and opportunity are linked for reporting and analytics. */
OpportunityId: DevKit.Controls.Lookup;
/** Shows the order number for customer reference and to use in search. The number cannot be modified. */
OrderNumber: DevKit.Controls.String;
/** Select the payment terms to indicate when the customer needs to pay the total amount. */
PaymentTermsCode: DevKit.Controls.OptionSet;
/** Choose the price list associated with this record to make sure the products associated with the campaign are offered at the correct prices. */
PriceLevelId: DevKit.Controls.Lookup;
/** Choose the related quote so that order data and quote data are linked for reporting and analytics. */
QuoteId: DevKit.Controls.Lookup;
/** Enter the delivery date requested by the customer for all products in the order. */
RequestDeliveryBy: DevKit.Controls.Date;
/** Select a shipping method for deliveries sent to this address. */
ShippingMethodCode: DevKit.Controls.OptionSet;
/** Shows the complete Ship To address. */
ShipTo_Composite: DevKit.Controls.String;
/** Shows whether the order is active, submitted, fulfilled, canceled, or invoiced. Only active orders can be edited. */
StateCode: DevKit.Controls.OptionSet;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.Controls.Lookup;
/** Select whether the products included in the order should be shipped to the specified address or held until the customer calls with further pick-up or delivery instructions. */
WillCall: DevKit.Controls.Boolean;
}
interface Navigation {
nav_msdyn_salesorder_msdyn_actual_SalesContract: DevKit.Controls.NavigationItem,
nav_msdyn_salesorder_msdyn_contractlinescheduleofvalue_contract: DevKit.Controls.NavigationItem,
nav_msdyn_salesorder_msdyn_contractperformance_salesorderid: DevKit.Controls.NavigationItem,
nav_msdyn_salesorder_msdyn_orderpricelist_Contract: DevKit.Controls.NavigationItem,
nav_msdyn_salesorder_msdyn_project_salesorderid: DevKit.Controls.NavigationItem,
navConnections: DevKit.Controls.NavigationItem,
navInvoices: DevKit.Controls.NavigationItem,
navProducts: DevKit.Controls.NavigationItem
}
interface Grid {
ProjectContractLines: DevKit.Controls.Grid;
salesorderdetailsGrid: DevKit.Controls.Grid;
ProjectPriceListsSubGrid: DevKit.Controls.Grid;
WebResource_ContractPerformance: DevKit.Controls.Grid;
ContractPerformance_ContractLines: DevKit.Controls.Grid;
ContractPerformance_ProductContractLines: DevKit.Controls.Grid;
}
}
class FormSalesOrder_Project_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form SalesOrder_Project_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form SalesOrder_Project_Information */
Body: DevKit.FormSalesOrder_Project_Information.Body;
/** The Header section of form SalesOrder_Project_Information */
Header: DevKit.FormSalesOrder_Project_Information.Header;
/** The Navigation of form SalesOrder_Project_Information */
Navigation: DevKit.FormSalesOrder_Project_Information.Navigation;
/** The Grid of form SalesOrder_Project_Information */
Grid: DevKit.FormSalesOrder_Project_Information.Grid;
}
namespace FormOrder {
interface tab_newSalesOrder_Sections {
quickOrder_salesinformation: DevKit.Controls.Section;
quickOrder_summary: DevKit.Controls.Section;
}
interface tab_newSalesOrder extends DevKit.Controls.ITab {
Section: tab_newSalesOrder_Sections;
}
interface Tabs {
newSalesOrder: tab_newSalesOrder;
}
interface Body {
Tab: Tabs;
/** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */
CustomerId: DevKit.Controls.Lookup;
/** Type additional information to describe the order, such as the products or services offered or details about the customer's product preferences. */
Description: DevKit.Controls.String;
/** Type a descriptive name for the order. */
Name: DevKit.Controls.String;
/** Choose the related opportunity so that the data for the order and opportunity are linked for reporting and analytics. */
OpportunityId: DevKit.Controls.Lookup;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
/** Choose the price list associated with this record to make sure the products associated with the campaign are offered at the correct prices. */
PriceLevelId: DevKit.Controls.Lookup;
/** Choose the related quote so that order data and quote data are linked for reporting and analytics. */
QuoteId: DevKit.Controls.Lookup;
/** Select the order's status. */
StatusCode: DevKit.Controls.OptionSet;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.Controls.Lookup;
}
}
class FormOrder extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Order
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Order */
Body: DevKit.FormOrder.Body;
}
namespace FormSalesOrder_Project_Quick_Create {
interface tab_tab_1_Sections {
tab_1_column_1_section_1: DevKit.Controls.Section;
tab_1_column_2_section_1: DevKit.Controls.Section;
tab_1_column_3_section_1: DevKit.Controls.Section;
}
interface tab_tab_1 extends DevKit.Controls.ITab {
Section: tab_tab_1_Sections;
}
interface Tabs {
tab_1: tab_tab_1;
}
interface Body {
Tab: Tabs;
/** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */
CustomerId: DevKit.Controls.Lookup;
/** Type additional information to describe the order, such as the products or services offered or details about the customer's product preferences. */
Description: DevKit.Controls.String;
/** Internal use only */
msdyn_ordertype: DevKit.Controls.OptionSet;
/** Type a descriptive name for the order. */
Name: DevKit.Controls.String;
/** Shows the order number for customer reference and to use in search. The number cannot be modified. */
OrderNumber: DevKit.Controls.String;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.Controls.Lookup;
}
}
class FormSalesOrder_Project_Quick_Create extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form SalesOrder_Project_Quick_Create
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form SalesOrder_Project_Quick_Create */
Body: DevKit.FormSalesOrder_Project_Quick_Create.Body;
}
class SalesOrderApi {
/**
* DynamicsCrm.DevKit SalesOrderApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Shows the parent account related to the record. This information is used to link the sales order to the account selected in the Customer field for reporting and analytics. */
AccountId: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the billing address. */
BillTo_AddressId: DevKit.WebApi.GuidValue;
/** Type the city for the customer's billing address. */
BillTo_City: DevKit.WebApi.StringValue;
/** Shows the complete Bill To address. */
BillTo_Composite: DevKit.WebApi.StringValueReadonly;
/** Type the primary contact name at the customer's billing address. */
BillTo_ContactName: DevKit.WebApi.StringValue;
/** Type the country or region for the customer's billing address. */
BillTo_Country: DevKit.WebApi.StringValue;
/** Type the fax number for the customer's billing address. */
BillTo_Fax: DevKit.WebApi.StringValue;
/** Type the first line of the customer's billing address. */
BillTo_Line1: DevKit.WebApi.StringValue;
/** Type the second line of the customer's billing address. */
BillTo_Line2: DevKit.WebApi.StringValue;
/** Type the third line of the billing address. */
BillTo_Line3: DevKit.WebApi.StringValue;
/** Type a name for the customer's billing address, such as "Headquarters" or "Field office", to identify the address. */
BillTo_Name: DevKit.WebApi.StringValue;
/** Type the ZIP Code or postal code for the billing address. */
BillTo_PostalCode: DevKit.WebApi.StringValue;
/** Type the state or province for the billing address. */
BillTo_StateOrProvince: DevKit.WebApi.StringValue;
/** Type the phone number for the customer's billing address. */
BillTo_Telephone: DevKit.WebApi.StringValue;
/** Shows the campaign that the order was created from. */
CampaignId: DevKit.WebApi.LookupValue;
/** Shows the parent contact related to the record. This information is used to link the contract to the contact selected in the Customer field for reporting and analytics. */
ContactId: DevKit.WebApi.LookupValueReadonly;
/** Shows who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
customerid_account: DevKit.WebApi.LookupValue;
customerid_contact: DevKit.WebApi.LookupValue;
/** Enter the date that all or part of the order was shipped to the customer. */
DateFulfilled_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Type additional information to describe the order, such as the products or services offered or details about the customer's product preferences. */
Description: DevKit.WebApi.StringValue;
/** Type the discount amount for the order if the customer is eligible for special savings. */
DiscountAmount: DevKit.WebApi.MoneyValue;
/** Value of the Order Discount Amount in base currency. */
DiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Type the discount rate that should be applied to the Detail Amount field to include additional savings for the customer in the order. */
DiscountPercentage: DevKit.WebApi.DecimalValue;
/** The primary email address for the entity. */
EmailAddress: DevKit.WebApi.StringValue;
/** The default image for the entity. */
EntityImage: DevKit.WebApi.StringValue;
EntityImage_Timestamp: DevKit.WebApi.BigIntValueReadonly;
EntityImage_URL: DevKit.WebApi.StringValueReadonly;
EntityImageId: DevKit.WebApi.GuidValueReadonly;
/** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Type the cost of freight or shipping for the products included in the order for use in calculating the Total Amount field. */
FreightAmount: DevKit.WebApi.MoneyValue;
/** Value of the Freight Amount in base currency. */
FreightAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Select the freight terms to make sure shipping charges are processed correctly. */
FreightTermsCode: DevKit.WebApi.OptionSetValue;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Select whether prices specified on the invoice are locked from any further updates. */
IsPriceLocked: DevKit.WebApi.BooleanValue;
/** Enter the date and time when the order was last submitted to an accounting or ERP system for processing. */
LastBackofficeSubmit_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Contains the date time stamp of the last on hold time. */
LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Shows who last updated the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who last updated the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Customer Account associated with this Order */
msdyn_Account: DevKit.WebApi.LookupValue;
/** User responsible for managing the account referenced by this contract. */
msdyn_AccountManagerId: DevKit.WebApi.LookupValue;
/** Organizational unit responsible for this contract. */
msdyn_ContractOrganizationalUnitId: DevKit.WebApi.LookupValue;
/** Internal use only */
msdyn_ordertype: DevKit.WebApi.OptionSetValue;
/** For internal use only */
msdyn_ProcessStartedOn_TimezoneDateAndTime: DevKit.WebApi.TimezoneDateAndTimeValue;
/** Shows the current state of the project contract. */
msdyn_PSAState: DevKit.WebApi.OptionSetValue;
/** Shows the reason for the project contract status. */
msdyn_PSAStatusReason: DevKit.WebApi.OptionSetValue;
/** Value of the estimated chargeable cost. */
msdyn_TotalChargeableCostRollup: DevKit.WebApi.MoneyValueReadonly;
/** Value of the Total Chargeable Cost in base currency. */
msdyn_totalchargeablecostrollup_Base: DevKit.WebApi.MoneyValueReadonly;
/** Last Updated time of rollup field Total Chargeable Cost. */
msdyn_TotalChargeableCostRollup_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** State of rollup field Total Chargeable Cost. */
msdyn_TotalChargeableCostRollup_State: DevKit.WebApi.IntegerValueReadonly;
/** Total estimated cost that will not be charged to the customer. */
msdyn_TotalNonchargeableCostRollup: DevKit.WebApi.MoneyValueReadonly;
/** Value of the Total Non-chargeable Cost in base currency. */
msdyn_totalnonchargeablecostrollup_Base: DevKit.WebApi.MoneyValueReadonly;
/** Last Updated time of rollup field Total Non-chargeable Cost. */
msdyn_TotalNonchargeableCostRollup_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** State of rollup field Total Non-chargeable Cost. */
msdyn_TotalNonchargeableCostRollup_State: DevKit.WebApi.IntegerValueReadonly;
/** Type a descriptive name for the order. */
Name: DevKit.WebApi.StringValue;
/** Shows the duration in minutes for which the order was on hold. */
OnHoldTime: DevKit.WebApi.IntegerValueReadonly;
/** Choose the related opportunity so that the data for the order and opportunity are linked for reporting and analytics. */
OpportunityId: DevKit.WebApi.LookupValue;
/** Shows the order number for customer reference and to use in search. The number cannot be modified. */
OrderNumber: DevKit.WebApi.StringValue;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Select the payment terms to indicate when the customer needs to pay the total amount. */
PaymentTermsCode: DevKit.WebApi.OptionSetValue;
/** Choose the price list associated with this record to make sure the products associated with the campaign are offered at the correct prices. */
PriceLevelId: DevKit.WebApi.LookupValue;
/** Select the type of pricing error, such as a missing or invalid product, or missing quantity. */
PricingErrorCode: DevKit.WebApi.OptionSetValue;
/** Select the priority so that preferred customers or critical issues are handled quickly. */
PriorityCode: DevKit.WebApi.OptionSetValue;
/** Contains the id of the process associated with the entity. */
ProcessId: DevKit.WebApi.GuidValue;
/** Choose the related quote so that order data and quote data are linked for reporting and analytics. */
QuoteId: DevKit.WebApi.LookupValue;
/** Enter the delivery date requested by the customer for all products in the order. */
RequestDeliveryBy_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Unique identifier of the order. */
SalesOrderId: DevKit.WebApi.GuidValue;
/** Select a shipping method for deliveries sent to this address. */
ShippingMethodCode: DevKit.WebApi.OptionSetValue;
/** Unique identifier of the shipping address. */
ShipTo_AddressId: DevKit.WebApi.GuidValue;
/** Type the city for the customer's shipping address. */
ShipTo_City: DevKit.WebApi.StringValue;
/** Shows the complete Ship To address. */
ShipTo_Composite: DevKit.WebApi.StringValueReadonly;
/** Type the primary contact name at the customer's shipping address. */
ShipTo_ContactName: DevKit.WebApi.StringValue;
/** Type the country or region for the customer's shipping address. */
ShipTo_Country: DevKit.WebApi.StringValue;
/** Type the fax number for the customer's shipping address. */
ShipTo_Fax: DevKit.WebApi.StringValue;
/** Select the freight terms to make sure shipping orders are processed correctly. */
ShipTo_FreightTermsCode: DevKit.WebApi.OptionSetValue;
/** Type the first line of the customer's shipping address. */
ShipTo_Line1: DevKit.WebApi.StringValue;
/** Type the second line of the customer's shipping address. */
ShipTo_Line2: DevKit.WebApi.StringValue;
/** Type the third line of the shipping address. */
ShipTo_Line3: DevKit.WebApi.StringValue;
/** Type a name for the customer's shipping address, such as "Headquarters" or "Field office", to identify the address. */
ShipTo_Name: DevKit.WebApi.StringValue;
/** Type the ZIP Code or postal code for the shipping address. */
ShipTo_PostalCode: DevKit.WebApi.StringValue;
/** Type the state or province for the shipping address. */
ShipTo_StateOrProvince: DevKit.WebApi.StringValue;
/** Type the phone number for the customer's shipping address. */
ShipTo_Telephone: DevKit.WebApi.StringValue;
/** Skip Price Calculation */
SkipPriceCalculation: DevKit.WebApi.OptionSetValue;
/** Choose the service level agreement (SLA) that you want to apply to the sales order record. */
SLAId: DevKit.WebApi.LookupValue;
/** Last SLA that was applied to this sales order. This field is for internal use only. */
SLAInvokedId: DevKit.WebApi.LookupValueReadonly;
SLAName: DevKit.WebApi.StringValueReadonly;
/** Contains the id of the stage where the entity is located. */
StageId: DevKit.WebApi.GuidValue;
/** Shows whether the order is active, submitted, fulfilled, canceled, or invoiced. Only active orders can be edited. */
StateCode: DevKit.WebApi.OptionSetValue;
/** Select the order's status. */
StatusCode: DevKit.WebApi.OptionSetValue;
/** Enter the date when the order was submitted to the fulfillment or shipping center. */
SubmitDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Type the code for the submitted status in the fulfillment or shipping center system. */
SubmitStatus: DevKit.WebApi.IntegerValue;
/** Type additional details or notes about the order for the fulfillment or shipping center. */
SubmitStatusDescription: DevKit.WebApi.StringValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Shows the total amount due, calculated as the sum of the products, discounts, freight, and taxes for the order. */
TotalAmount: DevKit.WebApi.MoneyValue;
/** Value of the Total Amount in base currency. */
TotalAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the total product amount for the order, minus any discounts. This value is added to freight and tax amounts in the calculation for the total amount due for the order. */
TotalAmountLessFreight: DevKit.WebApi.MoneyValue;
/** Value of the Total Pre-Freight Amount in base currency. */
TotalAmountLessFreight_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the total discount amount, based on the discount price and rate entered on the order. */
TotalDiscountAmount: DevKit.WebApi.MoneyValue;
/** Value of the Total Discount Amount in base currency. */
TotalDiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the sum of all existing and write-in products included on the order, based on the specified price list and quantities. */
TotalLineItemAmount: DevKit.WebApi.MoneyValue;
/** Value of the Total Detail Amount in base currency. */
TotalLineItemAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the total of the Manual Discount amounts specified on all products included in the order. This value is reflected in the Detail Amount field on the order and is added to any discount amount or rate specified on the order. */
TotalLineItemDiscountAmount: DevKit.WebApi.MoneyValue;
/** Value of the Total Line Item Discount Amount in base currency. */
TotalLineItemDiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the Tax amounts specified on all products included in the order, included in the Total Amount due calculation for the order. */
TotalTax: DevKit.WebApi.MoneyValue;
/** Value of the Total Tax in base currency. */
TotalTax_Base: DevKit.WebApi.MoneyValueReadonly;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */
TraversedPath: DevKit.WebApi.StringValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
/** Select whether the products included in the order should be shipped to the specified address or held until the customer calls with further pick-up or delivery instructions. */
WillCall: DevKit.WebApi.BooleanValue;
}
}
declare namespace OptionSet {
namespace SalesOrder {
enum FreightTermsCode {
/** 1 */
FOB,
/** 2 */
No_Charge
}
enum msdyn_ordertype {
/** 192350000 */
Item_based,
/** 690970002 */
Service_Maintenance_Based,
/** 192350001 */
Work_based
}
enum msdyn_PSAState {
/** 192350002 */
Active,
/** 192350003 */
Closed,
/** 192350000 */
Draft,
/** 192350001 */
On_hold
}
enum msdyn_PSAStatusReason {
/** 192350006 */
Abandoned,
/** 192350004 */
Completed,
/** 192350003 */
Confirmed,
/** 192350000 */
Draft,
/** 192350001 */
In_review,
/** 192350005 */
Lost,
/** 192350002 */
On_hold
}
enum PaymentTermsCode {
/** 2 */
_2_10_Net_30,
/** 1 */
Net_30,
/** 3 */
Net_45,
/** 4 */
Net_60
}
enum PricingErrorCode {
/** 36 */
Base_Currency_Attribute_Overflow,
/** 37 */
Base_Currency_Attribute_Underflow,
/** 1 */
Detail_Error,
/** 27 */
Discount_Type_Invalid_State,
/** 33 */
Inactive_Discount_Type,
/** 3 */
Inactive_Price_Level,
/** 20 */
Invalid_Current_Cost,
/** 28 */
Invalid_Discount,
/** 26 */
Invalid_Discount_Type,
/** 19 */
Invalid_Price,
/** 17 */
Invalid_Price_Level_Amount,
/** 34 */
Invalid_Price_Level_Currency,
/** 18 */
Invalid_Price_Level_Percentage,
/** 9 */
Invalid_Pricing_Code,
/** 30 */
Invalid_Pricing_Precision,
/** 7 */
Invalid_Product,
/** 29 */
Invalid_Quantity,
/** 24 */
Invalid_Rounding_Amount,
/** 23 */
Invalid_Rounding_Option,
/** 22 */
Invalid_Rounding_Policy,
/** 21 */
Invalid_Standard_Cost,
/** 15 */
Missing_Current_Cost,
/** 14 */
Missing_Price,
/** 2 */
Missing_Price_Level,
/** 12 */
Missing_Price_Level_Amount,
/** 13 */
Missing_Price_Level_Percentage,
/** 8 */
Missing_Pricing_Code,
/** 6 */
Missing_Product,
/** 31 */
Missing_Product_Default_UOM,
/** 32 */
Missing_Product_UOM_Schedule_,
/** 4 */
Missing_Quantity,
/** 16 */
Missing_Standard_Cost,
/** 5 */
Missing_Unit_Price,
/** 10 */
Missing_UOM,
/** 0 */
None,
/** 35 */
Price_Attribute_Out_Of_Range,
/** 25 */
Price_Calculation_Error,
/** 11 */
Product_Not_In_Price_Level,
/** 38 */
Transaction_currency_is_not_set_for_the_product_price_list_item
}
enum PriorityCode {
/** 1 */
Default_Value
}
enum ShippingMethodCode {
/** 1 */
Airborne,
/** 2 */
DHL,
/** 3 */
FedEx,
/** 6 */
Full_Load,
/** 5 */
Postal_Mail,
/** 4 */
UPS,
/** 7 */
Will_Call
}
enum ShipTo_FreightTermsCode {
/** 1 */
Default_Value
}
enum SkipPriceCalculation {
/** 0 */
DoPriceCalcAlways,
/** 1 */
SkipPriceCalcOnRetrieve
}
enum StateCode {
/** 0 */
Active,
/** 2 */
Canceled,
/** 3 */
Fulfilled,
/** 4 */
Invoiced,
/** 1 */
Submitted
}
enum StatusCode {
/** 100001 */
Complete,
/** 3 */
In_Progress,
/** 100003 */
Invoiced,
/** 1 */
New,
/** 4 */
No_Money,
/** 690970000 */
On_hold,
/** 100002 */
Partial,
/** 2 */
Pending
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Field Service Information','Order','Project Information','Quick Create'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
const PRIORITY_TOP_THRESHOLD = 76;
const LS_BIN = "/bin/ls";
const ASDF_DATA_DIR = "~/.asdf";
const HOUR_IN_MILLISECONDS = 3600000;
/*
* Generators
*/
const installedPluginNamesGenerator = (
suggestOptions?: Partial<Fig.Suggestion>
): Fig.Generator => ({
script: "asdf plugin-list",
postProcess: (output) =>
output.split("\n").map((pluginName) => ({
name: `${pluginName}`,
description: "Plugin name",
priority: PRIORITY_TOP_THRESHOLD,
icon: "fig://icon?type=package",
...suggestOptions,
})),
});
const allPluginNamesGenerator = (
suggestOptions?: Partial<Fig.Suggestion>
): Fig.Generator => ({
// If use `asdf plugin-list-all`, it will time out, so use `ls`.
script: `${LS_BIN} -1 ${ASDF_DATA_DIR}/repository/plugins`,
postProcess: (output) =>
output.split("\n").map((pluginName) => ({
name: `${pluginName}`,
description: "Plugin name",
priority: PRIORITY_TOP_THRESHOLD,
icon: "fig://icon?type=package",
...suggestOptions,
})),
});
const installedPluginVersionsGenerator = (
suggestOptions?: Partial<Fig.Suggestion>,
generatorOptions?: Partial<Fig.Generator>
): Fig.Generator => ({
script: (context) => {
const pluginName = context[context.length - 2];
return `asdf list ${pluginName}`;
},
postProcess: (output) =>
output
.split("\n")
.reverse()
.map((pluginVersion) => ({
name: `${pluginVersion}`.trim(),
description: "Plugin version",
priority: PRIORITY_TOP_THRESHOLD,
icon: "fig://icon?type=commit",
...suggestOptions,
})),
...generatorOptions,
});
const allPluginVersionsGenerator = (
suggestOptions?: Partial<Fig.Suggestion>,
generatorOptions?: Partial<Fig.Generator>
): Fig.Generator => ({
script: (context) => {
const pluginName = context[context.length - 2];
return `asdf list-all ${pluginName}`;
},
cache: {
ttl: HOUR_IN_MILLISECONDS,
},
postProcess: (output) =>
output
.split("\n")
.reverse()
.map((pluginVersion) => ({
name: `${pluginVersion}`.trim(),
description: "Plugin version",
priority: PRIORITY_TOP_THRESHOLD,
icon: "fig://icon?type=commit",
...suggestOptions,
})),
...generatorOptions,
});
const shimNamesGenerator = (
suggestOptions?: Partial<Fig.Suggestion>
): Fig.Generator => ({
// Use `ls` because there is no command to get shims in `asdf`.
script: `${LS_BIN} -1 ${ASDF_DATA_DIR}/shims`,
postProcess: (output) =>
output.split("\n").map((shimName) => ({
name: `${shimName}`,
description: "Shim name",
priority: PRIORITY_TOP_THRESHOLD,
icon: "fig://icon?type=command",
...suggestOptions,
})),
});
/*
* Reusable specs
*/
const pluginAddSpec: Omit<Fig.Subcommand, "name"> = {
description:
"Add a plugin from the plugin repo OR, add a Git repo as a plugin by specifying the name and repo url",
args: [
{
name: "name",
generators: allPluginNamesGenerator(),
},
{
name: "git-url",
isOptional: true,
},
],
};
const pluginListAllSpec: Omit<Fig.Subcommand, "name"> = {
description: "List plugins registered on asdf-plugins repository with URLs",
};
const pluginListSpec: Omit<Fig.Subcommand, "name"> = {
description: "List installed plugins. Optionally show git urls and git-ref",
options: [
{
name: "--urls",
description: "Show git urls",
},
{
name: "--refs",
description: "Show git refs",
},
],
subcommands: [
{
name: "all",
...pluginListAllSpec,
},
],
};
const pluginRemoveSpec: Omit<Fig.Subcommand, "name"> = {
description: "Remove plugin and package versions",
args: {
name: "name",
generators: installedPluginNamesGenerator({ isDangerous: true }),
},
};
const pluginUpdateSpec: Omit<Fig.Subcommand, "name"> = {
description:
"Update a plugin to latest commit on default branch or a particular git-ref",
args: [
{
name: "name",
isOptional: true,
isDangerous: true,
},
{
name: "git-ref",
isOptional: true,
isDangerous: true,
},
],
options: [
{
name: "--all",
description: "Update all plugins to latest commit on default branch",
isDangerous: true,
},
],
};
const listAllSpec: Omit<Fig.Subcommand, "name"> = {
description: "List all available (remote) versions of a package",
args: [
{
name: "name",
generators: installedPluginNamesGenerator(),
},
{
name: "version",
generators: installedPluginVersionsGenerator(),
isOptional: true,
},
],
};
const shimVersionsSpec: Omit<Fig.Subcommand, "name"> = {
description: "List for given command which plugins and versions provide it",
args: {
name: "command",
generators: shimNamesGenerator(),
},
};
/*
* Completion spec
*/
const completionSpec: Fig.Spec = {
name: "asdf",
description:
"Extendable version manager with support for Ruby, Node.js, Elixir, Erlang & more",
subcommands: [
{
name: "plugin",
description: "Plugin management sub-commands",
subcommands: [
{
name: "add",
...pluginAddSpec,
},
{
name: "list",
...pluginListSpec,
},
{
name: "remove",
...pluginRemoveSpec,
},
{
name: "update",
...pluginUpdateSpec,
},
],
},
{
name: "plugin-add",
...pluginAddSpec,
},
{
name: "plugin-list",
...pluginListSpec,
},
{
name: "plugin-list-all",
...pluginListAllSpec,
},
{
name: "plugin-remove",
...pluginRemoveSpec,
},
{
name: "plugin-update",
...pluginUpdateSpec,
},
{
name: "install",
description:
"Install plugin at stated version, or all from .tools-versions",
args: [
{
name: "name",
generators: installedPluginNamesGenerator(),
isOptional: true,
},
{
name: "version",
suggestions: [
{
name: "latest",
isDangerous: true,
},
],
generators: allPluginVersionsGenerator(undefined, {
getQueryTerm: (token) => {
if (token.includes("latest")) {
return token.slice(token.indexOf(":") + 1);
}
return token;
},
}),
isOptional: true,
},
],
},
{
name: "uninstall",
description: "Remove a specific version of a package",
args: [
{
name: "name",
generators: installedPluginNamesGenerator({ isDangerous: true }),
},
{
name: "version",
generators: installedPluginVersionsGenerator({ isDangerous: true }),
isOptional: true,
},
],
},
{
name: "current",
description: "Display current versions for named package (else all)",
args: {
name: "name",
isOptional: true,
generators: installedPluginNamesGenerator(),
},
},
{
name: "where",
description:
"Display install path for given package at optional specified version",
args: [
{
name: "name",
generators: installedPluginNamesGenerator(),
},
{
name: "version",
generators: installedPluginVersionsGenerator(),
isOptional: true,
},
],
},
{
name: "which",
description: "Display path to an executable",
args: {
name: "command",
generators: shimNamesGenerator(),
},
},
{
name: "local",
description: "Set package local version",
args: [
{
name: "name",
generators: installedPluginNamesGenerator(),
},
{
name: "version",
generators: installedPluginVersionsGenerator(),
},
],
},
{
name: "global",
description: "Set package global version",
args: [
{
name: "name",
generators: installedPluginNamesGenerator(),
},
{
name: "version",
generators: installedPluginVersionsGenerator(),
},
],
},
{
name: "shell",
description:
"Set the package version to ASDF_${LANG}_VERSION` in the current shell",
args: [
{
name: "name",
generators: installedPluginNamesGenerator(),
},
{
name: "version",
generators: installedPluginVersionsGenerator(),
},
],
},
{
name: "latest",
description:
"Display latest version available to install for a named package",
args: [
{
name: "name",
generators: installedPluginNamesGenerator(),
},
{
name: "version",
generators: installedPluginVersionsGenerator(),
isOptional: true,
},
],
},
{
name: "list",
description: "List installed versions of a package",
args: {
name: "name",
generators: installedPluginNamesGenerator(),
},
subcommands: [
{
name: "all",
priority: PRIORITY_TOP_THRESHOLD + 1,
...listAllSpec,
},
],
},
{
name: "list-all",
...listAllSpec,
},
{
name: "help",
description: "Output documentation for plugin and tool",
args: [
{
name: "name",
generators: installedPluginNamesGenerator(),
},
{
name: "version",
generators: installedPluginVersionsGenerator(),
isOptional: true,
},
],
},
{
name: "exec",
description: "Executes the command shim for the current version",
args: {
name: "command",
generators: shimNamesGenerator(),
isCommand: true,
},
},
{
name: "env",
description: "Prints or runs an executable under a command environment",
args: {
name: "command",
generators: shimNamesGenerator(),
},
},
{
name: "info",
description: "Print os, shell and asdf debug information",
},
{
name: "reshim",
description: "Recreate shims for version of a package",
args: [
{
name: "name",
generators: installedPluginNamesGenerator(),
isOptional: true,
},
{
name: "version",
generators: installedPluginVersionsGenerator(),
isOptional: true,
},
],
},
{
name: "shim",
description: "Shim management sub-commands",
subcommands: [
{
name: "versions",
...shimVersionsSpec,
},
],
},
{
name: "shim-versions",
...shimVersionsSpec,
},
{
name: "update",
description: "Update ASDF to the latest stable release (unless --head)",
options: [
{
name: "--head",
description: "Using HEAD commit",
isDangerous: true,
},
],
},
{
name: "version",
description: "Version for asdf",
},
],
options: [
{
name: "--version",
description: "Version for asdf",
},
{
name: ["-h", "--help"],
description: "Help for asdf",
},
],
};
export default completionSpec; | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { CustomAssessmentAutomations } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { SecurityCenter } from "../securityCenter";
import {
CustomAssessmentAutomation,
CustomAssessmentAutomationsListByResourceGroupNextOptionalParams,
CustomAssessmentAutomationsListByResourceGroupOptionalParams,
CustomAssessmentAutomationsListBySubscriptionNextOptionalParams,
CustomAssessmentAutomationsListBySubscriptionOptionalParams,
CustomAssessmentAutomationsGetOptionalParams,
CustomAssessmentAutomationsGetResponse,
CustomAssessmentAutomationRequest,
CustomAssessmentAutomationsCreateOptionalParams,
CustomAssessmentAutomationsCreateResponse,
CustomAssessmentAutomationsDeleteOptionalParams,
CustomAssessmentAutomationsListByResourceGroupResponse,
CustomAssessmentAutomationsListBySubscriptionResponse,
CustomAssessmentAutomationsListByResourceGroupNextResponse,
CustomAssessmentAutomationsListBySubscriptionNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing CustomAssessmentAutomations operations. */
export class CustomAssessmentAutomationsImpl
implements CustomAssessmentAutomations {
private readonly client: SecurityCenter;
/**
* Initialize a new instance of the class CustomAssessmentAutomations class.
* @param client Reference to the service client
*/
constructor(client: SecurityCenter) {
this.client = client;
}
/**
* List custom assessment automations by provided subscription and resource group
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param options The options parameters.
*/
public listByResourceGroup(
resourceGroupName: string,
options?: CustomAssessmentAutomationsListByResourceGroupOptionalParams
): PagedAsyncIterableIterator<CustomAssessmentAutomation> {
const iter = this.listByResourceGroupPagingAll(resourceGroupName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByResourceGroupPagingPage(resourceGroupName, options);
}
};
}
private async *listByResourceGroupPagingPage(
resourceGroupName: string,
options?: CustomAssessmentAutomationsListByResourceGroupOptionalParams
): AsyncIterableIterator<CustomAssessmentAutomation[]> {
let result = await this._listByResourceGroup(resourceGroupName, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByResourceGroupNext(
resourceGroupName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByResourceGroupPagingAll(
resourceGroupName: string,
options?: CustomAssessmentAutomationsListByResourceGroupOptionalParams
): AsyncIterableIterator<CustomAssessmentAutomation> {
for await (const page of this.listByResourceGroupPagingPage(
resourceGroupName,
options
)) {
yield* page;
}
}
/**
* List custom assessment automations by provided subscription
* @param options The options parameters.
*/
public listBySubscription(
options?: CustomAssessmentAutomationsListBySubscriptionOptionalParams
): PagedAsyncIterableIterator<CustomAssessmentAutomation> {
const iter = this.listBySubscriptionPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listBySubscriptionPagingPage(options);
}
};
}
private async *listBySubscriptionPagingPage(
options?: CustomAssessmentAutomationsListBySubscriptionOptionalParams
): AsyncIterableIterator<CustomAssessmentAutomation[]> {
let result = await this._listBySubscription(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listBySubscriptionNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listBySubscriptionPagingAll(
options?: CustomAssessmentAutomationsListBySubscriptionOptionalParams
): AsyncIterableIterator<CustomAssessmentAutomation> {
for await (const page of this.listBySubscriptionPagingPage(options)) {
yield* page;
}
}
/**
* Gets a single custom assessment automation by name for the provided subscription and resource group.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param customAssessmentAutomationName Name of the Custom Assessment Automation.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
customAssessmentAutomationName: string,
options?: CustomAssessmentAutomationsGetOptionalParams
): Promise<CustomAssessmentAutomationsGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, customAssessmentAutomationName, options },
getOperationSpec
);
}
/**
* Creates or updates a custom assessment automation for the provided subscription. Please note that
* providing an existing custom assessment automation will replace the existing record.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param customAssessmentAutomationName Name of the Custom Assessment Automation.
* @param customAssessmentAutomationBody Custom Assessment Automation body
* @param options The options parameters.
*/
create(
resourceGroupName: string,
customAssessmentAutomationName: string,
customAssessmentAutomationBody: CustomAssessmentAutomationRequest,
options?: CustomAssessmentAutomationsCreateOptionalParams
): Promise<CustomAssessmentAutomationsCreateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
customAssessmentAutomationName,
customAssessmentAutomationBody,
options
},
createOperationSpec
);
}
/**
* Deletes a custom assessment automation by name for a provided subscription
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param customAssessmentAutomationName Name of the Custom Assessment Automation.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
customAssessmentAutomationName: string,
options?: CustomAssessmentAutomationsDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, customAssessmentAutomationName, options },
deleteOperationSpec
);
}
/**
* List custom assessment automations by provided subscription and resource group
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param options The options parameters.
*/
private _listByResourceGroup(
resourceGroupName: string,
options?: CustomAssessmentAutomationsListByResourceGroupOptionalParams
): Promise<CustomAssessmentAutomationsListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
listByResourceGroupOperationSpec
);
}
/**
* List custom assessment automations by provided subscription
* @param options The options parameters.
*/
private _listBySubscription(
options?: CustomAssessmentAutomationsListBySubscriptionOptionalParams
): Promise<CustomAssessmentAutomationsListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{ options },
listBySubscriptionOperationSpec
);
}
/**
* ListByResourceGroupNext
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method.
* @param options The options parameters.
*/
private _listByResourceGroupNext(
resourceGroupName: string,
nextLink: string,
options?: CustomAssessmentAutomationsListByResourceGroupNextOptionalParams
): Promise<CustomAssessmentAutomationsListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, nextLink, options },
listByResourceGroupNextOperationSpec
);
}
/**
* ListBySubscriptionNext
* @param nextLink The nextLink from the previous successful call to the ListBySubscription method.
* @param options The options parameters.
*/
private _listBySubscriptionNext(
nextLink: string,
options?: CustomAssessmentAutomationsListBySubscriptionNextOptionalParams
): Promise<CustomAssessmentAutomationsListBySubscriptionNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listBySubscriptionNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Security/customAssessmentAutomations/{customAssessmentAutomationName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CustomAssessmentAutomation
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion1],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.customAssessmentAutomationName
],
headerParameters: [Parameters.accept],
serializer
};
const createOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Security/customAssessmentAutomations/{customAssessmentAutomationName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.CustomAssessmentAutomation
},
201: {
bodyMapper: Mappers.CustomAssessmentAutomation
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.customAssessmentAutomationBody,
queryParameters: [Parameters.apiVersion1],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.customAssessmentAutomationName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Security/customAssessmentAutomations/{customAssessmentAutomationName}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion1],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.customAssessmentAutomationName
],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Security/customAssessmentAutomations",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CustomAssessmentAutomationsListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion1],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const listBySubscriptionOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Security/customAssessmentAutomations",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CustomAssessmentAutomationsListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion1],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CustomAssessmentAutomationsListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion1],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listBySubscriptionNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CustomAssessmentAutomationsListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion1],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import type { AstNode, ColorTokenType, CommentNode, FloatNode, InfallibleParser, IntegerNode, Parser, ParserContext, ResourceLocationNode, ResourceLocationOptions, SequenceUtil, Source, StringNode } from '@spyglassmc/core'
import * as core from '@spyglassmc/core'
import { any, Arrayable, failOnEmpty, failOnError, Failure, map, optional, Range, repeat, ResourceLocation, select, sequence, setType, stopBefore, SymbolAccessType, validate } from '@spyglassmc/core'
import { arrayToMessage, localeQuote, localize } from '@spyglassmc/locales'
import type { AccessorKeyNode, AnyTypeNode, AttributeNode, AttributeTreeNamedValuesNode, AttributeTreeNode, AttributeTreePosValuesNode, AttributeValueNode, BooleanTypeNode, DispatcherTypeNode, DispatchStatementNode, DocCommentsNode, DynamicIndexNode, EnumBlockNode, EnumFieldNode, EnumInjectionNode, EnumNode, EnumValueNode, FloatRangeNode, IdentifierNode, IndexBodyNode, InjectionNode, IntRangeNode, ListTypeNode, LiteralNode, LiteralTypeNode, ModuleNode, NumericTypeNode, PathNode, PrimitiveArrayTypeNode, ReferenceTypeNode, StringTypeNode, StructBlockNode, StructInjectionNode, StructKeyNode, StructMapKeyNode, StructNode, StructPairFieldNode, StructSpreadFieldNode, TopLevelNode, TupleTypeNode, TypeAliasNode, TypedNumberNode, TypeNode, TypeParamBlockNode, TypeParamNode, UnionTypeNode, UseStatementNode } from '../node/index.js'
import { LiteralNumberCaseInsensitiveSuffixes, NumericTypeFloatKinds, NumericTypeIntKinds, PrimitiveArrayValueKinds, StaticIndexKeywords } from '../type/index.js'
/**
* @returns A comment parser that accepts normal comments (`//`) and reports an error if it's a doc comment (`///`).
*
* `Failure` when there isn't a comment.
*/
export const comment: Parser<CommentNode> = validate(
core.comment({
singleLinePrefixes: new Set(['//']),
}),
(res, src) => !src.slice(res).startsWith('///'),
localize('mcdoc.parser.syntax.doc-comment-unexpected')
)
/**
* @returns A parser that parses the gap between **SYNTAX** rules, which may contains whitespace and regular comments.
*/
function syntaxGap(
/* istanbul ignore next */
delegatesDocComments = false
): InfallibleParser<CommentNode[]> {
return (src: Source, ctx: ParserContext): CommentNode[] => {
const ans: CommentNode[] = []
src.skipWhitespace()
while (src.canRead() && src.peek(2) === '//' && (!delegatesDocComments || src.peek(3) !== '///')) {
const result = comment(src, ctx) as CommentNode
ans.push(result)
src.skipWhitespace()
}
return ans
}
}
type SyntaxUtil<CN extends AstNode> = SequenceUtil<CN | CommentNode>
type SP<CN extends AstNode> = InfallibleParser<CN | SyntaxUtil<CN> | undefined> | Parser<CN | SyntaxUtil<CN> | undefined> | { get: (result: SyntaxUtil<CN>) => InfallibleParser<CN | SyntaxUtil<CN> | undefined> | Parser<CN | SyntaxUtil<CN> | undefined> }
type SIP<CN extends AstNode> = InfallibleParser<CN | SyntaxUtil<CN> | undefined> | { get: (result: SyntaxUtil<CN>) => InfallibleParser<CN | SyntaxUtil<CN> | undefined> }
/**
* @template CN Child node.
*
* @returns A parser that follows a **SYNTAX** rule built with the passed-in parsers.
*
* `Failure` when any of the `parsers` returns a `Failure`.
*/
function syntax<PA extends SP<AstNode>[]>(parsers: PA, delegatesDocComments?: boolean): PA extends SIP<AstNode>[]
? InfallibleParser<SyntaxUtil<{ [K in number]: PA[K] extends SIP<infer V> ? V : never }[number]>>
: Parser<SyntaxUtil<{ [K in number]: PA[K] extends SP<infer V> ? V : never }[number]>>
function syntax(parsers: SP<AstNode>[], delegatesDocComments = false): Parser<SyntaxUtil<AstNode>> {
return (src, ctx) => {
src.skipWhitespace()
const ans = sequence(parsers, syntaxGap(delegatesDocComments))(src, ctx)
src.skipWhitespace()
return ans
}
}
/**
* @template CN Child node.
*
* @param parser Must be fallible.
*
* @returns A parser that follows a **SYNTAX** rule built with the passed-in parser being repeated zero or more times.
*/
function syntaxRepeat<P extends Parser<AstNode | SyntaxUtil<AstNode>>>(parser: P, delegatesDocComments?: boolean): P extends InfallibleParser
? { _inputParserIsInfallible: never } & void
: P extends Parser<infer V | SyntaxUtil<infer V>> ? InfallibleParser<SyntaxUtil<V>> : never
function syntaxRepeat<CN extends AstNode>(parser: Parser<CN | SyntaxUtil<CN>>, delegatesDocComments = false): InfallibleParser<SyntaxUtil<CN>> | void {
return repeat<CN | CommentNode>(parser, syntaxGap(delegatesDocComments))
}
export function literal(literal: Arrayable<string>, options?: { allowedChars?: Set<string>, specialChars?: Set<string>, colorTokenType?: ColorTokenType }): InfallibleParser<LiteralNode> {
return (src, ctx) => {
const ans: LiteralNode = {
type: 'mcdoc:literal',
range: Range.create(src),
value: '',
colorTokenType: options?.colorTokenType,
}
ans.value = src.readIf(c => options?.allowedChars?.has(c) ?? (options?.specialChars?.has(c) || /[a-z]/i.test(c)))
ans.range.end = src.cursor
if (Arrayable.toArray(literal).every(l => l !== ans.value)) {
ctx.err.report(localize('expected-got', arrayToMessage(literal), localeQuote(ans.value)), ans)
}
return ans
}
}
function keyword(keyword: Arrayable<string>, options: { allowedChars?: Set<string>, specialChars?: Set<string>, colorTokenType?: ColorTokenType } = { colorTokenType: 'keyword' }): Parser<LiteralNode> {
return (src, ctx) => {
const result = literal(keyword, options)(src, ctx)
if (!Arrayable.toArray(keyword).includes(result.value)) {
return Failure
}
return result
}
}
function punctuation(punctuation: string): InfallibleParser<undefined> {
return (src, ctx) => {
src.skipWhitespace()
if (!src.trySkip(punctuation)) {
ctx.err.report(localize('expected-got', localeQuote(punctuation), localeQuote(src.peek())), src)
}
return undefined
}
}
function marker(punctuation: string): Parser<undefined> {
return (src, _ctx) => {
src.skipWhitespace()
if (!src.trySkip(punctuation)) {
return Failure
}
return undefined
}
}
export function resLoc(options: ResourceLocationOptions): InfallibleParser<ResourceLocationNode> {
return validate(
core.resourceLocation(options),
res => res.namespace !== undefined,
localize('mcdoc.parser.resource-location.colon-expected', localeQuote(ResourceLocation.NamespacePathSep))
)
}
const UnicodeControlCharacters = Object.freeze([
'\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06',
'\x07', '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D',
'\x0E', '\x0F', '\x7F',
])
export const string: InfallibleParser<StringNode> = stopBefore(core.string({
escapable: { characters: ['b', 'f', 'n', 'r', 't', '\\', '"'], unicode: true },
quotes: ['"'],
}), ...UnicodeControlCharacters)
export const identifier: InfallibleParser<IdentifierNode> = (src, ctx) => {
// https://spyglassmc.com/user/mcdoc/#identifier
const IdentifierStart = /^[\p{L}\p{Nl}]$/u
const IdentifierContinue = /^[\p{L}\p{Nl}\u200C\u200D\p{Mn}\p{Mc}\p{Nd}\p{Pc}]$/u
const ReservedWords = new Set(['any', 'boolean', 'byte', 'double', 'enum', 'false', 'float', 'int', 'long', 'short', 'string', 'struct', 'super', 'true'])
const ans: IdentifierNode = {
type: 'mcdoc:identifier',
range: Range.create(src),
options: { category: 'mcdoc' },
value: '',
}
const start = src.innerCursor
if (IdentifierStart.test(src.peek())) {
src.skip()
while (IdentifierContinue.test(src.peek())) {
src.skip()
}
} else {
ctx.err.report(localize('expected', localize('mcdoc.node.identifier')), src)
}
ans.value = src.string.slice(start, src.innerCursor)
ans.range.end = src.cursor
if (ReservedWords.has(ans.value)) {
ctx.err.report(localize('mcdoc.parser.identifier.reserved-word', localeQuote(ans.value)), ans)
}
return ans
}
function indexBody(options?: { accessType?: SymbolAccessType, noDynamic?: boolean }): InfallibleParser<IndexBodyNode> {
const accessorKey: InfallibleParser<AccessorKeyNode> = select([
{
prefix: '%',
parser: literal(['%key', '%parent'], { specialChars: new Set(['%']) }),
},
{
prefix: '"',
parser: string,
},
{
parser: identifier,
},
])
const dynamicIndex: InfallibleParser<DynamicIndexNode> = setType(
'mcdoc:dynamic_index',
syntax([
punctuation('['),
accessorKey,
repeat(sequence([marker('.'), accessorKey])),
punctuation(']'),
])
)
const index: InfallibleParser<LiteralNode | IdentifierNode | StringNode | ResourceLocationNode | DynamicIndexNode> = select([
{
prefix: '%',
parser: literal(StaticIndexKeywords.map(v => `%${v}`), { specialChars: new Set(['%']) }),
},
{
prefix: '"',
parser: string,
},
{
prefix: '[',
parser: options?.noDynamic
? validate(dynamicIndex, () => false, localize('mcdoc.parser.index-body.dynamic-index-not-allowed'))
: dynamicIndex,
},
{
parser: any([resLoc({ category: 'mcdoc/dispatcher', accessType: options?.accessType }), identifier]),
},
])
return setType(
'mcdoc:index_body',
syntax([
punctuation('['),
index,
syntaxRepeat(syntax([marker(','), failOnEmpty(index)])),
optional(marker(',')),
punctuation(']'),
])
)
}
const pathSegment: InfallibleParser<IdentifierNode | LiteralNode> = select([
{ prefix: 'super', parser: literal('super') },
{ parser: identifier },
])
export const path: InfallibleParser<PathNode> = (src, ctx) => {
let isAbsolute: boolean | undefined
if (src.trySkip('::')) {
isAbsolute = true
}
return map(
sequence([
pathSegment,
repeat(sequence([marker('::'), pathSegment])),
]),
res => {
const ans: PathNode = {
type: 'mcdoc:path',
children: res.children,
range: res.range,
isAbsolute,
}
return ans
}
)(src, ctx)
}
const attributeTreePosValues: InfallibleParser<AttributeTreePosValuesNode> = setType(
'mcdoc:attribute/tree/pos',
syntax([
{ get: () => attributeValue },
syntaxRepeat(syntax([marker(','), { get: () => failOnEmpty(attributeValue) }], true), true),
], true)
)
const attributeNamedValue: Parser<SyntaxUtil<StringNode | IdentifierNode | AttributeValueNode>> = syntax([
select([
{ prefix: '"', parser: string },
{ parser: identifier },
]),
select([
{ prefix: '=', parser: syntax([punctuation('='), { get: () => attributeValue }], true) },
{ parser: { get: () => attributeTree } },
]),
], true)
const attributeTreeNamedValues: Parser<AttributeTreeNamedValuesNode> = setType(
'mcdoc:attribute/tree/named',
syntax([
attributeNamedValue,
syntaxRepeat(syntax([marker(','), failOnEmpty(attributeNamedValue)], true), true),
], true)
)
const treeBody: InfallibleParser<SyntaxUtil<AttributeTreePosValuesNode | AttributeTreeNamedValuesNode>> = any([
syntax([attributeTreeNamedValues, optional(marker(','))]),
syntax([attributeTreePosValues, punctuation(','), attributeTreeNamedValues, optional(marker(','))]),
syntax([attributeTreePosValues, optional(marker(','))]),
])
const AttributeTreeClosure = Object.freeze({
'(': ')',
'[': ']',
'{': '}',
})
const attributeTree: Parser<AttributeTreeNode> = (src, ctx) => {
const delim = src.trySkip('(') ? '(' : (src.trySkip('[') ? '[' : (src.trySkip('{') ? '{' : undefined))
if (!delim) {
return Failure
}
const res = treeBody(src, ctx)
const ans: AttributeTreeNode = {
type: 'mcdoc:attribute/tree',
range: res.range,
children: res.children,
delim,
}
src.trySkip(AttributeTreeClosure[delim])
return ans
}
const attributeValue: InfallibleParser<AttributeValueNode> = select([
{ predicate: src => ['(', '[', '{'].includes(src.peek()), parser: attributeTree as InfallibleParser<AttributeTreeNode> },
{ parser: { get: () => type } },
])
export const attribute: Parser<AttributeNode> = setType(
'mcdoc:attribute',
syntax([
marker('#['),
identifier,
select([
{ prefix: '=', parser: syntax([punctuation('='), attributeValue, punctuation(']')], true) },
{ predicate: src => ['(', '[', '{'].includes(src.peek()), parser: syntax([attributeTree as InfallibleParser<AttributeTreeNode>, punctuation(']')], true) },
{ parser: punctuation(']') },
]),
], true)
)
const attributes = repeat(attribute)
export const dispatchStatement: Parser<DispatchStatementNode> = setType(
'mcdoc:dispatch_statement',
syntax([
attributes,
keyword('dispatch'),
resLoc({ category: 'mcdoc/dispatcher', accessType: SymbolAccessType.Write }),
indexBody({ noDynamic: true }),
literal('to'),
{ get: () => type },
], true)
)
export const docComment: Parser<CommentNode> = core.comment({
singleLinePrefixes: new Set(['///']),
includesEol: true,
})
export const docComments: InfallibleParser<DocCommentsNode> = setType('mcdoc:doc_comments', repeat(docComment, src => {
src.skipWhitespace()
return []
}))
const prelim: InfallibleParser<SyntaxUtil<DocCommentsNode | AttributeNode>> = syntax([
optional(failOnEmpty(docComments)),
attributes,
])
const enumType: InfallibleParser<LiteralNode> = literal([
'byte',
'short',
'int',
'long',
'string',
'float',
'double',
], { colorTokenType: 'type' })
export const float: InfallibleParser<FloatNode> = core.float({
pattern: /^[-+]?(?:[0-9]+(?:[eE][-+]?[0-9]+)?|[0-9]*\.[0-9]+(?:[eE][-+]?[0-9]+)?)$/,
})
export const typedNumber: InfallibleParser<TypedNumberNode> = setType(
'mcdoc:typed_number',
sequence([
float,
optional(keyword(LiteralNumberCaseInsensitiveSuffixes, { colorTokenType: 'keyword' })),
])
)
const enumValue: InfallibleParser<EnumValueNode> = select([
{ prefix: '"', parser: string },
{ parser: typedNumber },
])
const enumField: InfallibleParser<EnumFieldNode> = setType(
'mcdoc:enum/field',
syntax([
prelim,
identifier,
punctuation('='),
enumValue,
], true)
)
const enumBlock: InfallibleParser<EnumBlockNode> = setType(
'mcdoc:enum/block',
syntax([
punctuation('{'),
select([
{ prefix: '}', parser: punctuation('}') },
{
parser: syntax([
enumField,
syntaxRepeat(syntax([marker(','), failOnEmpty(enumField)], true), true),
optional(marker(',')),
punctuation('}'),
], true),
},
]),
], true)
)
export const enum_: Parser<EnumNode> = setType(
'mcdoc:enum',
syntax([
prelim,
keyword('enum'),
punctuation('('),
enumType,
punctuation(')'),
optional(failOnError(identifier)),
enumBlock,
], true)
)
const structMapKey: InfallibleParser<StructMapKeyNode> = setType(
'mcdoc:struct/map_key',
syntax([
punctuation('['),
{ get: () => type },
punctuation(']'),
], true)
)
const structKey: InfallibleParser<StructKeyNode> = select([
{ prefix: '"', parser: string },
{ prefix: '[', parser: structMapKey },
{ parser: identifier },
])
const structPairField: InfallibleParser<StructPairFieldNode> = (src, ctx) => {
let isOptional: boolean | undefined
const result0 = syntax([
prelim,
structKey,
], true)(src, ctx)
if (src.trySkip('?')) {
isOptional = true
}
const result1 = syntax([
punctuation(':'),
{ get: () => type },
], true)(src, ctx)
const ans: StructPairFieldNode = {
type: 'mcdoc:struct/field/pair',
children: [...result0.children, ...result1.children],
range: Range.span(result0, result1),
isOptional,
}
return ans
}
const structSpreadField: Parser<StructSpreadFieldNode> = setType(
'mcdoc:struct/field/spread',
syntax([
attributes,
marker('...'),
{ get: () => type },
], true)
)
const structField: InfallibleParser<StructPairFieldNode | StructSpreadFieldNode> = any([
structSpreadField,
structPairField,
])
const structBlock: InfallibleParser<StructBlockNode> = setType(
'mcdoc:struct/block',
syntax([
punctuation('{'),
select([
{ prefix: '}', parser: punctuation('}') },
{
parser: syntax([
structField,
syntaxRepeat(syntax([marker(','), failOnEmpty(structField)], true), true),
optional(marker(',')),
punctuation('}'),
], true),
},
]),
], true)
)
export const struct: Parser<StructNode> = setType(
'mcdoc:struct',
syntax([
prelim,
keyword('struct'),
optional(failOnEmpty(identifier)),
structBlock,
], true)
)
const enumInjection: InfallibleParser<EnumInjectionNode> = setType(
'mcdoc:injection/enum',
syntax([
literal('enum'),
punctuation('('),
enumType,
punctuation(')'),
path,
enumBlock,
])
)
const structInjection: InfallibleParser<StructInjectionNode> = setType(
'mcdoc:injection/struct',
syntax([
literal('struct'),
path,
structBlock,
])
)
export const injection: Parser<InjectionNode> = setType(
'mcdoc:injection',
syntax([
keyword('inject'),
select([
{ prefix: 'enum', parser: enumInjection },
{ parser: structInjection },
]),
])
)
const typeParam: InfallibleParser<TypeParamNode> = setType(
'mcdoc:type_param',
syntax([
identifier,
optional(syntax([failOnError(literal('extends')), path])),
])
)
const typeParamBlock: InfallibleParser<TypeParamBlockNode> = setType(
'mcdoc:type_param_block',
syntax([
punctuation('<'),
select([
{ prefix: '>', parser: punctuation('>') },
{
parser: syntax([
typeParam,
syntaxRepeat(syntax([marker(','), failOnEmpty(typeParam)])),
optional(marker(',')),
punctuation('>'),
]),
},
]),
])
)
const noop: InfallibleParser<undefined> = () => undefined
const optionalTypeParamBlock: InfallibleParser<TypeParamBlockNode | undefined> = select([
{ prefix: '<', parser: typeParamBlock },
{ parser: noop },
])
export const typeAlias: Parser<TypeAliasNode> = setType(
'mcdoc:type_alias',
syntax([
docComments,
keyword('type'),
identifier,
optionalTypeParamBlock,
punctuation('='),
{ get: () => type },
], true)
)
export const useStatement: Parser<UseStatementNode> = setType(
'mcdoc:use_statement',
syntax([
keyword('use'),
path,
select([
{ prefix: 'as', parser: syntax([literal('as'), identifier]) },
{ parser: noop },
]),
], true)
)
const topLevel: Parser<TopLevelNode> = any([
comment,
dispatchStatement,
enum_,
injection,
struct,
typeAlias,
useStatement,
])
export const module_: Parser<ModuleNode> = setType('mcdoc:module', syntaxRepeat(topLevel, true))
/* eslint-disable @typescript-eslint/indent */
type GetTypeNode<T extends string, P extends Parser<AstNode | SyntaxUtil<AstNode>>> = { type: T } & SyntaxUtil<
| AttributeNode
| IndexBodyNode
| (P extends InfallibleParser<infer V> ? (V extends SyntaxUtil<infer U> ? U : (V extends AstNode ? V : never)) : never)
>
function typeBase<T extends string, P extends Parser<AstNode | SyntaxUtil<AstNode>>>(type: T, parser: P): P extends InfallibleParser<AstNode | SyntaxUtil<AstNode>>
? InfallibleParser<GetTypeNode<T, P>>
: Parser<GetTypeNode<T, P>>
/* eslint-enable @typescript-eslint/indent */
function typeBase<T extends string>(type: T, parser: Parser): Parser<{ type: T } & SyntaxUtil<AstNode>> {
return setType(type, syntax([
attributes,
parser,
syntaxRepeat(failOnError(indexBody())),
], true))
}
export const anyType: Parser<AnyTypeNode> = typeBase('mcdoc:type/any', keyword('any', { colorTokenType: 'type' }))
export const booleanType: Parser<BooleanTypeNode> = typeBase('mcdoc:type/boolean', keyword('boolean', { colorTokenType: 'type' }))
export const integer: InfallibleParser<IntegerNode> = core.integer({
pattern: /^(?:0|[-+]?[1-9][0-9]*)$/,
})
function range<P extends InfallibleParser<IntegerNode> | InfallibleParser<FloatNode>>(
type: P extends InfallibleParser<infer V> ? (V extends IntegerNode ? IntRangeNode : FloatRangeNode)['type'] : never,
number: P
): InfallibleParser<P extends InfallibleParser<infer V> ? (V extends IntegerNode ? IntRangeNode : FloatRangeNode) : never>
function range(type: string, number: InfallibleParser): InfallibleParser {
return setType(
type,
select([
{
prefix: '..',
parser: sequence([
literal('..', { allowedChars: new Set('.') }),
number,
]),
},
{
parser: sequence([
stopBefore(number, '..'),
select([
{
prefix: '..',
parser: sequence([
literal('..', { allowedChars: new Set('.') }),
optional(failOnEmpty(number)),
]),
},
{ parser: noop },
]),
]),
},
])
)
}
const intRange: InfallibleParser<IntRangeNode> = range('mcdoc:int_range', integer)
const atIntRange: InfallibleParser<IntRangeNode | undefined> = optional((src, ctx) => {
if (!src.trySkip('@')) {
return Failure
}
src.skipWhitespace()
return intRange(src, ctx)
})
export const stringType: Parser<StringTypeNode> = typeBase('mcdoc:type/string', syntax([
keyword('string', { colorTokenType: 'type' }),
atIntRange,
]))
export const literalType: Parser<LiteralTypeNode> = typeBase('mcdoc:type/literal', select([
{ predicate: src => src.tryPeek('false') || src.tryPeek('true'), parser: keyword(['false', 'true'], { colorTokenType: 'type' }) },
{ prefix: '"', parser: failOnEmpty(string) },
{ parser: failOnError(typedNumber) },
]))
const floatRange: InfallibleParser<FloatRangeNode> = range('mcdoc:float_range', float)
const atFloatRange: InfallibleParser<FloatRangeNode | undefined> = optional((src, ctx) => {
if (!src.trySkip('@')) {
return Failure
}
src.skipWhitespace()
return floatRange(src, ctx)
})
export const numericType: Parser<NumericTypeNode> = typeBase('mcdoc:type/numeric_type', select([
{
predicate: src => NumericTypeFloatKinds.some(k => src.tryPeek(k)),
parser: syntax([
keyword(NumericTypeFloatKinds, { colorTokenType: 'type' }),
atFloatRange,
]),
},
{
parser: syntax([
keyword(NumericTypeIntKinds, { colorTokenType: 'type' }),
atIntRange,
]),
},
]))
export const primitiveArrayType: Parser<PrimitiveArrayTypeNode> = typeBase('mcdoc:type/primitive_array', syntax([
literal(PrimitiveArrayValueKinds),
atIntRange,
keyword('[]', { allowedChars: new Set(['[', ']']), colorTokenType: 'type' }),
atIntRange,
]))
export const listType: Parser<ListTypeNode> = typeBase('mcdoc:type/list', syntax([
marker('['),
{ get: () => type },
punctuation(']'),
atIntRange,
], true))
export const tupleType: Parser<TupleTypeNode> = typeBase('mcdoc:type/tuple', syntax([
marker('['),
{ get: () => type },
marker(','),
select([
{ prefix: ']', parser: punctuation(']') },
{
parser: syntax([
{ get: () => type },
syntaxRepeat(syntax([marker(','), { get: () => failOnEmpty(type) }], true), true),
optional(marker(',')),
punctuation(']'),
], true),
},
]),
], true))
export const dispatcherType: Parser<DispatcherTypeNode> = typeBase('mcdoc:type/dispatcher', syntax([
failOnError(resLoc({ category: 'mcdoc/dispatcher' })),
indexBody(),
]))
export const unionType: Parser<UnionTypeNode> = typeBase('mcdoc:type/union', syntax([
marker('('),
select([
{ prefix: ')', parser: punctuation(')') },
{
parser: syntax([
{ get: () => type },
syntaxRepeat(syntax([marker('|'), { get: () => failOnEmpty(type) }], true), true),
optional(marker('|')),
punctuation(')'),
], true),
},
]),
]))
export const referenceType: InfallibleParser<ReferenceTypeNode> = typeBase('mcdoc:type/reference', syntax([
path,
optional(syntax([
marker('<'),
select([
{ prefix: '>', parser: punctuation('>') },
{
parser: syntax([
{ get: () => type },
syntaxRepeat(syntax([marker(','), { get: () => failOnEmpty(type) }], true), true),
optional(marker(',')),
punctuation('>'),
], true),
},
]),
])),
]))
export const type: InfallibleParser<TypeNode> = any([
anyType,
booleanType,
dispatcherType,
enum_,
listType,
literalType,
numericType,
primitiveArrayType,
stringType,
struct,
tupleType,
unionType,
referenceType,
]) | the_stack |
namespace uchan {
class QRState implements Persistable {
x: number = -1;
y: number = -1;
static fromDefaults() {
return new QRState();
}
fromObject(obj: any) {
this.x = obj['x'];
this.y = obj['y'];
}
toObject() {
return {
'x': this.x,
'y': this.y
};
}
}
export class QR {
watcher: Watcher;
persistence: Persistence;
postEndpoint: string;
filePostingEnabled: boolean;
stateListeners: any[];
state: QRState;
showing: boolean = false;
submitXhr: XMLHttpRequest = null;
draggable: Draggable;
element: HTMLDivElement;
formElement: HTMLFormElement;
closeElement: HTMLElement;
nameElement: HTMLInputElement;
passwordElement: HTMLInputElement;
commentElement: HTMLInputElement;
fileElement: HTMLInputElement;
submitElement: HTMLInputElement;
errorMessageElement: HTMLElement;
constructor(watcher: Watcher, persistence: Persistence) {
this.watcher = watcher;
this.persistence = persistence;
this.postEndpoint = uchan.context.postEndpoint;
this.filePostingEnabled = uchan.context.filePostingEnabled;
this.stateListeners = [];
this.state = <QRState>persistence.retrieve('qr', QRState);
if (this.state == null) {
this.state = QRState.fromDefaults();
persistence.persist('qr', this.state);
}
persistence.addCallback('qr', () => this.stateChanged());
this.setupView();
}
private setupView() {
this.element = document.createElement('div');
this.element.className = 'qr';
this.element.innerHTML = '' +
' <form class="qr-form" action="' + this.postEndpoint + '" method="post" enctype="multipart/form-data">' +
' <span class="handle">' +
' <span class="handle-text">Reply</span>' +
' <span class="handle-close">✖</span>' +
' </span><br>' +
' <input class="input" type="text" name="name" placeholder="Name"><br>' +
' <input class="input" type="password" name="password" placeholder="Password (for post deletion)"><br>' +
' <textarea class="input" name="comment" placeholder="Comment" rows="8"></textarea><br>' +
' <input type="file" name="file" multiple><input type="submit" value="Submit"/><br>' +
' <span class="error-message">Message</span>' +
' <input type="hidden" name="board" value="' + context.boardName + '"/>' +
' <input type="hidden" name="thread" value="' + context.threadRefno + '"/>' +
' </form>';
this.draggable = new Draggable(this.element, this.element.querySelector('.handle'), false);
this.draggable.bind(() => this.onDraggableMoved());
this.formElement = <HTMLFormElement>this.element.querySelector('.qr-form');
this.closeElement = <HTMLElement>this.element.querySelector('.handle-close');
this.closeElement.addEventListener('click', this.onCloseClickedEvent.bind(this));
this.nameElement = <HTMLInputElement>this.element.querySelector('input[name="name"]');
this.passwordElement = <HTMLInputElement>this.element.querySelector('input[name="password"]');
this.commentElement = <HTMLInputElement>this.element.querySelector('textarea[name="comment"]');
this.fileElement = <HTMLInputElement>this.element.querySelector('input[name="file"]');
this.fileElement.style.display = this.filePostingEnabled ? 'inline-block' : 'none';
this.fileElement.addEventListener('change', this.onFileChangeEvent.bind(this));
this.submitElement = <HTMLInputElement>this.element.querySelector('input[type="submit"]');
this.errorMessageElement = <HTMLElement>this.element.querySelector('.error-message');
this.commentElement.addEventListener('keydown', this.onCommentKeyDownEvent.bind(this));
this.submitElement.addEventListener('click', this.onSubmitEvent.bind(this));
document.body.appendChild(this.element);
}
insertFormElement(element) {
this.formElement.insertBefore(element, this.commentElement.nextSibling);
}
addStateChangedListener(listener) {
this.stateListeners.push(listener);
}
removeStateChangedListener(listener) {
let index = this.stateListeners.indexOf(listener);
if (index >= 0) {
this.stateListeners.splice(index, 1);
}
}
callStateChangedListeners(what) {
for (let i = 0; i < this.stateListeners.length; i++) {
this.stateListeners[i](this, what);
}
}
clear() {
this.formElement.reset();
this.callStateChangedListeners('clear');
}
addShowClickListener(element) {
element.addEventListener('click', this.onOpenEvent.bind(this));
}
onCommentKeyDownEvent(event) {
if (event.keyCode == 27) {
this.hide();
}
}
onFileChangeEvent(event) {
let overLimit = this.fileElement.files.length > context.fileMax;
this.submitElement.disabled = overLimit;
this.showErrorMessage(overLimit, 'Too many files selected, max ' + context.fileMax + ' files allowed');
}
onOpenEvent(event) {
event.preventDefault();
this.show();
}
onCloseClickedEvent(event) {
event.preventDefault();
this.hide();
}
onDraggableMoved() {
this.state.x = this.draggable.x;
this.state.y = this.draggable.y;
this.persistence.persist('qr', this.state);
}
stateChanged() {
this.state = <QRState>this.persistence.retrieve('qr', QRState);
this.draggable.setPosition(this.state.x, this.state.y);
}
show() {
if (!this.showing) {
this.showing = true;
this.element.style.display = 'inline-block';
if (this.state.x == -1 && this.state.y == -1) {
let bb = this.element.getBoundingClientRect();
this.state.x = Math.min(1000, document.documentElement.clientWidth - bb.width - 100);
this.state.y = 100;
}
this.draggable.setPosition(this.state.x, this.state.y);
this.commentElement.focus();
this.callStateChangedListeners('show');
}
}
hide() {
if (this.showing) {
this.showing = false;
this.element.style.display = 'none';
this.callStateChangedListeners('hide');
}
}
addRefno(refno) {
let toInsert = '>>' + refno + '\n';
let position = this.commentElement.selectionStart;
let value = this.commentElement.value;
this.commentElement.value = value.substring(0, position) + toInsert + value.substring(position);
this.commentElement.selectionStart = this.commentElement.selectionEnd = position + toInsert.length;
this.commentElement.focus();
}
onSubmitEvent(event) {
event.preventDefault();
this.submit();
}
submit() {
if (this.submitXhr == null) {
let xhr = this.submitXhr = new XMLHttpRequest();
xhr.open('POST', this.postEndpoint);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onerror = this.submitXhrOnErrorEvent.bind(this);
xhr.onload = this.submitXhrOnLoadEvent.bind(this);
xhr.upload.onprogress = this.submitXhrOnProgressEvent.bind(this);
let formData = new FormData(this.formElement);
xhr.send(formData);
this.submitElement.disabled = true;
this.callStateChangedListeners('submitSent');
}
}
submitXhrOnProgressEvent(event) {
this.submitElement.value = Math.round((event.loaded / event.total) * 100) + '%';
}
submitXhrOnErrorEvent(event) {
let responseData = null;
try {
responseData = JSON.parse(this.submitXhr.responseText);
} catch (e) {
}
let responseMessage = 'Error submitting';
if (responseData && responseData['message']) {
responseMessage = 'Error: ' + responseData['message'];
} else {
if (this.submitXhr.status == 400) {
responseMessage = 'Error: bad request';
}
}
console.error('Error submitting', this.submitXhr, event);
this.showErrorMessage(true, responseMessage);
this.callStateChangedListeners('submitError');
this.resetAfterSubmit();
}
submitXhrOnLoadEvent(event) {
if (this.submitXhr.status == 200) {
this.showErrorMessage(false);
this.callStateChangedListeners('submitDone');
this.clear();
this.hide();
this.watcher.afterPost();
} else {
this.submitXhrOnErrorEvent(event);
}
this.resetAfterSubmit();
}
resetAfterSubmit() {
this.submitElement.disabled = false;
this.submitElement.value = 'Submit';
this.submitXhr = null;
}
showErrorMessage(show, message = null) {
this.errorMessageElement.style.display = show ? 'inline-block' : 'none';
if (show) {
this.errorMessageElement.innerHTML = message;
}
}
}
} | the_stack |
import * as assert from "assert";
import * as vscode from "vscode";
// tslint:disable-next-line:no-duplicate-imports
import { commands } from "vscode";
import { IActionContext, IAzureQuickPickItem, IAzureUserInput } from "vscode-azureextensionui";
import { Json, templateKeys } from "../../../extension.bundle";
import { ext } from "../../extensionVariables";
import { ObjectValue } from "../../language/json/JSON";
import { ISnippet } from "../../snippets/ISnippet";
import { KnownContexts } from "../../snippets/KnownContexts";
import { assertNever } from '../../util/assertNever';
import { DeploymentTemplateDoc } from "./DeploymentTemplateDoc";
import { TemplateSectionType } from "./TemplateSectionType";
const insertCursorText = '[]';
const invalidTemplateMessage = `The ARM template file appears to be invalid. If you need to, you can add contents for a new template by typing "arm!" and selecting the desired snippet.`;
export class QuickPickItem<T> implements vscode.QuickPickItem {
public label: string;
public value: T;
public description: string;
constructor(label: string, value: T, description: string) {
this.label = label;
this.value = value;
this.description = description;
}
}
type ItemType = "string" | "securestring" | "int" | "bool" | "bool" | "object" | "secureobject" | "array";
export function getItemType(): QuickPickItem<ItemType>[] {
let items: QuickPickItem<ItemType>[] = [];
items.push(new QuickPickItem<ItemType>("String", "string", "A string"));
items.push(new QuickPickItem<ItemType>("Secure string", "securestring", "A secure string"));
items.push(new QuickPickItem<ItemType>("Int", "int", "An integer"));
items.push(new QuickPickItem<ItemType>("Bool", "bool", "A boolean"));
items.push(new QuickPickItem<ItemType>("Object", "object", "An object"));
items.push(new QuickPickItem<ItemType>("Secure object", "secureobject", "A secure object"));
items.push(new QuickPickItem<ItemType>("Array", "array", "An array"));
return items;
}
async function getResourceSnippets(): Promise<IAzureQuickPickItem<ISnippet>[]> {
let items: IAzureQuickPickItem<ISnippet>[] = [];
const snippets = await ext.snippetManager.value.getSnippets(KnownContexts.resources);
for (const snippet of snippets) {
items.push({
label: snippet.name,
data: snippet
});
}
return items.sort((a, b) => a.label.localeCompare(b.label));
}
export function getQuickPickItem(label: string, snippet: ISnippet): IAzureQuickPickItem<ISnippet> {
return { label: label, data: snippet };
}
export function getItemTypeQuickPicks(): QuickPickItem<TemplateSectionType>[] {
let items: QuickPickItem<TemplateSectionType>[] = [];
items.push(new QuickPickItem<TemplateSectionType>("Function", TemplateSectionType.Functions, "Insert a function"));
items.push(new QuickPickItem<TemplateSectionType>("Output", TemplateSectionType.Outputs, "Insert an output"));
items.push(new QuickPickItem<TemplateSectionType>("Parameter", TemplateSectionType.Parameters, "Insert a parameter"));
items.push(new QuickPickItem<TemplateSectionType>("Resource", TemplateSectionType.Resources, "Insert a resource"));
items.push(new QuickPickItem<TemplateSectionType>("Variable", TemplateSectionType.Variables, "Insert a variable"));
return items;
}
export class InsertItem {
private ui: IAzureUserInput;
constructor(ui: IAzureUserInput) {
this.ui = ui;
}
public async insertItem(template: DeploymentTemplateDoc | undefined, sectionType: TemplateSectionType, textEditor: vscode.TextEditor, context: IActionContext): Promise<void> {
if (!template) {
return;
}
switch (sectionType) {
case TemplateSectionType.Functions:
await this.insertFunction(template.topLevelValue, textEditor, context);
vscode.window.showInformationMessage("Please type the output of the function.");
break;
case TemplateSectionType.Outputs:
await this.insertOutput(template.topLevelValue, textEditor, context);
vscode.window.showInformationMessage("Please type the value of the output.");
break;
case TemplateSectionType.Parameters:
await this.insertParameter(template.topLevelValue, textEditor, context);
vscode.window.showInformationMessage("Done inserting parameter.");
break;
case TemplateSectionType.Resources:
await this.insertResource(template.topLevelValue, textEditor, context);
vscode.window.showInformationMessage("Press TAB to move between the tab stops.");
break;
case TemplateSectionType.Variables:
await this.insertVariable(template.topLevelValue, textEditor, context);
vscode.window.showInformationMessage("Please type the value of the variable.");
break;
case TemplateSectionType.TopLevel:
assert.fail("Unknown insert item type!");
default:
assertNever(sectionType);
}
}
private getTemplateObjectPart(templateTopLevel: ObjectValue | undefined, templatePart: string): Json.ObjectValue | undefined {
return this.getTemplatePart(templateTopLevel, templatePart)?.asObjectValue;
}
private getTemplateArrayPart(templateTopLevel: ObjectValue | undefined, templatePart: string): Json.ArrayValue | undefined {
return this.getTemplatePart(templateTopLevel, templatePart)?.asArrayValue;
}
private getTemplatePart(templateTopLevel: ObjectValue | undefined, templatePart: string): Json.Value | undefined {
return templateTopLevel?.getPropertyValue(templatePart);
}
public async insertParameterWithDefaultValue(templateTopLevel: ObjectValue | undefined, textEditor: vscode.TextEditor, context: IActionContext, name: string, value: string, description: string, options?: { undoStopBefore: boolean; undoStopAfter: boolean }): Promise<string> {
let parameter: Parameter = {
type: "string",
defaultValue: value
};
if (description) {
parameter.metadata = {
description: description
};
}
await this.insertInObject({
templateTopLevel,
textEditor,
part: templateKeys.parameters,
data: parameter,
name,
context,
setCursor: false,
reveal: false,
options: options
});
return name;
}
private async insertParameter(templateTopLevel: ObjectValue | undefined, textEditor: vscode.TextEditor, context: IActionContext): Promise<void> {
let name = await this.ui.showInputBox({ prompt: "Name of parameter?" });
const parameterType = await this.ui.showQuickPick(getItemType(), { placeHolder: 'Type of parameter?' });
let parameter: Parameter = {
type: parameterType.value
};
let defaultValue = await this.ui.showInputBox({ prompt: "Default value? Leave empty for no default value.", });
if (defaultValue) {
parameter.defaultValue = this.getDefaultValue(defaultValue, parameterType.value, context);
}
let description = await this.ui.showInputBox({ prompt: "Description? Leave empty for no description.", });
if (description) {
parameter.metadata = {
description: description
};
}
await this.insertInObject({
templateTopLevel,
textEditor,
part: templateKeys.parameters,
data: parameter,
name,
context,
setCursor: false
});
}
private throwExpectedError(message: string, context: IActionContext, suppressReportIssue: boolean = true): void {
context.errorHandling.suppressReportIssue = suppressReportIssue;
throw new Error(message);
}
private getDefaultValue(defaultValue: string, parameterType: ItemType, context: IActionContext): string | number | boolean | unknown | {} | [] {
switch (parameterType) {
case "int":
let intValue = Number(defaultValue);
if (isNaN(intValue)) {
this.throwExpectedError("Please enter a valid integer value", context);
}
return intValue;
case "array":
try {
return JSON.parse(defaultValue);
} catch (error) {
this.throwExpectedError("Please enter a valid array value", context);
}
break;
case "object":
case "secureobject":
try {
return JSON.parse(defaultValue);
} catch (error) {
this.throwExpectedError("Please enter a valid object value", context);
}
break;
case "bool":
switch (defaultValue) {
case "true":
return true;
case "false":
return false;
default:
this.throwExpectedError("Please enter 'true' or 'false'", context);
}
break;
case "string":
case "securestring":
return defaultValue;
default:
assertNever(parameterType);
}
}
public async insertInObject(
{ templateTopLevel,
textEditor,
part,
data,
name,
context,
setCursor = true,
reveal = true,
options = { undoStopBefore: true, undoStopAfter: true }
}: {
templateTopLevel: ObjectValue | undefined;
textEditor: vscode.TextEditor;
part: string;
data: Data | unknown;
name: string;
context: IActionContext;
setCursor?: boolean;
reveal?: boolean;
options?: { undoStopBefore: boolean; undoStopAfter: boolean };
}): Promise<void> {
let templatePart = this.getTemplateObjectPart(templateTopLevel, part);
if (!templatePart) {
if (!templateTopLevel) {
context.errorHandling.suppressReportIssue = true;
throw new Error(invalidTemplateMessage);
}
let subPart: Data = {};
subPart[name] = data;
await this.insertInObjectHelper({
templatePart: templateTopLevel,
textEditor,
data: subPart,
name: part,
setCursor,
reveal,
options
});
} else {
await this.insertInObjectHelper({
templatePart,
textEditor,
data,
name,
setCursor,
reveal,
options
});
}
}
/**
* Insert data into an template object (parameters, variables and outputs).
* @returns The document index of the cursor after the text has been inserted.
*/
// tslint:disable-next-line:no-any
private async insertInObjectHelper(
{ templatePart,
textEditor,
data,
name,
setCursor = true,
reveal = true,
options = { undoStopBefore: true, undoStopAfter: true }
}: {
templatePart: Json.ObjectValue; // The parent to place the new text into
textEditor: vscode.TextEditor;
// tslint:disable-next-line:no-any
data: any;
name: string;
setCursor?: boolean;
reveal?: boolean;
options?: { undoStopBefore: boolean; undoStopAfter: boolean };
}): Promise<number> {
let isFirstItem = templatePart.properties.length === 0;
let startText = isFirstItem ? '' : ',';
// Figure out the indenting level based on existing text
let templatePartStartPos = textEditor.document.positionAt(templatePart.span.startIndex);
let templatePartStartLine = textEditor.document.lineAt(templatePartStartPos.line);
// tslint:disable-next-line: no-non-null-assertion // Will always match at least empty string
let templatePartInitialWhitespace: string = templatePartStartLine.text.match(/^\s*/)![0];
let spacesPerTab = Math.max(1, Number(textEditor.options.tabSize) ?? 1);
let templatePartIndentColumn = templatePartInitialWhitespace.replace(/\t/g, ' '.repeat(spacesPerTab)).length;
spacesPerTab = Number.isSafeInteger(spacesPerTab) ? spacesPerTab : 1;
let templatePartIndentLevel = Math.max(0, Math.floor(templatePartIndentColumn / spacesPerTab));
let textIndentLevel = templatePartIndentLevel + 1;
let insertIndex = isFirstItem ?
templatePart.span.endIndex :
templatePart.properties[templatePart.properties.length - 1].span.afterEndIndex;
let endTabs = '\t'.repeat(textIndentLevel - 1);
let endText = isFirstItem ? `\r\n${endTabs}` : ``;
let text = typeof (data) === 'object' ? JSON.stringify(data, null, '\t') : `"${data}"`;
let indentedText = this.indent(`\r\n"${name}": ${text}`, textIndentLevel);
return await this.insertText(textEditor, insertIndex, `${startText}${indentedText}${endText}`, setCursor, reveal, options);
}
private async insertVariable(templateTopLevel: ObjectValue | undefined, textEditor: vscode.TextEditor, context: IActionContext): Promise<void> {
let name = await this.ui.showInputBox({ prompt: "Name of variable?" });
await this.insertInObject({
templateTopLevel,
textEditor,
part: templateKeys.variables,
data: insertCursorText,
name,
context
});
}
public async insertVariableWithValue(templateTopLevel: ObjectValue | undefined, textEditor: vscode.TextEditor, context: IActionContext, name: string, value: string, options?: { undoStopBefore: boolean; undoStopAfter: boolean }): Promise<void> {
await this.insertInObject({
templateTopLevel,
textEditor,
part: templateKeys.variables,
data: value,
name,
context,
setCursor: false,
reveal: false,
options: options
});
}
private async insertOutput(templateTopLevel: ObjectValue | undefined, textEditor: vscode.TextEditor, context: IActionContext): Promise<void> {
let name = await this.ui.showInputBox({ prompt: "Name of output?" });
const outputType = await this.ui.showQuickPick(getItemType(), { placeHolder: 'Type of output?' });
let output: Output = {
type: outputType.value,
value: insertCursorText.replace(/"/g, '')
};
await this.insertInObject({
templateTopLevel,
textEditor,
part: templateKeys.outputs,
data: output,
name,
context
});
}
private async insertFunctionAsTopLevel(topLevel: Json.ObjectValue | undefined, textEditor: vscode.TextEditor, context: IActionContext): Promise<void> {
if (!topLevel) {
context.errorHandling.suppressReportIssue = true;
throw new Error(invalidTemplateMessage);
}
let functions = [await this.getFunctionNamespace()];
await this.insertInObjectHelper({
templatePart: topLevel,
textEditor,
data: functions,
name: templateKeys.functions,
});
}
private async insertFunctionAsNamespace(functions: Json.ArrayValue, textEditor: vscode.TextEditor): Promise<void> {
let namespace = await this.getFunctionNamespace();
await this.insertInArray(functions, textEditor, namespace);
}
private async insertFunctionAsMembers(namespace: Json.ObjectValue, textEditor: vscode.TextEditor): Promise<void> {
let functionName = await this.ui.showInputBox({ prompt: "Name of function?" });
let functionDef = await this.getFunction();
// tslint:disable-next-line:no-any
let members: any = {};
// tslint:disable-next-line:no-unsafe-any
members[functionName] = functionDef;
await this.insertInObjectHelper({
templatePart: namespace,
textEditor,
data: members,
name: templateKeys.userFunctionMembers,
});
}
private async insertFunctionAsFunction(members: Json.ObjectValue, textEditor: vscode.TextEditor): Promise<void> {
let functionName = await this.ui.showInputBox({ prompt: "Name of function?" });
let functionDef = await this.getFunction();
await this.insertInObjectHelper({
templatePart: members,
textEditor,
data: functionDef,
name: functionName,
});
}
private async insertFunction(templateTopLevel: ObjectValue | undefined, textEditor: vscode.TextEditor, context: IActionContext): Promise<void> {
let functions = this.getTemplateArrayPart(templateTopLevel, templateKeys.functions);
if (!functions) {
// tslint:disable-next-line:no-unsafe-any
await this.insertFunctionAsTopLevel(templateTopLevel, textEditor, context);
return;
}
if (functions.length === 0) {
await this.insertFunctionAsNamespace(functions, textEditor);
return;
}
let namespace = Json.asObjectValue(functions.elements[0]);
if (!namespace) {
context.errorHandling.suppressReportIssue = true;
throw new Error(`The first namespace in "functions" is not an object`);
}
let members = namespace.getPropertyValue(templateKeys.userFunctionMembers);
if (!members) {
await this.insertFunctionAsMembers(namespace, textEditor);
return;
}
let membersObject = Json.asObjectValue(members);
if (!membersObject) {
context.errorHandling.suppressReportIssue = true;
throw new Error(`The first namespace in "functions" does not have members as an object!`);
}
await this.insertFunctionAsFunction(membersObject, textEditor);
return;
}
private async insertResource(templateTopLevel: ObjectValue | undefined, textEditor: vscode.TextEditor, context: IActionContext): Promise<void> {
let resources = this.getTemplateArrayPart(templateTopLevel, templateKeys.resources);
let index: number;
let prepend = "\r\n\t\t\r\n\t";
if (!resources) {
if (!templateTopLevel) {
context.errorHandling.suppressReportIssue = true;
throw new Error(invalidTemplateMessage);
}
// tslint:disable-next-line:no-any
let subPart: any = [];
index = await this.insertInObjectHelper({
templatePart: templateTopLevel,
textEditor,
data: subPart,
name: templateKeys.resources,
});
} else {
index = resources.span.endIndex;
if (resources.elements.length > 0) {
let lastIndex = resources.elements.length - 1;
index = resources.elements[lastIndex].span.afterEndIndex;
prepend = `,\r\n\t\t`;
}
}
const resource = await this.ui.showQuickPick(await getResourceSnippets(), { placeHolder: 'What resource do you want to insert?' });
await this.insertText(textEditor, index, prepend);
let newCursorPosition = this.getCursorPositionForInsertResource(textEditor, index, prepend);
textEditor.selection = new vscode.Selection(newCursorPosition, newCursorPosition);
await commands.executeCommand('editor.action.insertSnippet', { snippet: resource.data.insertText });
textEditor.revealRange(new vscode.Range(newCursorPosition, newCursorPosition), vscode.TextEditorRevealType.AtTop);
}
private getCursorPositionForInsertResource(textEditor: vscode.TextEditor, index: number, prepend: string): vscode.Position {
let prependRange = new vscode.Range(textEditor.document.positionAt(index), textEditor.document.positionAt(index + this.formatText(prepend, textEditor).length));
let prependFromDocument = textEditor.document.getText(prependRange);
let lookFor = this.formatText('\t\t', textEditor);
let cursorPos = prependFromDocument.indexOf(lookFor);
return textEditor.document.positionAt(index + cursorPos + lookFor.length);
}
private async getFunction(): Promise<Function> {
const outputType = await this.ui.showQuickPick(getItemType(), { placeHolder: 'Type of function output?' });
let parameters = await this.getFunctionParameters();
let functionDef = {
parameters: parameters,
output: {
type: outputType.value,
value: insertCursorText
}
};
return functionDef;
}
private async getFunctionParameters(): Promise<FunctionParameter[]> {
let parameterName: string;
let parameters = [];
do {
const msg = parameters.length === 0 ? "Name of first parameter?" : "Name of next parameter?";
const leaveEmpty = "Press 'Enter' if there are no more parameters.";
parameterName = await this.ui.showInputBox({ prompt: msg, placeHolder: leaveEmpty });
if (parameterName !== '') {
const parameterType = await this.ui.showQuickPick(getItemType(), { placeHolder: `Type of parameter ${parameterName}?` });
parameters.push({
name: parameterName,
type: parameterType.value
});
}
} while (parameterName !== '');
return parameters;
}
// tslint:disable-next-line:no-any
private async insertInArray(templatePart: Json.ArrayValue, textEditor: vscode.TextEditor, data: any): Promise<void> {
let index = templatePart.span.endIndex;
let text = JSON.stringify(data, null, '\t');
let indentedText = this.indent(`\r\n${text}\r\n`, 2);
await this.insertText(textEditor, index, `${indentedText}\t`);
}
private async getFunctionNamespace(): Promise<FunctionNameSpace> {
let namespaceName = await this.ui.showInputBox({ prompt: "Name of namespace?" });
let namespace = {
namespace: namespaceName,
members: await this.getFunctionMembers()
};
return namespace;
}
// tslint:disable-next-line:no-any
private async getFunctionMembers(): Promise<any> {
let functionName = await this.ui.showInputBox({ prompt: "Name of function?" });
let functionDef = await this.getFunction();
// tslint:disable-next-line:no-any
let members: any = {};
// tslint:disable-next-line:no-unsafe-any
members[functionName] = functionDef;
return members;
}
/**
* Insert text into the document.
* @param textEditor The text editor to insert the text into.
* @param index The document index where to insert the text.
* @param text The text to be inserted.
* @param setCursor If the cursor should be set
* @param options If undostops should be created before and after the edit
* @returns The document index of the cursor after the text has been inserted.
*/
private async insertText(textEditor: vscode.TextEditor, index: number, text: string, setCursor: boolean = true, reveal: boolean = true, options?: { undoStopBefore: boolean; undoStopAfter: boolean }): Promise<number> {
text = this.formatText(text, textEditor);
let pos = textEditor.document.positionAt(index);
await textEditor.edit(builder => builder.insert(pos, text), options);
if (reveal) {
let endPos = textEditor.document.positionAt(index + text.length);
textEditor.revealRange(new vscode.Range(pos, endPos), vscode.TextEditorRevealType.Default);
}
if (setCursor && text.lastIndexOf(insertCursorText) >= 0) {
let insertedText = textEditor.document.getText(new vscode.Range(pos, textEditor.document.positionAt(index + text.length)));
let cursorPos = insertedText.lastIndexOf(insertCursorText);
let newIndex = index + cursorPos + insertCursorText.length / 2;
let pos2 = textEditor.document.positionAt(newIndex);
textEditor.selection = new vscode.Selection(pos2, pos2);
return newIndex;
}
return 0;
}
private formatText(text: string, textEditor: vscode.TextEditor): string {
if (textEditor.options.insertSpaces === true) {
text = text.replace(/\t/g, ' '.repeat(Number(textEditor.options.tabSize)));
} else {
text = text.replace(/ {4}/g, '\t');
}
return text;
}
/**
* Indents the given string
* @param str The string to be indented.
* @param numOfTabs The amount of indentations to place at the
* beginning of each line of the string.
* @return The new string with each line beginning with the desired
* amount of indentation.
*/
private indent(str: string, numOfTabs: number): string {
// tslint:disable-next-line:prefer-array-literal
str = str.replace(/^(?=.)/gm, '\t'.repeat(numOfTabs));
return str;
}
}
interface ParameterMetaData {
description: string;
}
interface Parameter extends Data {
// tslint:disable-next-line:no-reserved-keywords
type: string;
defaultValue?: string | number | boolean | unknown | {} | [];
metadata?: ParameterMetaData;
}
interface Output extends Data {
// tslint:disable-next-line:no-reserved-keywords
type: string;
value: string;
}
interface Function extends Data {
parameters: Parameter[];
output: Output;
}
interface FunctionParameter extends Data {
name: string;
// tslint:disable-next-line:no-reserved-keywords
type: string;
}
interface FunctionNameSpace {
namespace: string;
// tslint:disable-next-line:no-any
members: any[];
}
type Data = { [key: string]: unknown }; | the_stack |
import * as _ from 'lodash';
import * as express from 'express';
import * as cors from 'cors';
import corsGate = require('cors-gate');
import * as http from 'http';
import * as net from 'net';
import * as bodyParser from 'body-parser';
import * as Ws from 'ws';
import { v4 as uuid } from "uuid";
import { graphqlHTTP } from 'express-graphql';
import { execute, formatError, GraphQLScalarType, subscribe } from 'graphql';
import gql from 'graphql-tag';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { SubscriptionServer } from '@httptoolkit/subscriptions-transport-ws';
import { EventEmitter } from 'stream';
import DuplexPair = require('native-duplexpair');
import { destroyable, DestroyableServer } from "../util/destroyable-server";
import { isErrorLike } from '../util/error';
import { objectAllPromise } from '../util/promise';
import { DEFAULT_ADMIN_SERVER_PORT } from '../types';
import type { Mockttp } from '../mockttp';
import { RuleParameters } from '../rules/rule-parameters';
import { AdminPlugin, PluginConstructorMap, PluginStartParamsMap } from './admin-plugin-types';
import { parseAnyAst } from './graphql-utils';
import { MockttpAdminPlugin } from './mockttp-admin-plugin';
export interface AdminServerOptions<Plugins extends { [key: string]: AdminPlugin<any, any> }> {
/**
* Should the admin server print extra debug information? This enables admin server debugging
* only - individual mock session debugging must be enabled separately.
*/
debug?: boolean;
/**
* Set CORS options to limit the sites which can send requests to manage this admin server.
*/
corsOptions?: cors.CorsOptions & { strict?: boolean };
/**
* Set a keep alive frequency in milliseconds for the subscription & stream websockets of each
* session, to ensure they remain connected in long-lived connections, especially in browsers which
* often close quiet background connections automatically.
*/
webSocketKeepAlive?: number;
/**
* Override the default parameters for sessions started from this admin server. These values will be
* used for each setting that is not explicitly specified by the client when creating a mock session.
*/
pluginDefaults?: Partial<PluginStartParamsMap<Plugins>>;
/**
* Some rule options can't easily be specified in remote clients, since they need to access
* server-side state or Node APIs directly. To handle this, referenceable parameters can
* be provided here, and referenced with a `{ [MOCKTTP_PARAM_REF]: <value> }` value in place
* of the real parameter in the remote client.
*/
ruleParameters?: {
[key: string]: any
}
/**
* @internal
*
* This API is not yet stable, and is intended for internal use only. It may change in future
* in minor versions without warning.
*
* This defines admin plugin modules: remote-controlled types of mocks that should be attached to this
* admin server, to allow configuring other mocking services through the same HTTP infrastructure.
*
* This can be useful when mocking non-HTTP protocols like WebRTC.
*/
adminPlugins?: PluginConstructorMap<Plugins>
}
async function strictOriginMatch(
origin: string | undefined,
expectedOrigin: cors.CorsOptions['origin']
): Promise<boolean> {
if (!origin) return false;
if (typeof expectedOrigin === 'string') {
return expectedOrigin === origin;
}
if (_.isRegExp(expectedOrigin)) {
return !!origin.match(expectedOrigin);
}
if (_.isArray(expectedOrigin)) {
return _.some(expectedOrigin, (exp) =>
strictOriginMatch(origin, exp)
);
}
if (_.isFunction(expectedOrigin)) {
return new Promise<boolean>((resolve, reject) => {
expectedOrigin(origin, (error, result) => {
if (error) reject(error);
else resolve(strictOriginMatch(origin, result));
});
});
}
// We don't allow boolean or undefined matches
return false;
}
export class AdminServer<Plugins extends { [key: string]: AdminPlugin<any, any> }> {
private debug: boolean;
private requiredOrigin: cors.CorsOptions['origin'] | false;
private webSocketKeepAlive: number | undefined;
private ruleParams: RuleParameters;
private app = express();
private server: DestroyableServer & http.Server | null = null;
private eventEmitter = new EventEmitter();
private adminPlugins: PluginConstructorMap<Plugins>;
private sessions: { [id: string]: {
router: express.Router,
stop: () => Promise<void>,
subscriptionServer: SubscriptionServer,
streamServer: Ws.Server,
sessionPlugins: Plugins
} } = { };
constructor(options: AdminServerOptions<Plugins> = {}) {
this.debug = options.debug || false;
if (this.debug) console.log('Admin server started in debug mode');
this.webSocketKeepAlive = options.webSocketKeepAlive || undefined;
this.ruleParams = options.ruleParameters || {};
this.adminPlugins = options.adminPlugins || {} as PluginConstructorMap<Plugins>;
this.app.use(cors(options.corsOptions));
// If you use strict CORS, and set a specific origin, we'll enforce it:
this.requiredOrigin = !!options.corsOptions &&
!!options.corsOptions.strict &&
!!options.corsOptions.origin &&
typeof options.corsOptions.origin !== 'boolean' &&
options.corsOptions.origin;
if (this.requiredOrigin) {
this.app.use(corsGate({
strict: true, // MUST send an allowed origin
allowSafe: false, // Even for HEAD/GET requests (should be none anyway)
origin: '' // No base origin - we accept *no* same-origin requests
}));
}
this.app.use(bodyParser.json({ limit: '50mb' }));
const defaultPluginStartParams: Partial<PluginStartParamsMap<Plugins>> = options.pluginDefaults ?? {};
this.app.post('/start', async (req, res) => {
try {
const rawConfig = req.body;
// New clients send: "{ plugins: { http: {...}, webrtc: {...} } }" etc. Old clients just send
// the HTTP options bare with no wrapper, so we wrap them for backward compat.
const isPluginAwareClient = ('plugins' in rawConfig);
const providedPluginStartParams = (!isPluginAwareClient
? { // Backward compat: this means the client is not plugin-aware, and so all options are Mockttp options
http: {
options: _.cloneDeep(rawConfig),
port: (typeof req.query.port === 'string')
? JSON.parse(req.query.port)
: undefined
}
}
: rawConfig.plugins
) as PluginStartParamsMap<Plugins>;
// For each plugin that was specified, we pull default params into their start params.
const pluginStartParams = _.mapValues((providedPluginStartParams), (params, pluginId) => {
return _.merge({}, defaultPluginStartParams[pluginId], params);
});
if (this.debug) console.log('Admin server starting mock session with config', pluginStartParams);
// Backward compat: do an explicit check for HTTP port conflicts
const httpPort = (pluginStartParams as { http?: { port: number } }).http?.port;
if (_.isNumber(httpPort) && this.sessions[httpPort] != null) {
res.status(409).json({
error: `Cannot start: mock server is already running on port ${httpPort}`
});
return;
}
const missingPluginId = Object.keys(pluginStartParams).find(pluginId => !(pluginId in this.adminPlugins));
if (missingPluginId) {
res.status(400).json({
error: `Request to mock using unrecognized plugin: ${missingPluginId}`
});
return;
}
const sessionPlugins = _.mapValues(pluginStartParams, (__, pluginId: keyof Plugins) => {
const PluginType = this.adminPlugins[pluginId];
return new PluginType();
}) as Plugins;
const pluginStartResults = await objectAllPromise(
_.mapValues(sessionPlugins, (plugin, pluginId: keyof Plugins) =>
plugin.start(pluginStartParams[pluginId])
)
);
// More backward compat: old clients assume that the port is also the management id.
const sessionId = isPluginAwareClient
? uuid()
: (sessionPlugins as any as {
'http': MockttpAdminPlugin
}).http.getMockServer().port.toString();
await this.startSessionManagementAPI(sessionId, sessionPlugins);
if (isPluginAwareClient) {
res.json({
id: sessionId,
pluginData: pluginStartResults
});
} else {
res.json({
id: sessionId,
...(pluginStartResults['http']!)
});
}
} catch (e) {
res.status(500).json({ error: `Failed to start mock session: ${
(isErrorLike(e) && e.message) || e
}` });
}
});
this.app.post('/reset', async (req, res) => {
try {
await this.resetAdminServer();
res.json({ success: true });
} catch (e) {
res.status(500).json({
error: (isErrorLike(e) && e.message) || 'Unknown error'
});
}
});
// Dynamically route to mock sessions ourselves, so we can easily add/remove
// sessions as we see fit later on.
const sessionRequest = (req: express.Request, res: express.Response, next: express.NextFunction) => {
const sessionId = req.params.id;
const sessionRouter = this.sessions[sessionId]?.router;
if (!sessionRouter) {
res.status(404).send('Unknown mock session');
console.error(`Request for unknown mock session with id: ${sessionId}`);
return;
}
sessionRouter(req, res, next);
}
this.app.use('/session/:id/', sessionRequest);
this.app.use('/server/:id/', sessionRequest); // Old URL for backward compat
}
async resetAdminServer() {
if (this.debug) console.log('Resetting admin server');
await Promise.all(
Object.values(this.sessions).map(({ stop }) => stop())
);
}
/**
* Subscribe to hear when each mock ession is started. The listener is provided the
* session plugin data, which can be used to log session startup, add side-effects that
* run elsewhere at startup, or preconfigure every started plugin in addition ways.
*
* This is run synchronously when a session is created, after it has fully started
* but before its been returned to remote clients.
*/
on(event: 'mock-session-started', listener: (plugins: Plugins) => void): void;
/**
* Subscribe to hear when a mock session is stopped. The listener is provided with
* the state of all plugins that are about to be stopped. This can be used to log
* mock session shutdown, add side-effects that run elsewhere at shutdown, or clean
* up after sessions in other ways.
*
* This is run synchronously immediately before the session is shutdown, whilst all
* its state is still available, and before remote clients have had any response to
* their request. This is also run before shutdown when the admin server itself is
* cleanly shutdown with `adminServer.stop()`.
*/
on(event: 'mock-session-stopping', listener: (plugins: Plugins) => void): void;
on(event: string, listener: (...args: any) => void): void {
this.eventEmitter.on(event, listener);
}
async start(
listenOptions: number | {
port: number,
host: string
} = DEFAULT_ADMIN_SERVER_PORT
) {
if (this.server) throw new Error('Admin server already running');
await new Promise<void>((resolve, reject) => {
this.server = destroyable(this.app.listen(listenOptions, resolve));
this.server.on('error', reject);
this.server.on('upgrade', async (req: http.IncomingMessage, socket: net.Socket, head: Buffer) => {
const reqOrigin = req.headers['origin'] as string | undefined;
if (this.requiredOrigin && !await strictOriginMatch(reqOrigin, this.requiredOrigin)) {
console.warn(`Websocket request from invalid origin: ${req.headers['origin']}`);
socket.destroy();
return;
}
const isSubscriptionRequest = req.url!.match(/^\/(?:server|session)\/([\w\d\-]+)\/subscription$/);
const isStreamRequest = req.url!.match(/^\/(?:server|session)\/([\w\d\-]+)\/stream$/);
const isMatch = isSubscriptionRequest || isStreamRequest;
if (isMatch) {
const sessionId = isMatch[1];
let wsServer: Ws.Server = isSubscriptionRequest
? this.sessions[sessionId]?.subscriptionServer.server
: this.sessions[sessionId]?.streamServer;
if (wsServer) {
wsServer.handleUpgrade(req, socket, head, (ws) => {
wsServer.emit('connection', ws, req);
});
} else {
console.warn(`Websocket request for unrecognized mock session: ${sessionId}`);
socket.destroy();
}
} else {
console.warn(`Unrecognized websocket request for ${req.url}`);
socket.destroy();
}
});
});
}
private async startSessionManagementAPI(sessionId: string, plugins: Plugins): Promise<void> {
const mockSessionRouter = express.Router();
let running = true;
const stopSession = async () => {
if (!running) return;
running = false;
this.eventEmitter.emit('mock-session-stopping', plugins);
const session = this.sessions[sessionId];
delete this.sessions[sessionId];
await Promise.all(Object.values(plugins).map(plugin => plugin.stop()));
session.subscriptionServer.close();
// Close with code 1000 (purpose is complete - no more streaming happening)
session.streamServer.clients.forEach((client) => {
client.close(1000);
});
session.streamServer.close();
session.streamServer.emit('close');
};
mockSessionRouter.post('/stop', async (req, res) => {
await stopSession();
res.json({ success: true });
});
// A pair of sockets, representing the 2-way connection between the session & WSs.
// All websocket messages are written to wsSocket, and then read from sessionSocket
// All session messages are written to sessionSocket, and then read from wsSocket and sent
const { socket1: wsSocket, socket2: sessionSocket } = new DuplexPair();
// This receives a lot of listeners! One channel per matcher, handler & completion checker,
// and each adds listeners for data/error/finish/etc. That's OK, it's not generally a leak,
// but maybe 100 would be a bit suspicious (unless you have 30+ active rules).
sessionSocket.setMaxListeners(100);
if (this.debug) {
sessionSocket.on('data', (d: any) => {
console.log('Streaming data from WS clients:', d.toString());
});
wsSocket.on('data', (d: any) => {
console.log('Streaming data to WS clients:', d.toString());
});
}
const streamServer = new Ws.Server({ noServer: true });
streamServer.on('connection', (ws) => {
let newClientStream = Ws.createWebSocketStream(ws, {});
wsSocket.pipe(newClientStream).pipe(wsSocket, { end: false });
const unpipe = () => {
wsSocket.unpipe(newClientStream);
newClientStream.unpipe(wsSocket);
};
newClientStream.on('error', unpipe);
wsSocket.on('end', unpipe);
});
streamServer.on('close', () => {
wsSocket.end();
sessionSocket.end();
});
// Handle errors by logging & stopping this session
const onStreamError = (e: Error) => {
if (!running) return; // We don't care about connection issues during shutdown
console.error("Error in admin server stream, shutting down mock session");
console.error(e);
stopSession();
};
wsSocket.on('error', onStreamError);
sessionSocket.on('error', onStreamError);
const schema = makeExecutableSchema({
typeDefs: [
AdminServer.baseSchema,
...Object.values(plugins).map(plugin => plugin.schema)
],
resolvers: [
this.buildBaseResolvers(sessionId),
...Object.values(plugins).map(plugin =>
plugin.buildResolvers(sessionSocket, this.ruleParams)
)
]
});
const subscriptionServer = SubscriptionServer.create({
schema,
execute,
subscribe,
keepAlive: this.webSocketKeepAlive
}, {
noServer: true
});
mockSessionRouter.use(
graphqlHTTP({
schema,
customFormatErrorFn: (error) => {
console.error(error.stack);
return formatError(error);
}
}
));
if (this.webSocketKeepAlive) {
// If we have a keep-alive set, send the client a ping frame every Xms to
// try and stop closes (especially by browsers) due to inactivity.
const webSocketKeepAlive = setInterval(() => {
[
...streamServer.clients,
...subscriptionServer.server.clients
].forEach((client) => {
if (client.readyState !== Ws.OPEN) return;
client.ping();
});
}, this.webSocketKeepAlive);
// We use the stream server's shutdown as an easy proxy event for full shutdown:
streamServer.on('close', () => clearInterval(webSocketKeepAlive));
}
this.sessions[sessionId] = {
sessionPlugins: plugins,
router: mockSessionRouter,
streamServer,
subscriptionServer,
stop: stopSession
};
this.eventEmitter.emit('mock-session-started', plugins);
}
stop(): Promise<void> {
if (!this.server) return Promise.resolve();
return Promise.all([
this.server.destroy(),
].concat(
Object.values(this.sessions).map((s) => s.stop())
)).then(() => {
this.server = null;
});
}
private static baseSchema = gql`
type Mutation {
reset: Void
enableDebug: Void
}
type Query {
ruleParameterKeys: [String!]!
}
type Subscription {
_empty_placeholder_: Void # A placeholder so we can define an empty extendable type
}
scalar Void
scalar Raw
scalar Json
scalar Buffer
`;
private buildBaseResolvers(sessionId: string) {
return {
Query: {
ruleParameterKeys: () => this.ruleParameterKeys
},
Mutation: {
reset: () => this.resetPluginsForSession(sessionId),
enableDebug: () => this.enableDebugForSession(sessionId)
},
Raw: new GraphQLScalarType({
name: 'Raw',
description: 'A raw entity, serialized directly (must be JSON-compatible)',
serialize: (value: any) => value,
parseValue: (input: string): any => input,
parseLiteral: parseAnyAst
}),
// Json exists just for API backward compatibility - all new data should be Raw.
// Converting to JSON is pointless, since bodies all contain JSON anyway.
Json: new GraphQLScalarType({
name: 'Json',
description: 'A JSON entity, serialized as a simple JSON string',
serialize: (value: any) => JSON.stringify(value),
parseValue: (input: string): any => JSON.parse(input),
parseLiteral: parseAnyAst
}),
Void: new GraphQLScalarType({
name: 'Void',
description: 'Nothing at all',
serialize: (value: any) => null,
parseValue: (input: string): any => null,
parseLiteral: (): any => { throw new Error('Void literals are not supported') }
}),
Buffer: new GraphQLScalarType({
name: 'Buffer',
description: 'A buffer',
serialize: (value: Buffer) => {
return value.toString('base64');
},
parseValue: (input: string) => {
return Buffer.from(input, 'base64');
},
parseLiteral: parseAnyAst
})
};
};
private resetPluginsForSession(sessionId: string) {
return Promise.all(
Object.values(this.sessions[sessionId].sessionPlugins).map(plugin =>
plugin.reset?.()
)
);
}
private enableDebugForSession(sessionId: string) {
return Promise.all(
Object.values(this.sessions[sessionId].sessionPlugins).map(plugin =>
plugin.enableDebug?.()
)
);
}
get ruleParameterKeys() {
return Object.keys(this.ruleParams);
}
} | the_stack |
import { createMemoryHistory as createHistory } from 'history'
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import { MemoryRouter, Router, withRouter } from 'react-router'
import NotLiveRoute from '../src/index'
import renderStrict from './utils/renderStrict'
const Route = withRouter(NotLiveRoute)
describe('A <Route>', () => {
const node = document.createElement('div')
afterEach(() => {
ReactDOM.unmountComponentAtNode(node)
})
describe('without a <Router>', () => {
it('throws an error', () => {
jest.spyOn(console, 'error').mockImplementation(() => {})
expect(() => {
renderStrict(<Route />, node)
}).toThrow(/You should not use <Route> outside a <Router>/)
})
})
it('renders when it matches', () => {
const text = 'cupcakes'
renderStrict(
<MemoryRouter initialEntries={['/cupcakes']}>
<Route path="/cupcakes" render={() => <h1>{text}</h1>} />
</MemoryRouter>,
node
)
expect(node.innerHTML).toContain(text)
})
it('renders when it matches at the root URL', () => {
const text = 'cupcakes'
renderStrict(
<MemoryRouter initialEntries={['/']}>
<Route path="/" render={() => <h1>{text}</h1>} />
</MemoryRouter>,
node
)
expect(node.innerHTML).toContain(text)
})
it('does not render when it does not match', () => {
const text = 'bubblegum'
renderStrict(
<MemoryRouter initialEntries={['/bunnies']}>
<Route path="/flowers" render={() => <h1>{text}</h1>} />
</MemoryRouter>,
node
)
expect(node.innerHTML).not.toContain(text)
})
it('matches using nextContext when updating', () => {
const history = createHistory({
initialEntries: ['/sushi/california']
})
renderStrict(
<Router history={history}>
<Route path="/sushi/:roll" render={({ match }) => <h1>{match.url}</h1>} />
</Router>,
node
)
history.push('/sushi/spicy-tuna')
expect(node.innerHTML).toContain('/sushi/spicy-tuna')
})
describe('with dynamic segments in the path', () => {
it('decodes them', () => {
renderStrict(
<MemoryRouter initialEntries={['/a%20dynamic%20segment']}>
<Route path="/:id" render={({ match }) => <h1>{match.params.id}</h1>} />
</MemoryRouter>,
node
)
expect(node.innerHTML).toContain('a dynamic segment')
})
})
describe('with an array of paths', () => {
it('matches the first provided path', () => {
const node = document.createElement('div')
ReactDOM.render(
<MemoryRouter initialEntries={['/hello']}>
<Route path={['/hello', '/world']} render={() => <div>Hello World</div>} />
</MemoryRouter>,
node
)
expect(node.innerHTML).toContain('Hello World')
})
it('matches other provided paths', () => {
const node = document.createElement('div')
ReactDOM.render(
<MemoryRouter initialEntries={['/other', '/world']} initialIndex={1}>
<Route path={['/hello', '/world']} render={() => <div>Hello World</div>} />
</MemoryRouter>,
node
)
expect(node.innerHTML).toContain('Hello World')
})
it('provides the matched path as a string', () => {
const node = document.createElement('div')
ReactDOM.render(
<MemoryRouter initialEntries={['/other', '/world']} initialIndex={1}>
<Route path={['/hello', '/world']} render={({ match }) => <div>{match.path}</div>} />
</MemoryRouter>,
node
)
expect(node.innerHTML).toContain('/world')
})
it("doesn't remount when moving from one matching path to another", () => {
const node = document.createElement('div')
const history = createHistory()
const mount = jest.fn()
class MatchedRoute extends React.Component {
componentWillMount() {
mount()
}
render() {
return <div>Hello World</div>
}
}
history.push('/hello')
ReactDOM.render(
<Router history={history}>
<Route path={['/hello', '/world']} component={MatchedRoute} />
</Router>,
node
)
expect(mount).toHaveBeenCalledTimes(1)
expect(node.innerHTML).toContain('Hello World')
history.push('/world/somewhere/else')
expect(mount).toHaveBeenCalledTimes(1)
expect(node.innerHTML).toContain('Hello World')
})
})
describe('with a unicode path', () => {
it('is able to match', () => {
renderStrict(
<MemoryRouter initialEntries={['/パス名']}>
<Route path="/パス名" render={({ match }) => <h1>{match.url}</h1>} />
</MemoryRouter>,
node
)
expect(node.innerHTML).toContain('/パス名')
})
})
describe('with escaped special characters in the path', () => {
it('is able to match', () => {
renderStrict(
<MemoryRouter initialEntries={['/pizza (1)']}>
<Route path="/pizza \(1\)" render={({ match }) => <h1>{match.url}</h1>} />
</MemoryRouter>,
node
)
expect(node.innerHTML).toContain('/pizza (1)')
})
})
describe('with `exact=true`', () => {
it('renders when the URL does not have a trailing slash', () => {
const text = 'bubblegum'
renderStrict(
<MemoryRouter initialEntries={['/somepath/']}>
<Route exact path="/somepath" render={() => <h1>{text}</h1>} />
</MemoryRouter>,
node
)
expect(node.innerHTML).toContain(text)
})
it('renders when the URL has trailing slash', () => {
const text = 'bubblegum'
renderStrict(
<MemoryRouter initialEntries={['/somepath']}>
<Route exact path="/somepath/" render={() => <h1>{text}</h1>} />
</MemoryRouter>,
node
)
expect(node.innerHTML).toContain(text)
})
describe('and `strict=true`', () => {
it('does not render when the URL has a trailing slash', () => {
const text = 'bubblegum'
renderStrict(
<MemoryRouter initialEntries={['/somepath/']}>
<Route exact strict path="/somepath" render={() => <h1>{text}</h1>} />
</MemoryRouter>,
node
)
expect(node.innerHTML).not.toContain(text)
})
it('does not render when the URL does not have a trailing slash', () => {
const text = 'bubblegum'
renderStrict(
<MemoryRouter initialEntries={['/somepath']}>
<Route exact strict path="/somepath/" render={() => <h1>{text}</h1>} />
</MemoryRouter>,
node
)
expect(node.innerHTML).not.toContain(text)
})
})
})
// describe('the `location` prop', () => {
// it('overrides `context.location`', () => {
// const text = 'bubblegum'
// renderStrict(
// <MemoryRouter initialEntries={['/cupcakes']}>
// <Route location={{ pathname: '/bubblegum' }} path="/bubblegum" render={() => <h1>{text}</h1>} />
// </MemoryRouter>,
// node
// )
// expect(node.innerHTML).toContain(text)
// })
// })
describe('the `children` prop', () => {
describe('that is an element', () => {
it('renders', () => {
const text = 'bubblegum'
renderStrict(
<MemoryRouter initialEntries={['/']}>
<Route path="/">
<h1>{text}</h1>
</Route>
</MemoryRouter>,
node
)
expect(node.innerHTML).toContain(text)
})
})
describe('that is a function', () => {
it('receives { history, location, match } props', () => {
const history = createHistory()
let props = null
renderStrict(
<Router history={history}>
<Route
path="/"
children={p => {
props = p
return null
}}
/>
</Router>,
node
)
expect(props).not.toBe(null)
expect(props.history).toBe(history)
expect(typeof props.location).toBe('object')
expect(typeof props.match).toBe('object')
})
it('renders', () => {
const text = 'bubblegum'
renderStrict(
<MemoryRouter initialEntries={['/']}>
<Route path="/" children={() => <h1>{text}</h1>} />
</MemoryRouter>,
node
)
expect(node.innerHTML).toContain(text)
})
describe('that returns `undefined`', () => {
it('logs a warning to the console and renders nothing', () => {
jest.spyOn(console, 'warn').mockImplementation(() => {})
renderStrict(
<MemoryRouter initialEntries={['/']}>
<Route path="/" children={() => undefined} />
</MemoryRouter>,
node
)
expect(node.innerHTML).toEqual('')
expect(console.warn).toHaveBeenCalledWith(
expect.stringContaining('You returned `undefined` from the `children` function')
)
})
})
})
describe('that is an empty array (as in Preact)', () => {
it('ignores the children', () => {
const text = 'bubblegum'
renderStrict(
<MemoryRouter>
<Route render={() => <h1>{text}</h1>}>{[]}</Route>
</MemoryRouter>,
node
)
expect(node.innerHTML).toContain(text)
})
})
})
describe('the `component` prop', () => {
it('renders the component', () => {
const text = 'bubblegum'
const Home = () => <h1>{text}</h1>
renderStrict(
<MemoryRouter initialEntries={['/']}>
<Route path="/" component={Home} />
</MemoryRouter>,
node
)
expect(node.innerHTML).toContain(text)
})
it('receives { history, location, match } props', () => {
const history = createHistory()
let props = null
const Component = p => {
props = p
return null
}
renderStrict(
<Router history={history}>
<Route path="/" component={Component} />
</Router>,
node
)
expect(props).not.toBe(null)
expect(props.history).toBe(history)
expect(typeof props.location).toBe('object')
expect(typeof props.match).toBe('object')
})
// it("won't throw a prop-type warning when passed valid React components that aren't functions", () => {
// function forwardRef(Component) {
// class ForwardComponent extends React.Component {
// render() {
// const { forwardedRef, ...rest } = this.props
// return <Component ref={forwardedRef} {...rest} />
// }
// }
// return React.forwardRef((props, ref) => {
// return <ForwardComponent {...props} forwardedRef={ref} />
// })
// }
// const history = createHistory()
// const Component = () => null
// const WrappedComponent = forwardRef(Component)
// jest.spyOn(console, 'error').mockImplementation(() => {})
// ReactDOM.render(
// <Router history={history}>
// <Route path="/" component={WrappedComponent} />
// </Router>,
// node
// )
// expect(console.error).not.toHaveBeenCalled()
// })
})
describe('the `render` prop', () => {
it('renders its return value', () => {
const text = 'Mrs. Kato'
renderStrict(
<MemoryRouter initialEntries={['/']}>
<Route path="/" render={() => <h1>{text}</h1>} />
</MemoryRouter>,
node
)
expect(node.innerHTML).toContain(text)
})
it('receives { history, location, match } props', () => {
const history = createHistory()
let props = null
renderStrict(
<Router history={history}>
<Route
path="/"
render={p => {
props = p
return null
}}
/>
</Router>,
node
)
expect(props).not.toBe(null)
expect(props.history).toBe(history)
expect(typeof props.location).toBe('object')
expect(typeof props.match).toBe('object')
})
})
}) | the_stack |
import * as React from "react"
import * as Rx from "rxjs"
import * as Frame from "./Frame"
import classnames from "classnames"
import * as css from "./Ink.css"
import { Portal } from "react-portal"
import GPS from "gps"
import * as RxOps from "rxjs/operators"
import * as Content from "capstone/Content"
export interface PenPoint {
x: number
y: number
strokeWidth: number
}
export interface InkStroke {
points: PenPoint[]
settings: StrokeSettings
}
export interface Props {
strokes: InkStroke[]
mode: Content.Mode
scale?: number
onInkStroke?: (stroke: InkStroke) => void
}
export interface CanvasProps {
strokes: InkStroke[]
mode: Content.Mode
scale?: number
onInkStroke?: (stroke: InkStroke) => void
strokeType?: StrokeType
updateVisibleEraserPosition: (eraserPosition?: PenPoint) => void
}
enum StrokeType {
ink = "ink",
erase = "erase",
default = ink,
}
export interface StrokeSettings {
readonly globalCompositeOperation: string
readonly strokeStyle: string
readonly lineCap: string
readonly lineJoin: string
lineWidth: number
}
const StrokeMappings: { [st: string]: (pressure: number) => number } = {
[StrokeType.ink]: pressure => {
return Math.max(1.5, 16 * Math.pow(pressure, 12))
},
[StrokeType.erase]: pressure => {
return Math.max(16, 120 * Math.pow(pressure, 3))
},
}
const StrokeSettings: { [st: string]: StrokeSettings } = {
[StrokeType.ink]: {
globalCompositeOperation: "source-over",
strokeStyle: "black",
lineCap: "round",
lineJoin: "round",
lineWidth: 1.5,
},
[StrokeType.erase]: {
globalCompositeOperation: "destination-out",
strokeStyle: "white",
lineCap: "round",
lineJoin: "round",
lineWidth: 8,
},
}
interface State {
strokeType?: StrokeType
eraserPosition?: PenPoint
}
interface CanvasState {}
export default class Ink extends React.Component<Props, State> {
state: State = {}
optionsPanel?: HTMLDivElement
render() {
const { onInkStroke, strokes, mode, scale } = this.props
const { eraserPosition, strokeType } = this.state
const { updateVisibleEraserPosition } = this
return (
<div>
{eraserPosition != undefined ? (
<div
className={css.Eraser}
style={{
left: eraserPosition.x,
top: eraserPosition.y,
width: eraserPosition.strokeWidth,
height: eraserPosition.strokeWidth,
}}
/>
) : null}
<InkCanvas
strokeType={strokeType}
onInkStroke={onInkStroke}
updateVisibleEraserPosition={updateVisibleEraserPosition}
strokes={strokes}
scale={scale}
mode={mode}
/>
{this.props.mode == "fullscreen" ? (
<Portal>
<div className={css.Options} ref={this.onOptionsPanelRef}>
<Option
label="Ink"
value={StrokeType.ink}
selected={strokeType === StrokeType.ink}
onChange={this.onStrokeTypeChange}
/>
<Option
label="Erase"
value={StrokeType.erase}
selected={strokeType === StrokeType.erase}
onChange={this.onStrokeTypeChange}
/>
</div>
</Portal>
) : null}
</div>
)
}
componentDidMount() {
GPS.setInteractionMode(GPS.InteractionMode.default)
}
componentWillUnmount() {
GPS.setInteractionMode(GPS.InteractionMode.default)
}
onOptionsPanelRef = (ref: HTMLDivElement) => {
this.optionsPanel = ref
}
onStrokeTypeChange = (strokeType?: StrokeType) => {
if (this.state.strokeType === strokeType) {
GPS.setInteractionMode(GPS.InteractionMode.default)
this.setState({ eraserPosition: undefined, strokeType: undefined })
} else {
GPS.setInteractionMode(GPS.InteractionMode.inking)
this.setState({ strokeType })
}
}
updateVisibleEraserPosition = (eraserPosition?: PenPoint) => {
this.setState({ eraserPosition })
}
}
class InkCanvas extends React.Component<CanvasProps, CanvasState> {
canvasElement?: HTMLCanvasElement | null
ctx?: CanvasRenderingContext2D | null
pointerEventSubscription?: Rx.Subscription
wetStroke?: InkStroke
lastDrawnPoint = 0
nextDryStroke = 0
state: CanvasState = {}
componentDidMount() {
this.drawDry()
this.pointerEventSubscription = GPS.stream()
.pipe(
RxOps.map(GPS.onlyPen),
RxOps.filter(GPS.ifNotEmpty),
RxOps.map(GPS.toAnyPointer),
RxOps.map(GPS.toMostRecentEvent),
)
.subscribe(this.onPenEvent)
}
componentWillUnmount() {
this.pointerEventSubscription && this.pointerEventSubscription.unsubscribe()
}
componentDidUpdate(prevProps: Props) {
if (prevProps.strokes.length !== this.props.strokes.length) {
requestAnimationFrame(this.drawDry)
}
}
shouldComponentUpdate() {
return false
}
render() {
return <canvas ref={this.canvasAdded} className={css.InkLayer} />
}
onPenEvent = (event: PointerEvent) => {
if (!this.props.strokeType) return
const target = event.target as HTMLElement
// don't record strokes on the options buttons
if (target && target.className && target.className.indexOf("Option") >= 0)
return
if (event.type == "pointerdown") {
this.onPanStart(event)
} else if (event.type == "pointerup" || event.type == "pointercancel") {
this.onPanEnd(event)
} else if (event.type == "pointermove") {
this.onPanMove(event)
}
}
onPanStart = (event: PointerEvent) => {
this.onPanMove(event)
}
onPanMove = (event: PointerEvent) => {
const { x, y } = event
const { strokeType } = this.props
if (!strokeType) return
const coalesced: PointerEvent[] = event.getCoalescedEvents()
if (!this.wetStroke) {
this.wetStroke = {
points: [],
settings: StrokeSettings[strokeType],
}
}
this.wetStroke.points.push(
...coalesced.map((value, i, a) => {
return {
x: value.x,
y: value.y,
strokeWidth: StrokeMappings[strokeType](value.pressure),
}
}),
)
if (strokeType == StrokeType.erase) {
const eraserPosition = {
x: event.x,
y: event.y,
strokeWidth: StrokeMappings[strokeType](event.pressure),
}
this.props.updateVisibleEraserPosition(eraserPosition)
}
this.drawWet()
}
onPanEnd = (event: PointerEvent) => {
this.lastDrawnPoint = 0
if (this.props.strokeType === StrokeType.erase) {
this.props.updateVisibleEraserPosition(undefined)
}
this.inkStroke()
this.resetWetStroke()
}
inkStroke = () => {
if (!this.props.onInkStroke || !this.props.strokeType) {
return
}
this.wetStroke && this.props.onInkStroke(this.wetStroke)
}
resetWetStroke() {
this.wetStroke = undefined
this.lastDrawnPoint = 0
if (this.ctx && this.canvasElement) {
this.ctx.beginPath()
}
}
prepareCanvas(canvas: HTMLCanvasElement) {
// Get the device pixel ratio, falling back to 1.
var dpr = window.devicePixelRatio || 1
const scale = (this.props.scale || 1) * dpr
// Get the size of the canvas in CSS pixels.
if (this.props.mode == "fullscreen") {
canvas.width = window.innerWidth * scale
canvas.height = window.innerHeight * scale
} else {
var rect = canvas.getBoundingClientRect()
canvas.width = rect.width * dpr
canvas.height = rect.height * dpr
}
var ctx = canvas.getContext("2d")
// Scale all drawing operations by the dpr, so you
// don't have to worry about the difference.
if (ctx) {
ctx.translate(0.5, 0.5)
ctx.scale(scale, scale)
}
return ctx
}
canvasAdded = (canvas: HTMLCanvasElement | null) => {
this.canvasElement = canvas
if (canvas) {
this.ctx = this.prepareCanvas(canvas)
}
}
drawWet = Frame.throttle(() => {
if (!this.ctx || !this.wetStroke || !this.props.strokeType) return
for (
this.lastDrawnPoint;
this.lastDrawnPoint < this.wetStroke.points.length;
this.lastDrawnPoint++
) {
let point = this.wetStroke.points[this.lastDrawnPoint]
let settings = StrokeSettings[this.props.strokeType]
settings.lineWidth = point.strokeWidth
Object.assign(this.ctx, settings)
if (this.lastDrawnPoint === 0) {
continue
}
const twoPoints = [this.wetStroke.points[this.lastDrawnPoint - 1], point]
const pathString =
"M " + twoPoints.map(point => `${point.x} ${point.y}`).join(" L ")
const path = new Path2D(pathString)
this.ctx.stroke(path)
}
})
drawDry = Frame.throttle(() => {
if (!this.canvasElement) return
const { strokes } = this.props
this.prepareCanvas(this.canvasElement)
const ctx = this.canvasElement.getContext("2d")
if (!ctx || strokes.length == 0) return
strokes
.slice(this.nextDryStroke)
.forEach(stroke => this.drawDryStroke(stroke))
this.nextDryStroke = strokes.length
})
drawDryStroke(stroke: InkStroke) {
const ctx = this.canvasElement && this.canvasElement.getContext("2d")
if (!ctx || stroke.points.length == 0) return
let strokeSettings = stroke.settings
let from = stroke.points[0]
if (!from) return
let pathString = ""
if (stroke.points.length === 1) {
pathString = `M ${from.x} ${from.y} C`
const path = new Path2D(pathString)
strokeSettings.lineWidth = from.strokeWidth
Object.assign(ctx, stroke)
ctx.stroke(path)
} else {
stroke.points.forEach((to, index) => {
if (!to || !from) return
pathString = `M ${from.x} ${from.y} L ${to.x} ${to.y}`
const path = new Path2D(pathString)
strokeSettings.lineWidth = to.strokeWidth
Object.assign(ctx, strokeSettings)
ctx.stroke(path)
from = to
})
}
}
}
interface OptionProps {
label: React.ReactNode
value: StrokeType
selected: boolean
onChange: (value?: StrokeType) => void
}
class Option<T> extends React.Component<OptionProps> {
render() {
const { value, selected, onChange } = this.props
const baseName =
value == StrokeType.ink ? css.OptionButtonInk : css.OptionButtonEraser
return (
<div
className={css.Option}
onPointerDown={() => onChange(value)}
onContextMenu={this.onContextMenu}>
<div
className={classnames(baseName, {
[css.selected]: selected,
[css.deselected]: !selected,
})}
/>
</div>
)
}
onContextMenu = (event: React.MouseEvent) => {
event.preventDefault()
}
} | the_stack |
import 'reflect-metadata';
import { OBJ_DEF_CLS, ObjectDefinitionOptions, TagClsMetadata, TAGGED_CLS } from '..';
const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
const ARGUMENT_NAMES = /([^\s,]+)/g;
export type decoratorKey = string | symbol;
export const PRELOAD_MODULE_KEY = 'INJECTION_PRELOAD_MODULE_KEY';
export class DecoratorManager extends Map {
/**
* the key for meta data store in class
*/
injectClassKeyPrefix = 'INJECTION_CLASS_META_DATA';
/**
* the key for method meta data store in class
*/
injectClassMethodKeyPrefix = 'INJECTION_CLASS_METHOD_META_DATA';
/**
* the key for method meta data store in method
*/
injectMethodKeyPrefix = 'INJECTION_METHOD_META_DATA';
saveModule(key, module) {
if (!this.has(key)) {
this.set(key, new Set());
}
this.get(key).add(module);
}
static getDecoratorClassKey(decoratorNameKey: decoratorKey) {
return decoratorNameKey.toString() + '_CLS';
}
static getDecoratorMethodKey(decoratorNameKey: decoratorKey) {
return decoratorNameKey.toString() + '_METHOD';
}
static getDecoratorClsMethodPrefix(decoratorNameKey: decoratorKey) {
return decoratorNameKey.toString() + '_CLS_METHOD';
}
static getDecoratorClsMethodKey(decoratorNameKey: decoratorKey, methodKey: decoratorKey) {
return DecoratorManager.getDecoratorClsMethodPrefix(decoratorNameKey) + ':' + methodKey.toString();
}
listModule(key) {
return Array.from(this.get(key) || {});
}
static getOriginMetadata(metaKey, target, method?) {
if (method) {
// for property
if (!Reflect.hasMetadata(metaKey, target, method)) {
Reflect.defineMetadata(metaKey, new Map(), target, method);
}
return Reflect.getMetadata(metaKey, target, method);
} else {
// filter Object.create(null)
if (typeof target === 'object' && target.constructor) {
target = target.constructor;
}
// for class
if (!Reflect.hasMetadata(metaKey, target)) {
Reflect.defineMetadata(metaKey, new Map(), target);
}
return Reflect.getMetadata(metaKey, target);
}
}
/**
* save meta data to class or property
* @param decoratorNameKey the alias name for decorator
* @param data the data you want to store
* @param target target class
* @param propertyName
*/
saveMetadata(decoratorNameKey: decoratorKey, data, target, propertyName?) {
if (propertyName) {
const originMap = DecoratorManager.getOriginMetadata(this.injectMethodKeyPrefix, target, propertyName);
originMap.set(DecoratorManager.getDecoratorMethodKey(decoratorNameKey), data);
} else {
const originMap = DecoratorManager.getOriginMetadata(this.injectClassKeyPrefix, target);
originMap.set(DecoratorManager.getDecoratorClassKey(decoratorNameKey), data);
}
}
/**
* attach data to class or property
* @param decoratorNameKey
* @param data
* @param target
* @param propertyName
*/
attachMetadata(decoratorNameKey: decoratorKey, data, target, propertyName?) {
let originMap;
let key;
if (propertyName) {
originMap = DecoratorManager.getOriginMetadata(this.injectMethodKeyPrefix, target, propertyName);
key = DecoratorManager.getDecoratorMethodKey(decoratorNameKey);
} else {
originMap = DecoratorManager.getOriginMetadata(this.injectClassKeyPrefix, target);
key = DecoratorManager.getDecoratorClassKey(decoratorNameKey);
}
if (!originMap.has(key)) {
originMap.set(key, []);
}
originMap.get(key).push(data);
}
/**
* get single data from class or property
* @param decoratorNameKey
* @param target
* @param propertyName
*/
getMetadata(decoratorNameKey: decoratorKey, target, propertyName?) {
if (propertyName) {
const originMap = DecoratorManager.getOriginMetadata(this.injectMethodKeyPrefix, target, propertyName);
return originMap.get(DecoratorManager.getDecoratorMethodKey(decoratorNameKey));
} else {
const originMap = DecoratorManager.getOriginMetadata(this.injectClassKeyPrefix, target);
return originMap.get(DecoratorManager.getDecoratorClassKey(decoratorNameKey));
}
}
/**
* save property data to class
* @param decoratorNameKey
* @param data
* @param target
* @param propertyName
*/
savePropertyDataToClass(decoratorNameKey: decoratorKey, data, target, propertyName) {
const originMap = DecoratorManager.getOriginMetadata(this.injectClassMethodKeyPrefix, target);
originMap.set(DecoratorManager.getDecoratorClsMethodKey(decoratorNameKey, propertyName), data);
}
/**
* attach property data to class
* @param decoratorNameKey
* @param data
* @param target
* @param propertyName
*/
attachPropertyDataToClass(decoratorNameKey: decoratorKey, data, target, propertyName) {
const originMap = DecoratorManager.getOriginMetadata(this.injectClassMethodKeyPrefix, target);
const key = DecoratorManager.getDecoratorClsMethodKey(decoratorNameKey, propertyName);
if (!originMap.has(key)) {
originMap.set(key, []);
}
originMap.get(key).push(data);
}
/**
* get property data from class
* @param decoratorNameKey
* @param target
* @param propertyName
*/
getPropertyDataFromClass(decoratorNameKey: decoratorKey, target, propertyName) {
const originMap = DecoratorManager.getOriginMetadata(this.injectClassMethodKeyPrefix, target);
return originMap.get(DecoratorManager.getDecoratorClsMethodKey(decoratorNameKey, propertyName));
}
/**
* list property data from class
* @param decoratorNameKey
* @param target
*/
listPropertyDataFromClass(decoratorNameKey: decoratorKey, target) {
const originMap = DecoratorManager.getOriginMetadata(this.injectClassMethodKeyPrefix, target);
const res = [];
for (const [ key, value ] of originMap) {
if (key.indexOf(DecoratorManager.getDecoratorClsMethodPrefix(decoratorNameKey)) !== -1) {
res.push(value);
}
}
return res;
}
}
const manager = new DecoratorManager();
/**
* save data to class
* @param decoratorNameKey
* @param data
* @param target
*/
export function saveClassMetadata(decoratorNameKey: decoratorKey, data, target) {
return manager.saveMetadata(decoratorNameKey, data, target);
}
/**
* attach data to class
* @param decoratorNameKey
* @param data
* @param target
*/
export function attachClassMetadata(decoratorNameKey: decoratorKey, data, target) {
return manager.attachMetadata(decoratorNameKey, data, target);
}
/**
* get data from class
* @param decoratorNameKey
* @param target
*/
export function getClassMetadata(decoratorNameKey: decoratorKey, target) {
return manager.getMetadata(decoratorNameKey, target);
}
/**
* save method data to class
* @deprecated
* @param decoratorNameKey
* @param data
* @param target
* @param method
*/
export function saveMethodDataToClass(decoratorNameKey: decoratorKey, data, target, method) {
return manager.savePropertyDataToClass(decoratorNameKey, data, target, method);
}
/**
* attach method data to class
* @deprecated
* @param decoratorNameKey
* @param data
* @param target
* @param method
*/
export function attachMethodDataToClass(decoratorNameKey: decoratorKey, data, target, method) {
return manager.attachPropertyDataToClass(decoratorNameKey, data, target, method);
}
/**
* get method data from class
* @deprecated
* @param decoratorNameKey
* @param target
* @param method
*/
export function getMethodDataFromClass(decoratorNameKey: decoratorKey, target, method) {
return manager.getPropertyDataFromClass(decoratorNameKey, target, method);
}
/**
* list method data from class
* @deprecated
* @param decoratorNameKey
* @param target
*/
export function listMethodDataFromClass(decoratorNameKey: decoratorKey, target) {
return manager.listPropertyDataFromClass(decoratorNameKey, target);
}
/**
* save method data
* @deprecated
* @param decoratorNameKey
* @param data
* @param target
* @param method
*/
export function saveMethodMetadata(decoratorNameKey: decoratorKey, data, target, method) {
return manager.saveMetadata(decoratorNameKey, data, target, method);
}
/**
* attach method data
* @deprecated
* @param decoratorNameKey
* @param data
* @param target
* @param method
*/
export function attachMethodMetadata(decoratorNameKey: decoratorKey, data, target, method) {
return manager.attachMetadata(decoratorNameKey, data, target, method);
}
/**
* get method data
* @deprecated
* @param decoratorNameKey
* @param target
* @param method
*/
export function getMethodMetadata(decoratorNameKey: decoratorKey, target, method) {
return manager.getMetadata(decoratorNameKey, target, method);
}
/**
* save property data to class
* @param decoratorNameKey
* @param data
* @param target
* @param propertyName
*/
export function savePropertyDataToClass(decoratorNameKey: decoratorKey, data, target, propertyName) {
return manager.savePropertyDataToClass(decoratorNameKey, data, target, propertyName);
}
/**
* attach property data to class
* @param decoratorNameKey
* @param data
* @param target
* @param propertyName
*/
export function attachPropertyDataToClass(decoratorNameKey: decoratorKey, data, target, propertyName) {
return manager.attachPropertyDataToClass(decoratorNameKey, data, target, propertyName);
}
/**
* get property data from class
* @param decoratorNameKey
* @param target
* @param propertyName
*/
export function getPropertyDataFromClass(decoratorNameKey: decoratorKey, target, propertyName) {
return manager.getPropertyDataFromClass(decoratorNameKey, target, propertyName);
}
/**
* list property data from class
* @param decoratorNameKey
* @param target
*/
export function listPropertyDataFromClass(decoratorNameKey: decoratorKey, target) {
return manager.listPropertyDataFromClass(decoratorNameKey, target);
}
/**
* save property data
* @param decoratorNameKey
* @param data
* @param target
* @param propertyName
*/
export function savePropertyMetadata(decoratorNameKey: decoratorKey, data, target, propertyName) {
return manager.saveMetadata(decoratorNameKey, data, target, propertyName);
}
/**
* attach property data
* @param decoratorNameKey
* @param data
* @param target
* @param propertyName
*/
export function attachPropertyMetadata(decoratorNameKey: decoratorKey, data, target, propertyName) {
return manager.attachMetadata(decoratorNameKey, data, target, propertyName);
}
/**
* get property data
* @param decoratorNameKey
* @param target
* @param propertyName
*/
export function getPropertyMetadata(decoratorNameKey: decoratorKey, target, propertyName) {
return manager.getMetadata(decoratorNameKey, target, propertyName);
}
/**
* save preload module by target
* @param target
*/
export function savePreloadModule(target) {
return saveModule(PRELOAD_MODULE_KEY, target);
}
/**
* list preload module
*/
export function listPreloadModule() {
return manager.listModule(PRELOAD_MODULE_KEY);
}
/**
* save module to inner map
* @param decoratorNameKey
* @param target
*/
export function saveModule(decoratorNameKey: decoratorKey, target) {
return manager.saveModule(decoratorNameKey, target);
}
/**
* list module from decorator key
* @param decoratorNameKey
*/
export function listModule(decoratorNameKey: decoratorKey) {
return manager.listModule(decoratorNameKey);
}
/**
* clear all module
*/
export function clearAllModule() {
return manager.clear();
}
/**
* get parameter name from function
* @param func
*/
export function getParamNames(func) {
const fnStr = func.toString().replace(STRIP_COMMENTS, '');
let result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
if (result === null) {
result = [];
}
return result;
}
/**
* get provider id from module
* @param module
*/
export function getProviderId(module) {
const metaData = Reflect.getMetadata(TAGGED_CLS, module) as TagClsMetadata;
if (metaData) {
return metaData.id;
}
}
/**
* get object definition metadata
* @param module
*/
export function getObjectDefinition(module): ObjectDefinitionOptions {
return Reflect.getMetadata(OBJ_DEF_CLS, module) as ObjectDefinitionOptions;
} | the_stack |
import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { AssetGroupObservableService } from '../../../core/services/asset-group-observable.service';
import { AutorefreshService } from '../../services/autorefresh.service';
import { MultilineChartServiceCpu } from '../../services/multilineCpu.service';
import { MultilineChartServiceDisk } from '../../services/multilinedisk.service';
import { MultilineChartServiceNetwork } from '../../services/multilineNetwork.service';
import { DomainTypeObservableService } from '../../../core/services/domain-type-observable.service';
import { UtilsService } from '../../../shared/services/utils.service';
@Component({
selector: 'app-utilization-container',
templateUrl: './utilization-container.component.html',
styleUrls: ['./utilization-container.component.css'],
providers: [ MultilineChartServiceCpu, MultilineChartServiceDisk, MultilineChartServiceNetwork, AutorefreshService]
})
export class UtilizationContainerComponent implements OnInit, OnDestroy {
@ViewChild('widgetCpu') widgetContainer: ElementRef;
@ViewChild('widgetNet') widgetContainerNetwork: ElementRef;
@ViewChild('widgetDisk') widgetContainerDisk: ElementRef;
widgetWidth: number;
widgetHeight: number;
widgetWidthNet: number;
widgetHeightNet: number;
widgetWidthDisk: number;
widgetHeightDisk: number;
selectedAssetGroup: string;
errorMessages;
durationParams: any;
autoRefresh: boolean;
private error = false;
private dataLoaded = false;
private autorefreshInterval;
graphData: any;
networkData: any;
networkDatamassaged: any;
diskData: any;
diskDatamassaged: any;
colorSetCpu: any = [];
colorSetNetwork: any = [];
colorSetDisk: any = [];
countNetwork: any;
countDisk: any;
unitNetwork: any;
unitDisk: any;
errorMessage: any;
showerrorCpu = false;
showerrorNetwork = false;
showerrorDisk = false;
showloaderCpu = false;
showloaderDisk = false;
showloaderNetwork = false;
targetType: any = 'default';
private subscriptionToAssetGroup: Subscription;
private multilineChartCpuSubscription: Subscription;
private multilineChartDiscSubscription: Subscription;
private multilineChartNetworkSubscription: Subscription;
subscriptionDomain: Subscription;
selectedDomain: any;
constructor(
private multilineChartServiceCpu: MultilineChartServiceCpu,
private multilineChartServiceDisk: MultilineChartServiceDisk,
private multilineChartServiceNetwork: MultilineChartServiceNetwork,
private assetGroupObservableService: AssetGroupObservableService,
private autorefreshService: AutorefreshService,
private domainObservableService: DomainTypeObservableService,
private utilService: UtilsService ) {
this.subscriptionToAssetGroup = this.assetGroupObservableService.getAssetGroup().subscribe(
assetGroupName => {
this.selectedAssetGroup = assetGroupName;
});
this.subscriptionDomain = this.domainObservableService.getDomainType().subscribe(domain => {
this.selectedDomain = domain;
this.updateComponent();
});
}
ngOnInit() {
this.durationParams = this.autorefreshService.getDuration();
this.durationParams = parseInt(this.durationParams, 10);
this.autoRefresh = this.autorefreshService.autoRefresh;
this.updateComponent();
const afterLoad = this;
if (this.autoRefresh !== undefined) {
if ((this.autoRefresh === true ) || (this.autoRefresh.toString() === 'true')) {
this.autorefreshInterval = setInterval(function(){
afterLoad.getIssues();
}, this.durationParams);
}
}
}
updateComponent() {
this.graphData = false;
this.networkDatamassaged = false;
this.diskDatamassaged = false;
this.showloaderCpu = false;
this.showloaderNetwork = false;
this.showloaderDisk = false;
this.getIssues();
}
getIssues() {
const queryParams = {
'ag': this.selectedAssetGroup,
'domain': this.selectedDomain
};
if (this.multilineChartDiscSubscription) { this.multilineChartDiscSubscription.unsubscribe(); }
if (this.multilineChartCpuSubscription ) { this.multilineChartCpuSubscription.unsubscribe(); }
if (this.multilineChartNetworkSubscription) { this.multilineChartNetworkSubscription.unsubscribe(); }
this.colorSetCpu = ['#f75c03', '#26ba9d', '#645ec5'];
this.colorSetNetwork = ['#ffb00d', '#645ec5', '#f75c03'];
this.colorSetDisk = ['#3c5079', '#ffb00d', '#645ec5'];
this.multilineChartCpuSubscription = this.multilineChartServiceCpu.getData(queryParams).subscribe(
response => {
try {
this.showloaderCpu = true;
if (!this.utilService.checkIfAPIReturnedDataIsEmpty(response[0].values)) {
this.showerrorCpu = false;
this.graphData = response;
this.widgetWidth = parseInt(window.getComputedStyle(this.widgetContainer.nativeElement, null).getPropertyValue('width'), 10);
this.widgetHeight = parseInt(window.getComputedStyle(this.widgetContainer.nativeElement, null).getPropertyValue('height'), 10);
} else {
this.showerrorCpu = true;
this.errorMessage = 'noDataAvailable';
}
} catch (error) {
this.showerrorCpu = true;
this.showloaderCpu = true;
this.handleError(error);
}
},
error => {
this.showerrorCpu = true;
this.showloaderCpu = true;
this.errorMessage = 'apiResponseError';
}
);
this.multilineChartDiscSubscription = this.multilineChartServiceDisk.getData(queryParams).subscribe(
response => {
try {
this.showloaderDisk = true;
if (!this.utilService.checkIfAPIReturnedDataIsEmpty(response[0][0].values)) {
this.showerrorDisk = false;
this.diskData = response[0];
this.handleUnitDisk(response[0]);
this.widgetWidthDisk = parseInt(window.getComputedStyle(this.widgetContainerDisk.nativeElement, null).getPropertyValue('width'), 10);
this.widgetHeightDisk = parseInt(window.getComputedStyle(this.widgetContainerDisk.nativeElement, null).getPropertyValue('height'), 10);
} else {
this.showerrorDisk = true;
this.errorMessage = 'noDataAvailable';
}
} catch (error) {
this.showerrorDisk = true;
this.showloaderDisk = true;
this.errorMessage = 'apiResponseError';
}
},
error => {
this.showerrorDisk = true;
this.showloaderDisk = true;
this.errorMessage = 'apiResponseError';
}
);
this.multilineChartNetworkSubscription = this.multilineChartServiceNetwork.getData(queryParams).subscribe(
response => {
try {
this.showloaderNetwork = true;
if (!this.utilService.checkIfAPIReturnedDataIsEmpty(response[0][0].values)) {
this.showerrorNetwork = false;
this.networkData = response[0];
this.handleUnit(response[0]);
this.widgetWidthNet = parseInt(window.getComputedStyle(this.widgetContainerNetwork.nativeElement, null).getPropertyValue('width'), 10);
this.widgetHeightNet = parseInt(window.getComputedStyle(this.widgetContainerNetwork.nativeElement, null).getPropertyValue('height'), 10);
} else {
this.showerrorNetwork = true;
this.errorMessage = 'noDataAvailable';
}
} catch (error) {
this.showerrorNetwork = true;
this.showloaderNetwork = true;
this.errorMessage = 'apiResponseError';
}
},
error => {
this.showerrorNetwork = true;
this.showloaderNetwork = true;
this.errorMessage = 'apiResponseError';
}
);
}
handleUnit(data) {
for ( let i = 0 ; i < data.length; i++) {
for ( let j = 0 ; j < data[i].values.length; j++) {
const value = data[i].values[j].value;
const checkValue = this.reduceValue(value);
this.networkData[i].values[j].value = Math.round(checkValue);
}
}
this.networkDatamassaged = this.networkData;
const unit = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
this.unitNetwork = unit[this.countNetwork];
}
handleUnitDisk(data) {
for ( let i = 0; i < data.length; i++) {
for ( let j = 0; j < data[i].values.length; j++) {
const value = data[i].values[j].value;
const checkValue = this.reduceValueDisk(value);
this.diskData[i].values[j].value = Math.round(checkValue);
}
}
this.diskDatamassaged = this.diskData;
const unitDisk = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
this.unitDisk = unitDisk[this.countDisk];
}
reduceValue(data) {
const valueToBeChkd = data;
if (valueToBeChkd === 0) {
return valueToBeChkd;
} else {
const i = (Math.floor(Math.log(valueToBeChkd) / Math.log(1024)));
if (i === 0) { return valueToBeChkd; }
this.countNetwork = i;
return (valueToBeChkd / Math.pow(1024, i)).toFixed(2);
}
}
reduceValueDisk(data) {
const valueToBeChkd = data;
if (valueToBeChkd === 0) {
return valueToBeChkd;
} else {
const i = (Math.floor(Math.log(valueToBeChkd) / Math.log(1024)));
if (i === 0) { return valueToBeChkd; }
this.countDisk = i;
return (valueToBeChkd / Math.pow(1024, i)).toFixed(2);
}
}
handleError(error) {
this.dataLoaded = false;
this.errorMessage = 'apiResponseError';
this.error = true;
}
ngOnDestroy() {
try {
this.subscriptionToAssetGroup.unsubscribe();
this.multilineChartDiscSubscription.unsubscribe();
this.multilineChartCpuSubscription.unsubscribe();
this.multilineChartNetworkSubscription.unsubscribe();
this.subscriptionDomain.unsubscribe();
clearInterval(this.autorefreshInterval);
} catch (error) {
}
}
} | the_stack |
import { inject, injectable, named } from 'inversify';
import { flatten } from 'lodash';
import * as path from 'path';
import * as util from 'util';
import { CancellationToken, TestItem, Uri, TestController, WorkspaceFolder } from 'vscode';
import { IWorkspaceService } from '../../../common/application/types';
import { runAdapter } from '../../../common/process/internal/scripts/testing_tools';
import { IConfigurationService } from '../../../common/types';
import { asyncForEach } from '../../../common/utils/arrayUtils';
import { createDeferred, Deferred } from '../../../common/utils/async';
import { traceError } from '../../../logging';
import { sendTelemetryEvent } from '../../../telemetry';
import { EventName } from '../../../telemetry/constants';
import { PYTEST_PROVIDER } from '../../common/constants';
import { TestDiscoveryOptions } from '../../common/types';
import {
createErrorTestItem,
createWorkspaceRootTestItem,
getNodeByUri,
getWorkspaceNode,
removeItemByIdFromChildren,
updateTestItemFromRawData,
} from '../common/testItemUtilities';
import {
ITestFrameworkController,
ITestDiscoveryHelper,
ITestsRunner,
TestData,
RawDiscoveredTests,
ITestRun,
} from '../common/types';
import { preparePytestArgumentsForDiscovery, pytestGetTestFilesAndFolders } from './arguments';
@injectable()
export class PytestController implements ITestFrameworkController {
private readonly testData: Map<string, RawDiscoveredTests[]> = new Map();
private discovering: Map<string, Deferred<void>> = new Map();
private idToRawData: Map<string, TestData> = new Map();
constructor(
@inject(ITestDiscoveryHelper) private readonly discoveryHelper: ITestDiscoveryHelper,
@inject(ITestsRunner) @named(PYTEST_PROVIDER) private readonly runner: ITestsRunner,
@inject(IConfigurationService) private readonly configService: IConfigurationService,
@inject(IWorkspaceService) private readonly workspaceService: IWorkspaceService,
) {}
public async resolveChildren(
testController: TestController,
item: TestItem,
token?: CancellationToken,
): Promise<void> {
const workspace = this.workspaceService.getWorkspaceFolder(item.uri);
if (workspace) {
// if we are still discovering then wait
const discovery = this.discovering.get(workspace.uri.fsPath);
if (discovery) {
await discovery.promise;
}
// see if we have raw test data
const rawTestData = this.testData.get(workspace.uri.fsPath);
if (rawTestData) {
// Refresh each node with new data
if (rawTestData.length === 0) {
const items: TestItem[] = [];
testController.items.forEach((i) => items.push(i));
items.forEach((i) => testController.items.delete(i.id));
return Promise.resolve();
}
const root = rawTestData.length === 1 ? rawTestData[0].root : workspace.uri.fsPath;
if (root === item.id) {
// This is the workspace root node
if (rawTestData.length === 1) {
if (rawTestData[0].tests.length > 0) {
await updateTestItemFromRawData(
item,
testController,
this.idToRawData,
item.id,
rawTestData,
token,
);
} else {
this.idToRawData.delete(item.id);
testController.items.delete(item.id);
return Promise.resolve();
}
} else {
// To figure out which top level nodes have to removed. First we get all the
// existing nodes. Then if they have data we keep those nodes, Nodes without
// data will be removed after we check the raw data.
let subRootWithNoData: string[] = [];
item.children.forEach((c) => subRootWithNoData.push(c.id));
await asyncForEach(rawTestData, async (data) => {
let subRootId = data.root;
let rawId;
if (data.root === root) {
const subRoot = data.parents.filter((p) => p.parentid === '.' || p.parentid === root);
subRootId = path.join(data.root, subRoot.length > 0 ? subRoot[0].id : '');
rawId = subRoot.length > 0 ? subRoot[0].id : undefined;
}
if (data.tests.length > 0) {
let subRootItem = item.children.get(subRootId);
if (!subRootItem) {
subRootItem = createWorkspaceRootTestItem(testController, this.idToRawData, {
id: subRootId,
label: path.basename(subRootId),
uri: Uri.file(subRootId),
runId: subRootId,
parentId: item.id,
rawId,
});
item.children.add(subRootItem);
}
// We found data for a node. Remove its id from the no-data list.
subRootWithNoData = subRootWithNoData.filter((s) => s !== subRootId);
await updateTestItemFromRawData(
subRootItem,
testController,
this.idToRawData,
root, // All the file paths are based on workspace root.
[data],
token,
);
} else {
// This means there are no tests under this node
removeItemByIdFromChildren(this.idToRawData, item, [subRootId]);
}
});
// We did not find any data for these nodes, delete them.
removeItemByIdFromChildren(this.idToRawData, item, subRootWithNoData);
}
} else {
const workspaceNode = getWorkspaceNode(item, this.idToRawData);
if (workspaceNode) {
await updateTestItemFromRawData(
item,
testController,
this.idToRawData,
workspaceNode.id,
rawTestData,
token,
);
}
}
} else {
const workspaceNode = getWorkspaceNode(item, this.idToRawData);
if (workspaceNode) {
testController.items.delete(workspaceNode.id);
}
}
}
return Promise.resolve();
}
public async refreshTestData(testController: TestController, uri: Uri, token?: CancellationToken): Promise<void> {
sendTelemetryEvent(EventName.UNITTEST_DISCOVERING, undefined, { tool: 'pytest' });
const workspace = this.workspaceService.getWorkspaceFolder(uri);
if (workspace) {
// Discovery is expensive. So if it is already running then use the promise
// from the last run
const previous = this.discovering.get(workspace.uri.fsPath);
if (previous) {
return previous.promise;
}
const settings = this.configService.getSettings(workspace.uri);
const options: TestDiscoveryOptions = {
workspaceFolder: workspace.uri,
cwd:
settings.testing.cwd && settings.testing.cwd.length > 0
? settings.testing.cwd
: workspace.uri.fsPath,
args: settings.testing.pytestArgs,
ignoreCache: true,
token,
};
// Get individual test files and directories selected by the user.
const testFilesAndDirectories = pytestGetTestFilesAndFolders(options.args);
// Set arguments to use with pytest discovery script.
const args = runAdapter(['discover', 'pytest', '--', ...preparePytestArgumentsForDiscovery(options)]);
// Build options for each directory selected by the user.
let discoveryRunOptions: TestDiscoveryOptions[];
if (testFilesAndDirectories.length === 0) {
// User did not provide any directory. So we don't need to tweak arguments.
discoveryRunOptions = [
{
...options,
args,
},
];
} else {
discoveryRunOptions = testFilesAndDirectories.map((testDir) => ({
...options,
args: [...args, testDir],
}));
}
const deferred = createDeferred<void>();
this.discovering.set(workspace.uri.fsPath, deferred);
let rawTestData: RawDiscoveredTests[] = [];
try {
// This is where we execute pytest discovery via a common helper.
rawTestData = flatten(
await Promise.all(discoveryRunOptions.map((o) => this.discoveryHelper.runTestDiscovery(o))),
);
this.testData.set(workspace.uri.fsPath, rawTestData);
// Remove error node
testController.items.delete(`DiscoveryError:${workspace.uri.fsPath}`);
deferred.resolve();
} catch (ex) {
sendTelemetryEvent(EventName.UNITTEST_DISCOVERY_DONE, undefined, { tool: 'pytest', failed: true });
const cancel = options.token?.isCancellationRequested ? 'Cancelled' : 'Error';
traceError(`${cancel} discovering pytest tests:\r\n`, ex);
const message = getTestDiscoveryExceptions((ex as Error).message);
// Report also on the test view. Getting root node is more complicated due to fact
// that in pytest project can be organized in many ways
testController.items.add(
createErrorTestItem(testController, {
id: `DiscoveryError:${workspace.uri.fsPath}`,
label: `Pytest Discovery Error [${path.basename(workspace.uri.fsPath)}]`,
error: util.format(
`${cancel} discovering pytest tests (see Output > Python):\r\n`,
message.length > 0 ? message : ex,
),
}),
);
deferred.reject(ex as Error);
} finally {
// Discovery has finished running we have the raw test data at this point.
this.discovering.delete(workspace.uri.fsPath);
}
const root = rawTestData.length === 1 ? rawTestData[0].root : workspace.uri.fsPath;
const workspaceNode = testController.items.get(root);
if (workspaceNode) {
if (uri.fsPath === workspace.uri.fsPath) {
// this is a workspace level refresh
// This is an existing workspace test node. Just update the children
await this.resolveChildren(testController, workspaceNode, token);
} else {
// This is a child node refresh
const testNode = getNodeByUri(workspaceNode, uri);
if (testNode) {
// We found the node to update
await this.resolveChildren(testController, testNode, token);
} else {
// update the entire workspace tree
await this.resolveChildren(testController, workspaceNode, token);
}
}
} else if (rawTestData.length > 0) {
// This is a new workspace with tests.
const newItem = createWorkspaceRootTestItem(testController, this.idToRawData, {
id: root,
label: path.basename(root),
uri: Uri.file(root),
runId: root,
});
testController.items.add(newItem);
await this.resolveChildren(testController, newItem, token);
}
}
sendTelemetryEvent(EventName.UNITTEST_DISCOVERY_DONE, undefined, { tool: 'pytest', failed: false });
return Promise.resolve();
}
public runTests(testRun: ITestRun, workspace: WorkspaceFolder, token: CancellationToken): Promise<void> {
const settings = this.configService.getSettings(workspace.uri);
return this.runner.runTests(
testRun,
{
workspaceFolder: workspace.uri,
cwd:
settings.testing.cwd && settings.testing.cwd.length > 0
? settings.testing.cwd
: workspace.uri.fsPath,
token,
args: settings.testing.pytestArgs,
},
this.idToRawData,
);
}
}
function getTestDiscoveryExceptions(content: string): string {
const lines = content.split(/\r?\n/g);
let start = false;
let exceptions = '';
for (const line of lines) {
if (start) {
exceptions += `${line}\r\n`;
} else if (line.includes(' ERRORS ')) {
start = true;
}
}
return exceptions;
} | the_stack |
import { ComponentFixture, fakeAsync, flush, TestBed, tick } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AccountService } from 'app/core/auth/account.service';
import * as chai from 'chai';
import sinonChai from 'sinon-chai';
import { ArtemisTestModule } from '../../test.module';
import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';
import { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service';
import { MockComponent, MockPipe } from 'ng-mocks';
import { AlertService } from 'app/core/util/alert.service';
import { Router } from '@angular/router';
import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';
import { MockAccountService } from '../../helpers/mocks/service/mock-account.service';
import { LocalStorageService, SessionStorageService } from 'ngx-webstorage';
import { ComplaintService } from 'app/complaints/complaint.service';
import { MockComplaintService } from '../../helpers/mocks/service/mock-complaint.service';
import { NgxDatatableModule } from '@swimlane/ngx-datatable';
import { routes } from 'app/exercises/file-upload/participate/file-upload-participation.route';
import { FileUploadSubmissionComponent } from 'app/exercises/file-upload/participate/file-upload-submission.component';
import { createFileUploadSubmission, MockFileUploadSubmissionService } from '../../helpers/mocks/service/mock-file-upload-submission.service';
import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';
import { fileUploadExercise } from '../../helpers/mocks/service/mock-file-upload-exercise.service';
import { MAX_SUBMISSION_FILE_SIZE } from 'app/shared/constants/input.constants';
import { TranslateModule } from '@ngx-translate/core';
import * as sinon from 'sinon';
import { stub } from 'sinon';
import { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module';
import dayjs from 'dayjs';
import { of } from 'rxjs';
import { ArtemisSharedModule } from 'app/shared/shared.module';
import { FileUploaderService } from 'app/shared/http/file-uploader.service';
import { StudentParticipation } from 'app/entities/participation/student-participation.model';
import { Result } from 'app/entities/result.model';
import { FileUploadSubmissionService } from 'app/exercises/file-upload/participate/file-upload-submission.service';
import { ComplaintsForTutorComponent } from 'app/complaints/complaints-for-tutor/complaints-for-tutor.component';
import { ArtemisResultModule } from 'app/exercises/shared/result/result.module';
import { ArtemisComplaintsModule } from 'app/complaints/complaints.module';
import { ArtemisHeaderExercisePageWithDetailsModule } from 'app/exercises/shared/exercise-headers/exercise-headers.module';
import { RatingModule } from 'app/exercises/shared/rating/rating.module';
import { HtmlForMarkdownPipe } from 'app/shared/pipes/html-for-markdown.pipe';
import { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';
import { ArtemisTimeAgoPipe } from 'app/shared/pipes/artemis-time-ago.pipe';
chai.use(sinonChai);
const expect = chai.expect;
describe('FileUploadSubmissionComponent', () => {
let comp: FileUploadSubmissionComponent;
let fixture: ComponentFixture<FileUploadSubmissionComponent>;
let debugElement: DebugElement;
let router: Router;
let fileUploaderService: FileUploaderService;
let alertService: AlertService;
let fileUploadSubmissionService: FileUploadSubmissionService;
const result = { id: 1 } as Result;
beforeEach(async () => {
return TestBed.configureTestingModule({
imports: [
ArtemisTestModule,
NgxDatatableModule,
ArtemisResultModule,
ArtemisSharedModule,
ArtemisComplaintsModule,
TranslateModule.forRoot(),
RouterTestingModule.withRoutes([routes[0]]),
ArtemisSharedComponentModule,
ArtemisHeaderExercisePageWithDetailsModule,
RatingModule,
],
declarations: [
FileUploadSubmissionComponent,
MockComponent(ComplaintsForTutorComponent),
MockPipe(HtmlForMarkdownPipe),
MockPipe(ArtemisDatePipe),
MockPipe(ArtemisTimeAgoPipe),
],
providers: [
{ provide: AccountService, useClass: MockAccountService },
{ provide: SessionStorageService, useClass: MockSyncStorage },
{ provide: LocalStorageService, useClass: MockSyncStorage },
{ provide: ComplaintService, useClass: MockComplaintService },
{ provide: FileUploadSubmissionService, useClass: MockFileUploadSubmissionService },
{ provide: ParticipationWebsocketService, useClass: MockParticipationWebsocketService },
],
})
.overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(FileUploadSubmissionComponent);
comp = fixture.componentInstance;
debugElement = fixture.debugElement;
router = debugElement.injector.get(Router);
fixture.ngZone!.run(() => {
router.initialNavigation();
});
fileUploaderService = TestBed.inject(FileUploaderService);
alertService = TestBed.inject(AlertService);
fileUploadSubmissionService = debugElement.injector.get(FileUploadSubmissionService);
});
});
afterEach(fakeAsync(() => {
tick();
fixture.destroy();
flush();
}));
it('File Upload Submission is correctly initialized from service', fakeAsync(() => {
fixture.detectChanges();
tick();
// check if properties where assigned correctly on init
expect(comp.acceptedFileExtensions.replace(/\./g, '')).to.be.equal(fileUploadExercise.filePattern);
expect(comp.fileUploadExercise).to.be.equal(fileUploadExercise);
expect(comp.isAfterAssessmentDueDate).to.be.true;
// check if fileUploadInput is available
const fileUploadInput = debugElement.query(By.css('#fileUploadInput'));
expect(fileUploadInput).to.exist;
expect(fileUploadInput.nativeElement.disabled).to.be.false;
// check if extension elements are set
const extension = debugElement.query(By.css('.ms-1.badge.bg-info'));
expect(extension).to.exist;
expect(extension.nativeElement.textContent.replace(/\s/g, '')).to.be.equal(fileUploadExercise.filePattern!.split(',')[0].toUpperCase());
}));
it('Submission and file uploaded', fakeAsync(() => {
// Ignore window confirm
window.confirm = () => {
return false;
};
const fileName = 'exampleSubmission';
comp.submissionFile = new File([''], fileName, { type: 'application/pdf' });
comp.submission = createFileUploadSubmission();
fixture.detectChanges();
let submitFileButton = debugElement.query(By.css('jhi-button'));
jest.spyOn(fileUploaderService, 'uploadFile').mockReturnValue(Promise.resolve({ path: 'test' }));
submitFileButton.nativeElement.click();
comp.submission!.submitted = true;
comp.result = new Result();
fixture.detectChanges();
// check if fileUploadInput is available
const fileUploadInput = debugElement.query(By.css('#fileUploadInput'));
expect(fileUploadInput).to.not.exist;
submitFileButton = debugElement.query(By.css('.btn.btn-success'));
expect(submitFileButton).to.be.null;
}));
it('Too big file can not be submitted', fakeAsync(() => {
// Ignore console errors
console.error = jest.fn();
fixture.detectChanges();
tick();
const submissionFile = new File([''], 'exampleSubmission.png');
Object.defineProperty(submissionFile, 'size', { value: MAX_SUBMISSION_FILE_SIZE + 1, writable: false });
comp.submission = createFileUploadSubmission();
const jhiErrorSpy = sinon.spy(alertService, 'error');
const event = { target: { files: [submissionFile] } };
comp.setFileSubmissionForExercise(event);
fixture.detectChanges();
// check that properties are set properly
expect(jhiErrorSpy.callCount).to.be.equal(1);
expect(comp.submissionFile).to.be.undefined;
expect(comp.submission!.filePath).to.be.undefined;
// check if fileUploadInput is available
const fileUploadInput = debugElement.query(By.css('#fileUploadInput'));
expect(fileUploadInput).to.exist;
expect(fileUploadInput.nativeElement.disabled).to.be.false;
expect(fileUploadInput.nativeElement.value).to.be.equal('');
}));
it('Incorrect file type can not be submitted', fakeAsync(() => {
// Ignore console errors
console.error = jest.fn();
fixture.detectChanges();
tick();
// Only png and pdf types are allowed
const submissionFile = new File([''], 'exampleSubmission.jpg');
comp.submission = createFileUploadSubmission();
const jhiErrorSpy = sinon.spy(alertService, 'error');
const event = { target: { files: [submissionFile] } };
comp.setFileSubmissionForExercise(event);
fixture.detectChanges();
// check that properties are set properly
expect(jhiErrorSpy.callCount).to.be.equal(1);
expect(comp.submissionFile).to.be.undefined;
expect(comp.submission!.filePath).to.be.undefined;
// check if fileUploadInput is available
const fileUploadInput = debugElement.query(By.css('#fileUploadInput'));
expect(fileUploadInput).to.exist;
expect(fileUploadInput.nativeElement.disabled).to.be.false;
expect(fileUploadInput.nativeElement.value).to.be.equal('');
tick();
fixture.destroy();
flush();
}));
it('should not allow to submit after the deadline if the initialization date is before the due date', fakeAsync(() => {
const submission = createFileUploadSubmission();
submission.participation!.initializationDate = dayjs().subtract(2, 'days');
(<StudentParticipation>submission.participation).exercise!.dueDate = dayjs().subtract(1, 'days');
stub(fileUploadSubmissionService, 'getDataForFileUploadEditor').returns(of(submission));
comp.submissionFile = new File([''], 'exampleSubmission.png');
fixture.detectChanges();
tick();
const submitButton = debugElement.query(By.css('jhi-button'));
expect(submitButton).to.exist;
expect(submitButton.attributes['ng-reflect-disabled']).to.be.equal('true');
tick();
fixture.destroy();
flush();
}));
it('should allow to submit after the deadline if the initialization date is after the due date', fakeAsync(() => {
const submission = createFileUploadSubmission();
submission.participation!.initializationDate = dayjs().add(1, 'days');
(<StudentParticipation>submission.participation).exercise!.dueDate = dayjs();
stub(fileUploadSubmissionService, 'getDataForFileUploadEditor').returns(of(submission));
comp.submissionFile = new File([''], 'exampleSubmission.png');
fixture.detectChanges();
tick();
expect(comp.isLate).to.be.true;
const submitButton = debugElement.query(By.css('jhi-button'));
expect(submitButton).to.exist;
expect(submitButton.attributes['ng-reflect-disabled']).to.be.equal('false');
tick();
fixture.destroy();
flush();
}));
it('should not allow to submit if there is a result and no due date', fakeAsync(() => {
stub(fileUploadSubmissionService, 'getDataForFileUploadEditor').returns(of(createFileUploadSubmission()));
comp.submissionFile = new File([''], 'exampleSubmission.png');
fixture.detectChanges();
tick();
comp.result = result;
fixture.detectChanges();
const submitButton = debugElement.query(By.css('jhi-button'));
expect(submitButton).to.exist;
expect(submitButton.attributes['ng-reflect-disabled']).to.be.equal('true');
tick();
fixture.destroy();
flush();
}));
it('should get inactive as soon as the due date passes the current date', fakeAsync(() => {
const submission = createFileUploadSubmission();
(<StudentParticipation>submission.participation).exercise!.dueDate = dayjs().add(1, 'days');
stub(fileUploadSubmissionService, 'getDataForFileUploadEditor').returns(of(submission));
comp.submissionFile = new File([''], 'exampleSubmission.png');
fixture.detectChanges();
tick();
comp.participation.initializationDate = dayjs();
expect(comp.isActive).to.be.true;
comp.fileUploadExercise.dueDate = dayjs().subtract(1, 'days');
fixture.detectChanges();
tick();
expect(comp.isActive).to.be.false;
tick();
fixture.destroy();
flush();
}));
}); | the_stack |
import * as React from 'react';
import {
InstantSearch,
Index,
createConnector,
SearchResults,
connectStateResults,
SearchBoxProvided,
connectSearchBox,
connectRefinementList,
CurrentRefinementsProvided,
connectCurrentRefinements,
RefinementListProvided,
Refinement,
connectHighlight,
connectHits,
HighlightProvided,
HighlightProps,
AutocompleteProvided,
connectAutoComplete,
Hit,
TranslatableProvided,
translatable,
ConnectorProvided,
StateResultsProvided,
ConnectorSearchResults,
BasicDoc,
AllSearchResults,
connectStats,
StatsProvided,
connectHitInsights,
InsightsClient,
ConnectHitInsightsProvided,
} from 'react-instantsearch-core';
import { Hits } from 'react-instantsearch-dom';
() => {
<Index indexName={'test'} indexId="id">
<div></div>
</Index>;
};
// https://community.algolia.com/react-instantsearch/guide/Custom_connectors.html
() => {
const CoolWidget = createConnector({
displayName: 'CoolWidget',
getProvidedProps(props, searchState) {
// Since the `queryAndPage` searchState entry isn't necessarily defined, we need
// to default its value.
const [query, page] = searchState.queryAndPage || ['', 0];
// Connect the underlying component to the `queryAndPage` searchState entry.
return {
query,
page,
refine: (value: string) => this.refine(value),
};
},
refine(props, searchState, newQuery, newPage) {
// When the underlying component calls its `refine` prop, update the searchState
// with the new query and page.
return {
// `searchState` represents the search state of *all* widgets. We need to extend it
// instead of replacing it, otherwise other widgets will lose their
// respective state.
...searchState,
queryAndPage: [newQuery, newPage],
};
},
})(props => (
<div>
The query is {props.query}, the page is {props.page}. This is an error:{' '}
{
props.somethingElse // $ExpectError
}
{/*
Clicking on this button will update the searchState to:
{
...otherSearchState,
query: 'algolia',
page: 20,
}
*/}
<button onClick={() => props.refine('algolia', 20)} />
{/*
Clicking on this button will update the searchState to:
{
...otherSearchState,
query: 'instantsearch',
page: 15,
}
*/}
<button onClick={() => props.refine('instantsearch', 15)} />
</div>
));
<CoolWidget>
<div></div>
</CoolWidget>;
};
() => {
interface Provided {
query: string;
page: number;
}
interface Exposed {
defaultRefinement: string;
startAtPage: number;
}
const typedCoolConnector = createConnector<Provided, Exposed>({
displayName: 'CoolWidget',
getProvidedProps(props, searchState) {
// Since the `queryAndPage` searchState entry isn't necessarily defined, we need
// to default its value.
const [query, page] = searchState.queryAndPage || [props.defaultRefinement, props.startAtPage];
// Connect the underlying component to the `queryAndPage` searchState entry.
return {
query,
page,
};
},
refine(props, searchState, newQuery, newPage) {
// When the underlying component calls its `refine` prop, update the searchState
// with the new query and page.
return {
// `searchState` represents the search state of *all* widgets. We need to extend it
// instead of replacing it, otherwise other widgets will lose their
// respective state.
...searchState,
queryAndPage: [newQuery, newPage],
};
},
});
const TypedCoolWidgetStateless = typedCoolConnector(props => (
<div>
The query is {props.query}, the page is {props.page}. This is an error:{' '}
{
props.somethingElse // $ExpectError
}
{/*
Clicking on this button will update the searchState to:
{
...otherSearchState,
query: 'algolia',
page: 20,
}
*/}
<button onClick={() => props.refine('algolia', 20)} />
{/*
Clicking on this button will update the searchState to:
{
...otherSearchState,
query: 'instantsearch',
page: 15,
}
*/}
<button onClick={() => props.refine('instantsearch', 15)} />
</div>
));
<TypedCoolWidgetStateless defaultRefinement={'asdf'} startAtPage={10} />;
const TypedCoolWidget = typedCoolConnector(
class extends React.Component<ConnectorProvided<Provided> & { passThruName: string }> {
render() {
const props = this.props;
return (
<div>
The query is {props.query}, the page is {props.page}. The name is {props.passThruName}
{/*
Clicking on this button will update the searchState to:
{
...otherSearchState,
query: 'algolia',
page: 20,
}
*/}
<button onClick={() => props.refine('algolia', 20)} />
{/*
Clicking on this button will update the searchState to:
{
...otherSearchState,
query: 'instantsearch',
page: 15,
}
*/}
<button onClick={() => props.refine('instantsearch', 15)} />
</div>
);
}
}
);
<TypedCoolWidget defaultRefinement={'asdf'} startAtPage={10} passThruName={'test'} />;
};
() => {
interface MyDoc {
field1: string;
field2: number;
field3: { compound: string };
}
interface StateResultsProps {
searchResults: SearchResults<MyDoc>;
// partial of StateResultsProvided
additionalProp: string;
}
const Stateless = connectStateResults((
{ searchResults, additionalProp } // $ExpectError
) => (
<div>
<h1>{additionalProp}</h1>
{searchResults.hits.map(h => {
return <span>{h._highlightResult.field1!.value}</span>;
})}
</div>
));
<Stateless />;
<Stateless additionalProp="test" />; // $ExpectError
const StatelessWithType = ({ additionalProp, searchResults }: StateResultsProps) => (
<div>
<h1>{additionalProp}</h1>
{searchResults.hits.map(h => {
// $ExpectType string
const compound = h._highlightResult.field3!.compound!.value;
return <span>{compound}</span>;
})}
</div>
);
const ComposedStatelessWithType = connectStateResults(StatelessWithType);
<ComposedStatelessWithType />; // $ExpectError
<ComposedStatelessWithType additionalProp="test" />;
class MyComponent extends React.Component<StateResultsProps> {
render() {
const { additionalProp, searchResults } = this.props;
return (
<div>
<h1>{additionalProp}</h1>
{searchResults.hits.map(h => {
// $ExpectType string[]
const words = h._highlightResult.field3!.compound!.matchedWords;
return (
<span>
{h.field2}: {words.join(',')}
</span>
);
})}
</div>
);
}
}
const ComposedMyComponent = connectStateResults(MyComponent);
<ComposedMyComponent />; // $ExpectError
<ComposedMyComponent additionalProp="test" />;
};
() => {
<InstantSearch searchClient={{}} indexName="xxx" />;
<InstantSearch indexName="xxx" />; // $ExpectError
};
// https://community.algolia.com/react-instantsearch/guide/Connectors.html
() => {
const MySearchBox = ({ currentRefinement, refine }: SearchBoxProvided) => (
<input type="text" value={currentRefinement} onChange={e => refine(e.target.value)} />
);
// `ConnectedSearchBox` renders a `<MySearchBox>` widget that is connected to
// the <InstantSearch> state, providing it with `currentRefinement` and `refine` props for
// reading and manipulating the current query of the search.
const ConnectedSearchBox = connectSearchBox(MySearchBox);
};
() => {
const MyCurrentRefinements = ({ refine, items, query }: CurrentRefinementsProvided) => (
<>
{items.map(refinement => (
<div key={refinement.id} onClick={() => refine(refinement.value)}>
<label>{refinement.label}</label>
</div>
))}
</>
);
const ConnectedCurrentRefinements = connectCurrentRefinements(MyCurrentRefinements);
<ConnectedCurrentRefinements clearsQuery={true} transformItems={item => item} />;
};
() => {
const MyClearRefinements = ({ refine, items }: CurrentRefinementsProvided) => (
<button onClick={() => refine(items)}>
clear all
</button>
);
const ConnectedClearRefinements = connectCurrentRefinements(MyClearRefinements);
<ConnectedClearRefinements clearsQuery={true} transformItems={item => item} />;
};
() => {
function renderRefinement(label: string, value: Refinement['value'], refine: CurrentRefinementsProvided['refine']) {
return (
<button className="badge badge-secondary" onClick={() => refine(value)}>
{label}
</button>
);
}
const MyCurrentRefinements = connectCurrentRefinements(({ refine, items, query }: CurrentRefinementsProvided) => {
return (
<>
{items.map(refinement => {
/*
* When existing several refinements for the same atribute name, then you get a
* nested items object that contains a label and a value function to use to remove a single filter.
* https://community.algolia.com/react-instantsearch/connectors/connectCurrentRefinements.html
*/
if (refinement.items) {
return <>{refinement.items.map(i => renderRefinement(i.label, i.value, refine))}</>;
}
// extra assert for typescript < 3.2
if (typeof refinement.currentRefinement === 'string') {
return renderRefinement(refinement.currentRefinement, refinement.value, refine);
}
})}
</>
);
});
};
() => {
const MyRefinementList = ({ items, refine }: RefinementListProvided) => (
<>
{items.map(item => (
<button onClick={() => refine(item.value)}>{item.label}</button>
))}
</>
);
const ConnectedRefinementList = connectRefinementList(MyRefinementList);
<ConnectedRefinementList
attribute={'test'}
searchable={true}
operator={'and'}
showMore={true}
limit={8}
showMoreLimit={99}
/>;
};
() => {
interface MyDoc {
a: 1;
b: {
c: '2';
};
}
const CustomHighlight = connectHighlight<MyDoc>(({ highlight, attribute, hit }) => {
const highlights = highlight({
highlightProperty: '_highlightResult',
attribute,
hit,
});
return <>{highlights.map(part => (part.isHighlighted ? <mark>{part.value}</mark> : <span>{part.value}</span>))}</>;
});
class CustomHighlight2 extends React.Component<HighlightProps & { limit: number }> {
render() {
const { highlight, attribute, hit, limit } = this.props;
const highlights = highlight({
highlightProperty: '_highlightResult',
attribute,
hit,
});
return (
<>
{highlights
.slice(0, limit)
.map(part => (part.isHighlighted ? <mark>{part.value}</mark> : <span>{part.value}</span>))}
</>
);
}
}
const ConnectedCustomHighlight2 = connectHighlight(CustomHighlight2);
const ConnectedStatelessHits = connectHits<MyDoc>(({ hits }) => (
<p>
<CustomHighlight attribute="name" hit={hits[0]} />
<ConnectedCustomHighlight2 attribute="name" hit={hits[1]} limit={7} />
</p>
));
<ConnectedStatelessHits />;
};
// https://github.com/algolia/react-instantsearch/blob/master/examples/autocomplete/src/App-Mentions.js
() => {
const Mention: any = null; // import Mention from 'antd/lib/mention';
const AsyncMention = ({ hits, refine }: AutocompleteProvided) => (
<Mention
style={{ width: 500, height: 100 }}
prefix="@"
notFoundContent={'No suggestion'}
placeholder="give someone an @-mention here"
suggestions={hits.map(hit => hit.name)}
onSearchChange={refine}
/>
);
const ConnectedAsyncMention = connectAutoComplete(AsyncMention);
<ConnectedAsyncMention />;
};
() => {
type Props = SearchBoxProvided &
TranslatableProvided & {
className?: string | undefined;
showLoadingIndicator?: boolean | undefined;
submit?: JSX.Element | undefined;
reset?: JSX.Element | undefined;
loadingIndicator?: JSX.Element | undefined;
onSubmit?: ((event: React.SyntheticEvent<HTMLFormElement>) => any) | undefined;
onReset?: ((event: React.SyntheticEvent<HTMLFormElement>) => any) | undefined;
onChange?: ((event: React.SyntheticEvent<HTMLInputElement>) => any) | undefined;
};
interface State {
query: string | null;
}
class SearchBox extends React.Component<Props, State> {
static defaultProps = {
currentRefinement: '',
className: 'ais-SearchBox',
focusShortcuts: ['s', '/'],
autoFocus: false,
searchAsYouType: true,
showLoadingIndicator: false,
isSearchStalled: false,
reset: <i className="material-icons">clear</i>,
submit: <i className="material-icons">search</i>,
};
constructor(props: SearchBox['props']) {
super(props);
this.state = {
query: null,
};
}
getQuery = () => this.props.currentRefinement;
onSubmit = (e: React.SyntheticEvent<any>) => {
e.preventDefault();
e.stopPropagation();
const { refine, onSubmit } = this.props;
if (onSubmit) {
onSubmit(e);
}
return false;
}
onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { onChange } = this.props;
const value = event.target.value;
this.setState({ query: value });
if (onChange) {
onChange(event);
}
}
onReset = (event: React.FormEvent<HTMLFormElement>) => {
const { refine, onReset } = this.props;
refine('');
this.setState({ query: '' });
if (onReset) {
onReset(event);
}
}
render() {
const { className, translate, loadingIndicator, submit, reset } = this.props;
const query = this.getQuery();
const isSearchStalled = this.props.showLoadingIndicator && this.props.isSearchStalled;
const isCurrentQuerySubmitted = query && query === this.props.currentRefinement;
const button = isSearchStalled ? 'loading' : isCurrentQuerySubmitted ? 'reset' : 'submit';
return (
<div className={className}>
<form
noValidate
onSubmit={this.onSubmit}
onReset={this.onReset}
className={`${className}-${isSearchStalled ? 'form--stalledSearch' : 'form'}`}
action=""
role="search"
>
<button
type="submit"
title={translate('submitTitle')}
className={`${className}-submit`}
hidden={button !== 'submit'}
>
{submit}
</button>
<button
type="reset"
title={translate('resetTitle')}
className={`${className}-reset`}
hidden={button !== 'reset'}
>
{reset}
</button>
<span className={`${className}-loadingIndicator`} hidden={button !== 'loading'}>
{loadingIndicator}
</span>
<input
{...{
onChange: this.onChange,
value: query,
type: 'search',
placeholder: translate('placeholder'),
autoComplete: 'off',
autoCorrect: 'off',
autoCapitalize: 'off',
spellCheck: false,
required: true,
maxLength: 512,
className: `${className}-input`,
}}
/>
</form>
</div>
);
}
}
const TranslatableSearchBox = translatable({
resetTitle: 'Clear the search query.',
submitTitle: 'Submit your search query.',
placeholder: 'Search here…',
})(SearchBox);
const ConnectedSearchBox = connectSearchBox(TranslatableSearchBox);
<ConnectedSearchBox
className="ais-search"
loadingIndicator={<i className="material-icons">search</i>}
onSubmit={evt => {
console.log('submitted', evt);
}}
/>;
};
// can we recreate connectStateResults from source using the createConnector typedef?
() => {
function getIndexId(context: any): string {
return context && context.multiIndexContext
? context.multiIndexContext.targetedIndex
: context.ais.mainTargetedIndex;
}
function getResults<TDoc>(
searchResults: { results: AllSearchResults<TDoc> },
context: any
): SearchResults<TDoc> | null | undefined {
const { results } = searchResults;
if (results && !results.hits) {
return results[getIndexId(context)] ? results[getIndexId(context)] : null;
} else {
return results ? results : null;
}
}
const csr = createConnector({
displayName: 'AlgoliaStateResults',
getProvidedProps(props, searchState, searchResults) {
const results = getResults(searchResults, this.context);
return {
searchState,
searchResults: results,
allSearchResults: searchResults.results,
searching: searchResults.searching,
isSearchStalled: searchResults.isSearchStalled,
error: searchResults.error,
searchingForFacetValues: searchResults.searchingForFacetValues,
props,
};
},
});
const asConnectStateResults: typeof connectStateResults = csr;
};
() => {
const TotalHits = ({ nbHits }: StatsProvided) => {
return <span>Your search returned {nbHits} results.</span>;
};
const ConnectedTotalHits = connectStats(TotalHits);
<ConnectedTotalHits />;
};
() => {
const HitComponent = ({ hit, insights }: ConnectHitInsightsProvided) => (
<button
onClick={() => {
insights('clickedObjectIDsAfterSearch', { eventName: 'hit clicked' });
}}
>
<article>
<h1>{hit.name}</h1>
</article>
</button>
);
const HitWithInsights = connectHitInsights(() => {})(HitComponent);
<Hits hitComponent={HitWithInsights} />;
}; | the_stack |
import { DebugElement, Type } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { JsonFormsControl } from '@jsonforms/angular';
import {
baseSetup,
ErrorTestExpectation,
setupMockStore,
TestConfig,
TestData,
getJsonFormsService
} from './util';
import { ControlElement, JsonSchema, Actions } from '@jsonforms/core';
interface ComponentResult<C extends JsonFormsControl> {
fixture: ComponentFixture<any>;
component: C;
rangeElement: DebugElement;
}
const prepareComponent = <C extends JsonFormsControl, I>(
testConfig: TestConfig<C>,
instance: Type<I>
): ComponentResult<C> => {
const fixture = TestBed.createComponent(testConfig.componentUT);
const component = fixture.componentInstance;
const rangeElement = fixture.debugElement.query(By.directive(instance));
const result: ComponentResult<C> = { fixture, component, rangeElement };
return result;
};
export const rangeDefaultData = { foo: 1.234 };
export const rangeDefaultSchema: JsonSchema = {
type: 'object',
properties: {
foo: {
type: 'number',
minimum: -42.42,
maximum: 42.42,
default: 0.42
}
}
};
export const rangeDefaultUischema: ControlElement = {
type: 'Control',
scope: '#/properties/foo',
options: { slider: true }
};
export const rangeDefaultTestData: TestData<ControlElement> = {
data: rangeDefaultData,
schema: rangeDefaultSchema,
uischema: rangeDefaultUischema
};
export const rangeBaseTest = <C extends JsonFormsControl, I>(
testConfig: TestConfig<C>,
instance: Type<I>
) => () => {
let fixture: ComponentFixture<any>;
let rangeElement: DebugElement;
let component: C;
baseSetup(testConfig);
beforeEach(() => {
const preparedComponents = prepareComponent(testConfig, instance);
fixture = preparedComponents.fixture;
rangeElement = preparedComponents.rangeElement;
component = preparedComponents.component;
});
it('should render floats', () => {
component.uischema = rangeDefaultTestData.uischema;
component.schema = rangeDefaultTestData.schema;
getJsonFormsService(component).init(
{core: {data: rangeDefaultTestData.data, schema: rangeDefaultTestData.schema, uischema: rangeDefaultTestData.uischema}}
);
component.ngOnInit();
fixture.detectChanges();
expect(component.data).toBe(1.234);
expect(rangeElement.componentInstance.value).toBe(1.234);
// step is of type string
expect(rangeElement.componentInstance.step).toBe(1);
expect(rangeElement.componentInstance.min).toBe(-42.42);
expect(rangeElement.componentInstance.max).toBe(42.42);
expect(rangeElement.componentInstance.disabled).toBe(false);
expect(fixture.nativeElement.children[0].style.display).not.toBe('none');
});
it('should render integer', () => {
component.uischema = rangeDefaultTestData.uischema;
const schema = JSON.parse(JSON.stringify(rangeDefaultTestData.schema));
schema.properties.foo.type = 'integer';
schema.properties.foo.minimum = -42;
schema.properties.foo.maximum = 42;
schema.properties.foo.default = 1;
setupMockStore(fixture, {
uischema: rangeDefaultTestData.uischema,
schema,
data: { foo: 12 }
});
getJsonFormsService(component).updateCore(
Actions.init({ foo: 12 }, schema, rangeDefaultTestData.uischema)
);
fixture.componentInstance.ngOnInit();
fixture.detectChanges();
expect(component.data).toBe(12);
expect(rangeElement.componentInstance.value).toBe(12);
// step is of type string
expect(rangeElement.componentInstance.step).toBe(1);
expect(rangeElement.componentInstance.min).toBe(-42);
expect(rangeElement.componentInstance.max).toBe(42);
expect(rangeElement.componentInstance.disabled).toBe(false);
// the component is wrapped in a div
expect(fixture.nativeElement.children[0].style.display).not.toBe('none');
});
it('should support updating the state', () => {
component.uischema = rangeDefaultTestData.uischema;
component.schema = rangeDefaultTestData.schema;
getJsonFormsService(component).init(
{core: {data: rangeDefaultTestData.data, schema: rangeDefaultTestData.schema, uischema: rangeDefaultTestData.uischema}}
);
component.ngOnInit();
fixture.detectChanges();
getJsonFormsService(component).updateCore(
Actions.update('foo', () => 4.56)
);
fixture.detectChanges();
expect(component.data).toBe(4.56);
expect(rangeElement.componentInstance.value).toBe(4.56);
});
it('should update with undefined value', () => {
component.uischema = rangeDefaultTestData.uischema;
component.schema = rangeDefaultTestData.schema;
getJsonFormsService(component).init(
{core: {data: rangeDefaultTestData.data, schema: rangeDefaultTestData.schema, uischema: rangeDefaultTestData.uischema}}
);
component.ngOnInit();
fixture.detectChanges();
getJsonFormsService(component).updateCore(
Actions.update('foo', () => undefined)
);
fixture.detectChanges();
expect(component.data).toBe(undefined);
expect(rangeElement.componentInstance.value).toBe(0.42);
});
it('should update with null value', () => {
component.uischema = rangeDefaultTestData.uischema;
component.schema = rangeDefaultTestData.schema;
getJsonFormsService(component).init(
{core: {data: rangeDefaultTestData.data, schema: rangeDefaultTestData.schema, uischema: rangeDefaultTestData.uischema}}
);
component.ngOnInit();
fixture.detectChanges();
getJsonFormsService(component).updateCore(
Actions.update('foo', () => null)
);
fixture.detectChanges();
expect(component.data).toBe(null);
expect(rangeElement.componentInstance.value).toBe(0.42);
});
it('should not update with wrong ref', () => {
component.uischema = rangeDefaultTestData.uischema;
component.schema = rangeDefaultTestData.schema;
getJsonFormsService(component).init(
{core: {data: rangeDefaultTestData.data, schema: rangeDefaultTestData.schema, uischema: rangeDefaultTestData.uischema}}
);
component.ngOnInit();
fixture.detectChanges();
getJsonFormsService(component).updateCore(
Actions.update('foo', () => 1.234)
);
getJsonFormsService(component).updateCore(
Actions.update('bar', () => 456.456)
);
fixture.detectChanges();
expect(component.data).toBe(1.234);
expect(rangeElement.componentInstance.value).toBe(1.234);
});
// store needed as we evaluate the calculated enabled value to disable/enable the control
it('can be disabled', () => {
component.uischema = rangeDefaultTestData.uischema;
component.schema = rangeDefaultTestData.schema;
component.disabled = true;
getJsonFormsService(component).init(
{core: {data: rangeDefaultTestData.data, schema: rangeDefaultTestData.schema, uischema: rangeDefaultTestData.uischema}}
);
component.ngOnInit();
fixture.detectChanges();
expect(rangeElement.componentInstance.disabled).toBe(true);
});
it('can be hidden', () => {
component.uischema = rangeDefaultTestData.uischema;
component.schema = rangeDefaultTestData.schema;
component.visible = false;
getJsonFormsService(component).init(
{core: {data: rangeDefaultTestData.data, schema: rangeDefaultTestData.schema, uischema: rangeDefaultTestData.uischema}}
);
fixture.detectChanges();
component.ngOnInit();
expect(fixture.nativeElement.children[0].style.display).toBe('none');
});
it('id should be present in output', () => {
component.uischema = rangeDefaultTestData.uischema;
component.schema = rangeDefaultTestData.schema;
component.id = 'myId';
getJsonFormsService(component).init(
{core: {data: rangeDefaultTestData.data, schema: rangeDefaultTestData.schema, uischema: rangeDefaultTestData.uischema}}
);
component.ngOnInit();
fixture.detectChanges();
expect(rangeElement.nativeElement.id).toBe('myId');
});
};
export const rangeInputEventTest = <C extends JsonFormsControl, I>(
testConfig: TestConfig<C>,
instance: Type<I>
) => () => {
let fixture: ComponentFixture<any>;
let component: C;
baseSetup(testConfig);
beforeEach(() => {
const preparedComponents = prepareComponent(testConfig, instance);
fixture = preparedComponents.fixture;
component = preparedComponents.component;
});
xit('should update via input event', async () => {
component.uischema = rangeDefaultTestData.uischema;
component.schema = rangeDefaultTestData.schema;
getJsonFormsService(component).init(
{core: {data: rangeDefaultTestData.data, schema: rangeDefaultTestData.schema, uischema: rangeDefaultTestData.uischema}}
);
component.ngOnInit();
fixture.detectChanges();
const spy = spyOn(component, 'onChange');
const sliderElement = fixture.debugElement.query(By.css('.mat-slider'))
.nativeElement;
const trackElement = fixture.debugElement.query(
By.css('.mat-slider-wrapper')
).nativeElement;
const dimensions = trackElement.getBoundingClientRect();
const x = dimensions.left + dimensions.width * 0.2;
const y = dimensions.top + dimensions.height * 0.2;
dispatchEvent(sliderElement, createMouseEvent('mousedown', x, y, 0));
// trigger change detection
fixture.detectChanges();
await fixture.whenStable();
expect(spy).toHaveBeenCalled();
});
};
export const rangeErrorTest = <C extends JsonFormsControl, I>(
testConfig: TestConfig<C>,
instance: Type<I>,
errorTestInformation: ErrorTestExpectation
) => () => {
let fixture: ComponentFixture<any>;
let component: C;
baseSetup(testConfig);
beforeEach(() => {
const preparedComponents = prepareComponent(testConfig, instance);
fixture = preparedComponents.fixture;
component = preparedComponents.component;
});
it('should display errors', () => {
component.uischema = rangeDefaultTestData.uischema;
component.schema = rangeDefaultTestData.schema;
const formsService = getJsonFormsService(component);
formsService.init({
core: {
data: rangeDefaultTestData.data,
schema: rangeDefaultTestData.schema,
uischema: undefined
}
});
formsService.updateCore(Actions.updateErrors([
{
instancePath: '/foo',
message: 'Hi, this is me, test error!',
keyword: '',
schemaPath: '',
params: {}
}
]));
formsService.refresh();
component.ngOnInit();
fixture.detectChanges();
const debugErrors: DebugElement[] = fixture.debugElement.queryAll(
By.directive(errorTestInformation.errorInstance)
);
expect(debugErrors.length).toBe(errorTestInformation.numberOfElements);
expect(
debugErrors[errorTestInformation.indexOfElement].nativeElement.textContent
).toBe('Hi, this is me, test error!');
});
};
/** Creates a browser MouseEvent with the specified options. */
const createMouseEvent = (type: string, x = 0, y = 0, button = 0) => {
const event = document.createEvent('MouseEvent');
event.initMouseEvent(
type,
true /* canBubble */,
false /* cancelable */,
window /* view */,
0 /* detail */,
x /* screenX */,
y /* screenY */,
x /* clientX */,
y /* clientY */,
false /* ctrlKey */,
false /* altKey */,
false /* shiftKey */,
false /* metaKey */,
button /* button */,
null /* relatedTarget */
);
// `initMouseEvent` doesn't allow us to pass the `buttons` and
// defaults it to 0 which looks like a fake event.
Object.defineProperty(event, 'buttons', { get: () => 1 });
return event;
};
/** Utility to dispatch any event on a Node. */
const dispatchEvent = (node: Node | Window, event: Event): Event => {
node.dispatchEvent(event);
return event;
}; | the_stack |
import Color from 'color'
import convert from 'color-convert'
import produce, {Draft, immerable} from 'immer'
import {
arrayMove,
clampedLinearMap,
getOrCreate,
longestIncreasingSubsequence,
optionalClamp,
random,
removeValue,
} from '../util/util'
import {
ConstantQuotaRule,
DayID,
DEFAULT_QUOTA_RULE_APPLIER_BY_TYPE,
DEFAULT_REPEATER_BY_TYPE,
deserializeQuotaRuleFromObject,
draftToQuotaRule,
isConstantQuotaRule,
Item,
ItemDraft,
ItemID,
ItemStatus,
QuotaRule,
QuotaRuleDraft,
QuotaRuleID,
quotaRuleToDraft,
RepeatType,
serializeQuotaRuleToObject,
SessionType,
} from './common'
import {Injectable} from '@angular/core'
import {BehaviorSubject} from 'rxjs'
import {dayIDNow} from '../util/time-util'
import {Task} from './data-analyzer'
import {MetadataStore} from './metadata-store'
import {
deserializeMapFromObject,
deserializeNumberFromObject,
deserializeNumberFromString,
parseSerializedObject,
quickDeserializeRequired,
serializeArrayToObject,
SerializedObject,
SerializedObjectMap,
serializeMapToObject,
serializePrimitiveToObject,
serializePrimitiveToString,
stringifySerializedObject,
} from '../util/serialization'
import {FsUtil} from '../util/fs-util'
import {debounceTime} from 'rxjs/operators'
export const DATA_FILE_NAME = 'vir-data.json'
export const TEMP_DATA_FILE_NAME_1 = 'vir-data.tmp1.json'
export const TEMP_DATA_FILE_NAME_2 = 'vir-data.tmp2.json'
export const AUTO_SAVE_IDLE_DELAY = 5000 // 5 seconds after change
export const AUTO_SAVE_INTERVAL = 60000 // Every minute
export interface InvalidItemError {
type: string
message: string
}
export interface InvalidQuotaRuleError {
type: string
message: string
}
export interface InvalidSessionError {
type: string
message: string
}
export enum SessionModificationType {
SET,
ADD,
}
function applySessionModification(existingCount: number,
modification: SessionModificationType,
count: number): number {
let result = 0
if (modification === SessionModificationType.SET) {
result = count
} else if (modification === SessionModificationType.ADD) {
result = existingCount + count
} else {
result = existingCount
}
return Math.max(0, result)
}
/**
* NOTE: Array is used instead of object for performance reasons.
* "Less than" means earlier in queue (i.e. higher priority)
*/
export type QueuePriorityProxy = [
dueDate: DayID | undefined,
special: number, // This is used to force unnatural ordering
postOrderIndex: number,
]
export function getQueuePriorityProxy(effectiveDueDate: DayID | undefined,
postOrderIndex: number): QueuePriorityProxy {
return [effectiveDueDate, 0, postOrderIndex]
}
export function queuePriorityProxyCompare(a: QueuePriorityProxy,
b: QueuePriorityProxy) {
if (a[0] !== b[0]) {
if (b[0] === undefined) return -1
if (a[0] === undefined) return 1
return a[0] - b[0]
}
if (a[1] !== b[1]) {
return a[1] - b[1]
}
return a[2] - b[2]
}
/**
* @deprecated Legacy
*/
export interface QueueItemInfo {
itemID: ItemID
postOrderIndex: number
effectiveDueDate?: DayID
}
/**
* @deprecated Legacy
*/
export function getSmartQueueInsertionIndex(queueInfo: QueueItemInfo[],
queueItemInfo: QueueItemInfo) {
// TODO improve this heuristic
let queueSize = queueInfo.length
let start = 0
let end = queueSize // exclusive
const selfDueDate = queueItemInfo.effectiveDueDate
if (selfDueDate === undefined) {
// Search for the last item with deadline
// for (let i = queueSize - 1; i >= 0; --i) {
// if (this.getItem(queue[i])!.dueDate !== undefined) {
// start = i + 1
// break
// }
// }
} else {
let foundLowerBound = false
let foundUpperBound = false
start = 0
end = 0
for (let i = 0; i < queueSize; ++i) {
const dueDate = queueInfo[i].effectiveDueDate
if (dueDate === undefined) continue
if (dueDate < selfDueDate) {
start = i + 1
end = start
} else if (!foundLowerBound) { // dueDate === selfDueDate
start = i
end = start
foundLowerBound = true
}
}
for (let i = queueSize - 1; i > start; --i) {
const dueDate = queueInfo[i].effectiveDueDate
if (dueDate === undefined) continue
if (dueDate > selfDueDate) {
end = i
} else if (!foundUpperBound) { // dueDate === selfDueDate
end = i + 1
foundUpperBound = true
}
}
}
if (start >= end) {
return start
} else {
const selfScore = queueItemInfo.postOrderIndex
// TODO draft.items.get(parentID)!.childrenIDs.indexOf(itemID)
let candidate: number | undefined = undefined
let candidateScore: number | undefined = undefined
for (let i = start; i < end; ++i) {
const score = queueInfo[i].postOrderIndex
if (score < selfScore) {
if (candidateScore === undefined || candidateScore < score) {
candidate = i
candidateScore = score
}
}
}
if (candidate === undefined) {
return start
} else {
return candidate + 1
}
}
}
export interface SubtreeRepetitionInfo {
itemID: ItemID
/**
* The number of days to place defer date before root due date
*/
startOffset?: number
/**
* The number of days to place self due date before root due date
*/
endOffset?: number
}
export interface SubtreeRepetitionResult {
itemID: ItemID
deferDate?: DayID
dueDate?: DayID
}
export function generateSubtreeRepetition(
nextTask: Task, rootItemID: ItemID, subtreeInfo: SubtreeRepetitionInfo[],
) {
const result: SubtreeRepetitionResult[] = []
const count = subtreeInfo.length
for (let i = 0; i < count; i++) {
const info = subtreeInfo[i]
if (info === undefined) continue
if (nextTask.end === undefined) { // Probably won't happen
result.push({itemID: info.itemID})
continue
}
if (info.itemID === rootItemID) { // This is the subtree root
// Only the startOffset is used
result.push({
itemID: info.itemID,
deferDate: info.startOffset === undefined ? nextTask.start :
optionalClamp(
nextTask.end - info.startOffset, nextTask.start, nextTask.end),
dueDate: nextTask.end,
})
} else {
// Simply shift defer and due date accordingly
result.push({
itemID: info.itemID,
deferDate: info.startOffset === undefined ? undefined :
nextTask.end - info.startOffset,
dueDate: info.endOffset === undefined ? undefined :
nextTask.end - info.endOffset,
})
// if (nextTask.start !== undefined) {
// if (info.deferDate !== undefined) {
// info.deferDate =
// Math.max(info.deferDate, nextTask.start)
// } else {
// info.deferDate = nextTask.start
// }
// if (info.dueDate !== undefined) {
// info.dueDate = Math.max(info.dueDate,
// nextTask.start) } else { info.dueDate = nextTask.start } }
}
}
return result
}
export class DayMap<T> {
[immerable] = true
private partitions = new Map<number, Map<DayID, T>>()
private static readonly PARTITION_SIZE = 30
constructor() {
}
private static toPartitionID(dayID: DayID) {
return Math.floor(dayID / DayMap.PARTITION_SIZE)
}
private static toDayID(partitionID: number) {
return partitionID * DayMap.PARTITION_SIZE
}
private getPartition(dayID: DayID) {
return this.partitions.get(DayMap.toPartitionID(dayID))
}
public getEarliestDayID() {
let earliestPartitionID: number | undefined = undefined
this.partitions.forEach((_, partitionID) => {
if (earliestPartitionID === undefined || partitionID <
earliestPartitionID) {
earliestPartitionID = partitionID
}
})
if (earliestPartitionID === undefined) return undefined
let earliestDayID: number | undefined = undefined
this.partitions.get(earliestPartitionID)!.forEach((_, dayID) => {
if (earliestDayID === undefined || dayID < earliestDayID) {
earliestDayID = dayID
}
})
if (earliestDayID === undefined) return DayMap.toDayID(earliestPartitionID)
return earliestDayID
}
public tryGet(dayID: DayID) {
const partition = this.getPartition(dayID)
if (partition === undefined) {
return undefined
}
return partition.get(dayID)
}
public static set<T>(draft: Draft<DayMap<T>>, dayID: DayID,
value: T) {
const partitionID = DayMap.toPartitionID(dayID)
// @ts-ignore
let partition: Map<DayID, T> | undefined = draft.partitions.get(
partitionID)
if (partition === undefined) {
partition = new Map<DayID, T>()
// @ts-ignore
draft.partitions.set(partitionID, partition)
}
partition.set(dayID, value)
}
public static tryGet<T>(draft: Draft<DayMap<T>>, dayID: DayID) {
const partitionID = DayMap.toPartitionID(dayID)
// @ts-ignore
let partition: Map<DayID, T> | undefined = draft.partitions.get(
partitionID)
if (partition === undefined) {
return undefined
}
return partition.get(dayID)
}
public static getOrCreate<T>(draft: Draft<DayMap<T>>, dayID: DayID,
creator: () => T) {
const partitionID = DayMap.toPartitionID(dayID)
// @ts-ignore
let partition: Map<DayID, T> | undefined = draft.partitions.get(
partitionID)
if (partition === undefined) {
partition = new Map<DayID, T>()
// @ts-ignore
draft.partitions.set(partitionID, partition)
}
let result = partition.get(dayID)
if (result === undefined) {
result = creator()
partition.set(dayID, result)
}
return result
}
public static remove<T>(draft: Draft<DayMap<T>>, dayID: DayID) {
const partitionID = DayMap.toPartitionID(dayID)
// @ts-ignore
let partition: Map<DayID, T> | undefined = draft.partitions.get(
partitionID)
if (partition === undefined) {
return
}
partition.delete(dayID)
if (partition.size === 0) {
// @ts-ignore
draft.partitions.delete(partitionID)
}
}
forEach(func: (item: T, dayID: DayID) => void) {
this.partitions.forEach(partition => {
partition.forEach(func)
})
}
static serializeToObject<T>(dayMap: DayMap<T>,
valueToObject: (value: T) => SerializedObject): SerializedObject {
return {
partitions:
serializeMapToObject(
dayMap.partitions, serializePrimitiveToString,
(value) =>
serializeMapToObject(
value, serializePrimitiveToString, valueToObject),
),
}
}
static deserializeFromObject<T>(obj: SerializedObject,
valueFromObject: (obj: SerializedObject) => T): DayMap<T> {
const map = obj as SerializedObjectMap
const result = new DayMap<T>()
result.partitions = deserializeMapFromObject(
map.partitions as SerializedObject, deserializeNumberFromString,
(value) =>
deserializeMapFromObject(
value, deserializeNumberFromString, valueFromObject),
)
return result
}
}
export class DayData {
[immerable] = true
sessions = new Map<SessionType, Map<ItemID, number>>()
static deserializeFromObject(obj: SerializedObject): DayData {
const map = obj as SerializedObjectMap
const result = new DayData()
result.sessions = deserializeMapFromObject(
map.sessions as SerializedObject, deserializeNumberFromString,
(value) =>
deserializeMapFromObject(
value, deserializeNumberFromString, deserializeNumberFromObject),
)
return result
}
static serializeToObject(value: DayData): SerializedObject {
return {
sessions:
serializeMapToObject(
value.sessions, serializePrimitiveToString,
(value) =>
serializeMapToObject(
value, serializePrimitiveToString, serializePrimitiveToObject),
),
}
}
}
export interface DataStoreState {
items: Map<ItemID, Item>
queue: ItemID[]
rootItemIDs: ItemID[]
timelineData: DayMap<DayData>
nextItemID: number
nextQuotaRuleID: number
quotaRules: Map<QuotaRuleID, QuotaRule>
quotaRuleOrder: QuotaRuleID[]
settings: {
startOfDayMinutes: number
quotaRuleAutoDeleteDays: number
}
}
function serializeDataStoreStateToObject(state: DataStoreState): SerializedObject {
return {
items: serializeMapToObject(state.items, serializePrimitiveToString,
Item.serializeToObject,
),
queue: serializeArrayToObject(state.queue, serializePrimitiveToObject),
rootItemIDs:
serializeArrayToObject(state.rootItemIDs, serializePrimitiveToObject),
timelineData:
DayMap.serializeToObject(state.timelineData, DayData.serializeToObject),
nextItemID: serializePrimitiveToObject(state.nextItemID),
nextQuotaRuleID: serializePrimitiveToObject(state.nextQuotaRuleID),
quotaRules:
serializeMapToObject(state.quotaRules, serializePrimitiveToString,
serializeQuotaRuleToObject,
),
quotaRuleOrder:
serializeArrayToObject(state.quotaRuleOrder, serializePrimitiveToObject),
settings: {
startOfDayMinutes: serializePrimitiveToObject(
state.settings.startOfDayMinutes),
quotaRuleAutoDeleteDays: serializePrimitiveToObject(
state.settings.quotaRuleAutoDeleteDays),
},
}
}
function deserializeDataStoreStateFromObject(obj: SerializedObject): DataStoreState {
const map = obj as SerializedObjectMap
const settings = map.settings as SerializedObjectMap
return {
items: map.items === undefined ? new Map<ItemID, Item>() :
deserializeMapFromObject(map.items, deserializeNumberFromString,
Item.deserializeFromObject,
),
queue: quickDeserializeRequired(map.queue),
rootItemIDs: quickDeserializeRequired(map.rootItemIDs),
timelineData: DayMap.deserializeFromObject(
map.timelineData as SerializedObject, DayData.deserializeFromObject),
nextItemID: quickDeserializeRequired(map.nextItemID),
nextQuotaRuleID: quickDeserializeRequired(map.nextQuotaRuleID),
quotaRules: map.quotaRules === undefined ?
new Map<QuotaRuleID, QuotaRule>() :
deserializeMapFromObject(map.quotaRules, deserializeNumberFromString,
deserializeQuotaRuleFromObject,
),
quotaRuleOrder: quickDeserializeRequired(map.quotaRuleOrder),
settings: {
startOfDayMinutes: quickDeserializeRequired(settings.startOfDayMinutes),
quotaRuleAutoDeleteDays: quickDeserializeRequired(
settings.quotaRuleAutoDeleteDays),
},
}
}
export interface DataStoreAutoCompleterData {
key: string
id: ItemID
}
export interface DataStoreAutoCompleterResult {
key: string
id: ItemID
score: number
}
/**
* If numCandidates is 0, then no limit will be imposed on the result.
*/
export class DataStoreAutoCompleter {
private data: DataStoreAutoCompleterData[] = []
private _keyToID = new Map<string, ItemID>()
private _idToKey = new Map<ItemID, string>()
constructor(dataStore: DataStore, filter?: (item: Item) => boolean) {
// TODO: optimize: use DFS to reduce the amount of parent-tracing
const keyCount = new Map<string, number>()
dataStore.state.items.forEach((item) => {
if (!filter || filter(item)) {
const key = DataStoreAutoCompleter.getKey(dataStore, item)
this.data.push({
key: key,
id: item.id,
})
if (keyCount.has(key)) {
keyCount.set(key, keyCount.get(key)! + 1)
} else {
keyCount.set(key, 1)
}
}
})
const numItems = this.data.length
for (let i = 0; i < numItems; i++) {
const entry = this.data[i]
if (keyCount.get(entry.key)! > 1) {
entry.key += ` (#${entry.id})`
}
this._keyToID.set(entry.key, entry.id)
this._idToKey.set(entry.id, entry.key)
}
}
private static getKey(dataStore: DataStore, item: Item) {
if (item.status === ItemStatus.COMPLETED) {
return '[DONE] ' + dataStore.getQualifiedName(item)
}
return dataStore.getQualifiedName(item)
}
query(pattern: string,
numCandidates: number = 0): DataStoreAutoCompleterResult[] {
let result: DataStoreAutoCompleterResult[] = []
pattern = pattern.toLowerCase()
const numEntries = this.data.length
for (let i = 0; i < numEntries; ++i) {
const data = this.data[i]
const key = data.key.toLowerCase()
const patternLen = pattern.length
const keyLen = key.length
let forwardScore = 0
let a = 0
let b = 0
let lastMatchedB = -1
while (a < patternLen && b < keyLen) {
if (pattern.charAt(a) === key.charAt(b)) {
++a
if (lastMatchedB === -1) {
forwardScore += 2.0
} else {
forwardScore += 1.0 + (1.0 / (b - lastMatchedB))
}
lastMatchedB = b
}
++b
}
if (a !== patternLen) continue // No match
let backwardScore = 0
a = patternLen - 1
b = keyLen - 1
lastMatchedB = -1
while (a >= 0 && b >= 0) {
if (pattern.charAt(a) === key.charAt(b)) {
--a
if (lastMatchedB === -1) {
backwardScore += 2.0
} else {
backwardScore += 1.0 + (1.0 / (lastMatchedB - b))
}
lastMatchedB = b
}
--b
}
const lengthScore = patternLen / keyLen
const score = Math.max(forwardScore, backwardScore) + lengthScore
result.push({
key: data.key, id: data.id, score,
})
}
result.sort((a, b) => {
if (a.score != b.score) {
return b.score - a.score
}
return a.key.localeCompare(b.key)
})
if (numCandidates > 0) {
result = result.slice(0, numCandidates)
}
return result
}
queryKeys(pattern: string, numCandidates: number = 0) {
return this.query(pattern, numCandidates).map(entry => entry.key)
}
queryIDs(pattern: string, numCandidates: number = 0) {
return this.query(pattern, numCandidates).map(entry => entry.id)
}
keyToID(key: string) {
return this._keyToID.get(key)
}
idToKey(itemID: ItemID) {
return this._idToKey.get(itemID)
}
}
function insertWithOptions(array: ItemID[], entry: ItemID,
options: UpdateItemOptions) {
let anchorIndex = -1
if (options.anchor !== undefined) {
anchorIndex = array.indexOf(options.anchor)
}
if (anchorIndex >= 0) {
const insert = options.insert || 'above'
if (insert === 'below') {
anchorIndex++
}
array.splice(anchorIndex, 0, entry)
} else {
array.push(entry)
}
}
export interface UpdateItemOptions {
anchor?: ItemID
insert?: 'above' | 'below'
}
function lexicographicLessThan(a: number[], b: number[]) {
let count = Math.min(a.length, b.length)
for (let i = 0; i < count; ++i) {
if (a[i] < b[i]) return true
if (a[i] > b[i]) return false
}
return a.length <= b.length
}
export interface EffectiveItemInfo {
deferDate?: DayID
dueDate?: DayID
repeat?: RepeatType
repeatEndDate?: DayID
repeatInterval: number
repeatOnCompletion: boolean
hasAncestorRepeat: boolean
hasActiveAncestorRepeat: boolean
}
@Injectable()
export class DataStore {
private _state: DataStoreState = {
items: new Map<ItemID, Item>(),
queue: [],
nextItemID: 1,
nextQuotaRuleID: 1,
rootItemIDs: [],
timelineData: new DayMap<DayData>(),
quotaRules: new Map<QuotaRuleID, QuotaRule>(),
quotaRuleOrder: [],
settings: {
startOfDayMinutes: 0,
quotaRuleAutoDeleteDays: 7,
},
}
private undoHistory: DataStoreState[] = []
private redoHistory: DataStoreState[] = []
private defaultColor = Color('#888888')
static readonly defaultDayData = new DayData()
private onChangeSubject = new BehaviorSubject<DataStore>(this)
private onReloadSubject = new BehaviorSubject<DataStore>(this)
onChange = this.onChangeSubject.asObservable()
onReload = this.onReloadSubject.asObservable()
private addItemReducer = (draft: Draft<DataStoreState>,
itemDraft: ItemDraft) => {
const id = draft.nextItemID
const item = itemDraft.toNewItem(id)
draft.nextItemID++
if (draft.nextItemID <= id) {
throw new Error('Item ID overflow')
}
if (draft.items.has(item.id)) {
throw new Error(`Item with ID ${item.id} already exists`)
}
draft.items.set(item.id, item)
if (item.parentID === undefined) {
draft.rootItemIDs.push(item.id)
} else {
const parent = draft.items.get(item.parentID)
if (parent === undefined) {
throw new Error(`Parent ID ${item.parentID} does not exist`)
}
parent.childrenIDs.push(item.id)
}
return id
}
private updateItemReducer = (draft: Draft<DataStoreState>,
itemDraft: ItemDraft,
options: UpdateItemOptions) => {
const itemID = itemDraft.id
const item = draft.items.get(itemID)
if (item === undefined) {
throw new Error(`Item with ID ${itemID} does not exist`)
}
const oldParentID = item.parentID
const newParentID = itemDraft.parentID
const oldStatus = item.status
const newStatus = itemDraft.status
itemDraft.applyToItem(item)
// Apply status change to children
if (oldStatus !== newStatus) {
this.setDraftSubtreeStatus(draft, item, newStatus)
}
// Change parent
if (newParentID !== oldParentID || options.anchor !== undefined) {
// Remove from old
if (oldParentID === undefined) {
removeValue(draft.rootItemIDs, itemID)
} else {
const parent = draft.items.get(oldParentID)
if (parent === undefined) {
throw new Error(`Parent ID ${oldParentID} does not exist`)
}
removeValue(parent.childrenIDs, itemID)
}
// Add to new
if (newParentID === undefined) {
insertWithOptions(draft.rootItemIDs, item.id, options)
} else {
const parent = draft.items.get(newParentID)
if (parent === undefined) {
throw new Error(`Parent ID ${newParentID} does not exist`)
}
insertWithOptions(parent.childrenIDs, item.id, options)
}
}
}
private removeItemReducer = (draft: Draft<DataStoreState>,
itemID: ItemID) => {
const item = draft.items.get(itemID)
if (item === undefined) {
throw new Error(`Item with ID ${itemID} does not exist`)
}
this._removeAllChildrenOf(draft, item)
if (item.parentID === undefined) {
removeValue(draft.rootItemIDs, itemID)
} else {
const parent = draft.items.get(item.parentID)
if (parent === undefined) {
throw new Error(`Parent ID ${item.parentID} does not exist`)
}
removeValue(parent.childrenIDs, itemID)
}
draft.items.delete(itemID)
this.invalidateItemID(draft, itemID)
}
private editSessionReducer = (draft: Draft<DataStoreState>, dayID: DayID,
type: SessionType, itemID: ItemID,
modification: SessionModificationType,
count: number) => {
// TODO optimize: remove day data that is equal to default/empty
const dayData = DayMap.getOrCreate(
draft.timelineData, dayID, () => new DayData())
const sessionsOfType = getOrCreate(
dayData.sessions, type,
() => new Map<ItemID, number>(),
)
const existingCount = getOrCreate(sessionsOfType, itemID, () => 0)
const newCount = applySessionModification(
existingCount, modification, count)
if (newCount === 0) {
sessionsOfType.delete(itemID)
} else {
sessionsOfType.set(itemID, newCount)
}
}
private queueMoveReducer = (draft: Draft<DataStoreState>, itemID: ItemID,
index: number) => {
const oldIndex = draft.queue.indexOf(itemID)
if (oldIndex < 0) return
arrayMove(draft.queue, oldIndex, index)
}
/**
* NOTE: This root item must be self-repeatable.
* Returns whether the repeat is successful (or simply marked as done)
*/
private repeatSubtreeReducer = (draft: Draft<DataStoreState>,
rootItemID: ItemID,
subtree: ItemID[],
currentDate: DayID): boolean => {
const item = draft.items.get(rootItemID)
if (item === undefined) return false
const firstTask: Task = {
cost: item.cost,
end: item.dueDate,
itemID: rootItemID,
start: item.deferDate,
}
if (firstTask.end === undefined) {
item.status = ItemStatus.COMPLETED
return false
}
// Move start and end to today
let repeatOffset = 0
if (item.repeatOnCompletion) {
repeatOffset = this.getCurrentDayID() - firstTask.end
firstTask.end += repeatOffset
if (firstTask.start !== undefined) {
firstTask.start += repeatOffset
}
}
const repeat = item.repeat
if (repeat === undefined) {
item.status = ItemStatus.COMPLETED
return false
}
const repeater = DEFAULT_REPEATER_BY_TYPE.get(repeat.type)
if (repeater === undefined) {
item.status = ItemStatus.COMPLETED
return false
}
const iterator = repeater(
firstTask, this.getEffectiveInfo(item), dayIDNow() + 100000000)
let nextTask: Task | undefined = undefined
while (true) {
nextTask = iterator()
if (nextTask === undefined || nextTask.end === undefined ||
nextTask.end >= currentDate) {
break
}
}
if (nextTask === undefined) {
item.status = ItemStatus.COMPLETED
return false
}
const subtreeInfo: SubtreeRepetitionInfo[] = []
const count = subtree.length
for (let i = 0; i < count; i++) {
const subtreeItemID = subtree[i]
const subtreeItem = draft.items.get(subtreeItemID)
if (subtreeItem === undefined) continue
subtreeItem.status = ItemStatus.ACTIVE
if (subtreeItemID === rootItemID) { // Is root item
const startOffset = subtreeItem.repeatDeferOffset === undefined ?
undefined : subtreeItem.repeatDeferOffset
const endOffset = 0
subtreeInfo.push({
itemID: subtreeItemID,
startOffset,
endOffset,
})
} else {
const startOffset = subtreeItem.deferDate === undefined ? undefined :
firstTask.end - repeatOffset - subtreeItem.deferDate
const endOffset = subtreeItem.dueDate === undefined ? 0 :
firstTask.end - repeatOffset - subtreeItem.dueDate
subtreeInfo.push({
itemID: subtreeItemID,
startOffset,
endOffset,
})
}
}
const repetitionResults = generateSubtreeRepetition(
nextTask, rootItemID, subtreeInfo)
const numResults = repetitionResults.length
for (let i = 0; i < numResults; ++i) {
const result = repetitionResults[i]
const subtreeItem = draft.items.get(result.itemID)
if (subtreeItem === undefined) continue
subtreeItem.deferDate = result.deferDate
subtreeItem.dueDate = result.dueDate
}
return true
}
/**
* NOTE: This function searches for item information in the current state.
* However, it does use the queue array from the given draft, since the queue
* array contains only primitives.
*/
private smartInsertItemsToQueueReducer = (draft: Draft<DataStoreState>,
itemIDs: ItemID[]) => {
// TODO optimize for single item insertion (without the need to sort)
const postOrderIndices = this.getPostOrderIndices()
const proxyQueue = this.computeQueuePriorityProxies(
draft.queue, postOrderIndices)
itemIDs.forEach(itemID => {
const item = this.getItem(itemID)
if (item === undefined) return
proxyQueue.push({
itemID: item.id,
priorityProxy: getQueuePriorityProxy(
this.getEffectiveDueDate(item), postOrderIndices.get(item.id) || 0),
})
})
proxyQueue.sort(
(a, b) => queuePriorityProxyCompare(a.priorityProxy, b.priorityProxy))
draft.queue = proxyQueue.map(item => item.itemID)
}
private removeItemFromQueueReducer = (draft: Draft<DataStoreState>,
itemID: ItemID) => {
removeValue(draft.queue, itemID)
}
private removeItemsFromQueueReducer = (draft: Draft<DataStoreState>,
itemIDs: ItemID[]) => {
const itemIDSet = new Set(itemIDs)
draft.queue = draft.queue.filter(value => !itemIDSet.has(value))
}
private autoAdjustQueueReducer = (draft: Draft<DataStoreState>) => {
const queueSize = draft.queue.length
const datedIndices: number[] = []
const data: {
itemID: ItemID,
dueDate: DayID,
originalIndex: number,
}[] = []
for (let i = 0; i < queueSize; ++i) {
const itemID = draft.queue[i]
const item = this.getItem(itemID)
if (item === undefined) {
throw new Error('Queue contained invalid itemID')
}
if (!item.autoAdjustPriority) continue
const dueDate = this.getEffectiveDueDate(item)
if (dueDate !== undefined) {
datedIndices.push(i)
data.push({
dueDate, itemID, originalIndex: i,
})
}
}
data.sort((a, b) => {
if (a.dueDate !== b.dueDate) {
return a.dueDate - b.dueDate
}
return a.originalIndex - b.originalIndex
})
const count = datedIndices.length
for (let i = 0; i < count; ++i) {
draft.queue[datedIndices[i]] = data[i].itemID
}
}
/**
* NOTE: This function searches for some items using the current state.
* Keep this in mind before chaining reducers on drafts.
*/
private updateAncestorChainStatisticsReducer = (draft: Draft<DataStoreState>,
initialItemID: ItemID) => {
let lastUpdatedItemID: ItemID | undefined = undefined
let itemID: ItemID | undefined = initialItemID
while (itemID !== undefined) {
const item = draft.items.get(itemID)
if (item === undefined) break
let childrenCost = 0
const childrenIDs = item.childrenIDs
const numChildren = childrenIDs.length
for (let j = 0; j < numChildren; j++) {
const childID = childrenIDs[j]
const child = (childID === lastUpdatedItemID ?
draft.items.get(childID) : this.getItem(childID))
if (child === undefined) continue
childrenCost += child.effectiveCost
}
if (numChildren === 0) {
item.effectiveCost = Math.max(childrenCost, item.cost)
item.residualCost = item.effectiveCost - childrenCost
} else { // When there's children, assume self cost is 0
item.effectiveCost = childrenCost
item.residualCost = 0
}
lastUpdatedItemID = itemID
itemID = item.parentID
}
}
private addQuotaRuleReducer = (draft: Draft<DataStoreState>,
quotaRuleDraft: QuotaRuleDraft<QuotaRule>) => {
const id = draft.nextQuotaRuleID
const quotaRule = draftToQuotaRule(quotaRuleDraft)
quotaRule.id = id
draft.nextQuotaRuleID++
if (draft.nextQuotaRuleID <= id) {
throw new Error('QuotaRule ID overflow')
}
if (draft.quotaRules.has(quotaRule.id)) {
throw new Error(`QuotaRule with ID ${quotaRule.id} already exists`)
}
draft.quotaRules.set(quotaRule.id, quotaRule)
draft.quotaRuleOrder.push(quotaRule.id)
}
private updateQuotaRuleReducer = (draft: Draft<DataStoreState>,
quotaRuleDraft: QuotaRuleDraft<QuotaRule>) => {
const quotaRuleID = quotaRuleDraft.id
const quotaRule = draftToQuotaRule(quotaRuleDraft)
if (!draft.quotaRules.has(quotaRuleID)) {
throw new Error(`QuotaRule with ID ${quotaRuleID} does not exist`)
}
draft.quotaRules.set(quotaRuleID, quotaRule)
}
private removeQuotaRuleReducer = (draft: Draft<DataStoreState>,
quotaRuleID: QuotaRuleID) => {
draft.quotaRules.delete(quotaRuleID)
removeValue(draft.quotaRuleOrder, quotaRuleID)
}
private removeQuotaRulesReducer = (draft: Draft<DataStoreState>,
quotaRuleIDs: QuotaRuleID[]) => {
quotaRuleIDs.forEach(quotaRuleID => {
draft.quotaRules.delete(quotaRuleID)
})
const quotaRuleIDSet = new Set(quotaRuleIDs)
draft.quotaRuleOrder =
draft.quotaRuleOrder.filter(value => !quotaRuleIDSet.has(value))
}
private quotaRuleMoveReducer = (draft: Draft<DataStoreState>,
quotaRuleID: QuotaRuleID,
index: number) => {
const oldIndex = draft.quotaRuleOrder.indexOf(quotaRuleID)
if (oldIndex < 0) return
arrayMove(draft.quotaRuleOrder, oldIndex, index)
}
/**
* NOTE: This method will always return a new array.
*/
getChildren = (item: Item) => {
const children: Item[] = []
const numChildren = item.childrenIDs.length
for (let i = 0; i < numChildren; ++i) {
const childID = item.childrenIDs[i]
const child = this.getItem(childID)
if (child === undefined) {
throw new Error(`Child ${childID} not found`)
}
children.push(child)
}
return children
}
private _freezeNotifyAndUndo = 0
maxUndoHistory = 50
private autoSaveStarted = false
lastSavedMs = new BehaviorSubject(new Date())
constructor(private readonly metadataStore: MetadataStore,
private readonly fsUtil: FsUtil) {
// TODO remove this
/*
this.batchEdit(() => {
let draft = new ItemDraft(-1, 'Hello')
draft.color =
Color.rgb(Math.random() * 255, Math.random() * 255, Math.random() * 255)
this.addItem(draft)
draft = new ItemDraft(-1, 'World')
draft.color =
Color.rgb(Math.random() * 255, Math.random() * 255, Math.random() * 255)
this.addItem(draft)
draft = new ItemDraft(-1, 'Okay')
draft.color =
Color.rgb(Math.random() * 255, Math.random() * 255, Math.random() * 255)
this.addItem(draft)
draft = new ItemDraft(-1, 'QWER')
draft.color =
Color.rgb(Math.random() * 255, Math.random() * 255, Math.random() * 255)
draft.parentID = 2
this.addItem(draft)
draft = new ItemDraft(-1, 'POIUPOIQWUE')
draft.color =
Color.rgb(Math.random() * 255, Math.random() * 255, Math.random() * 255)
draft.parentID = 4
this.addItem(draft)
draft = new ItemDraft(-1, 'qvqqvqvq')
draft.color =
Color.rgb(Math.random() * 255, Math.random() * 255, Math.random() * 255)
draft.parentID = 2
this.addItem(draft)
draft = new ItemDraft(-1, '324142124')
draft.color =
Color.rgb(Math.random() * 255, Math.random() * 255, Math.random() * 255)
draft.parentID = 1
this.addItem(draft)
// for (let i = 0; i < 200; ++i) {
// let draft = new ItemDraft(-1, 'Hello' + i.toString())
// draft.color =
// Color.rgb(
// Math.random() * 255, Math.random() * 255, Math.random() * 255)
// this.addItem(draft)
// }
// this.addSession(dayIDNow(), SessionType.COMPLETED, 1, 3)
// this.addSession(dayIDNow(), SessionType.PROJECTED, 2, 4)
// this.addSession(dayIDNow() + 1, SessionType.SCHEDULED, 3, 6)
this.addQuotaRule({
type: 'constant',
id: -1,
value: 5,
dayOfWeek: [],
} as ConstantQuotaRule)
this.addQuotaRule({
type: 'constant',
id: -1,
value: 4,
dayOfWeek: [1, 2, 3, 4, 5],
} as ConstantQuotaRule)
this.addQuotaRule({
type: 'constant',
id: -1,
value: 8,
dayOfWeek: [0, 6],
} as ConstantQuotaRule)
})
this.clearUndo()
*/
}
startAutoSave() {
if (this.autoSaveStarted) return
this.autoSaveStarted = true
// Idle save
this.onChange.pipe(debounceTime(AUTO_SAVE_IDLE_DELAY)).subscribe(() => {
this.save()
})
// Interval save
setInterval(() => {
const now = Date.now()
if (now - this.lastSavedMs.value.getTime() >= AUTO_SAVE_INTERVAL - 5000) {
this.save()
}
}, AUTO_SAVE_INTERVAL)
// Save on quit
window.addEventListener('beforeunload', () => {
this.save()
})
}
public get state() {
return this._state
}
validateItemDraft(draft: ItemDraft, isNewItem: boolean) {
if (!isNewItem && draft.parentID !== undefined &&
!this.canBeParentOf(draft.id, draft.parentID)) {
throw {
type: 'invalidParent',
message: 'Error: Invalid parent',
}
}
if (draft.name === '' || draft.name.indexOf(':') !== -1 ||
draft.name.indexOf('#') !== -1 || draft.name.indexOf('[') !== -1) {
throw {
type: 'invalidName',
message: 'Error: Invalid item name',
}
}
if (draft.cost < 0 || !Number.isInteger(draft.cost)) {
throw {
type: 'invalidCost',
message: 'Error: Invalid cost',
}
}
if (draft.repeat !== undefined &&
(draft.repeatInterval <= 0 || !Number.isInteger(draft.repeatInterval))) {
throw {
type: 'invalidRepeat',
message: 'Error: Invalid repeat interval',
}
}
if (draft.deferDate !== undefined && draft.dueDate !== undefined &&
draft.deferDate > draft.dueDate) {
throw {
type: 'invalidDeferDateDueDate',
message: 'Error: Defer date cannot be after due date',
}
}
if (draft.repeatDeferOffset !== undefined && (draft.repeatDeferOffset < 0 ||
!Number.isInteger(draft.repeatDeferOffset))) {
throw {
type: 'invalidRepeatDeferOffset',
message: 'Error: Invalid repeat defer offset',
}
}
}
public addItem(itemDraft: ItemDraft, skipValidation: boolean = false) {
if (!skipValidation) {
this.validateItemDraft(itemDraft, true)
}
this.pushUndo()
let id = 0
const newStatus = itemDraft.status
this._state =
produce(this._state, draft => {
id = this.addItemReducer(draft, itemDraft)
})
if (newStatus === ItemStatus.ACTIVE) {
this._state =
produce(this._state, draft => {
this.smartInsertItemsToQueueReducer(draft, [id])
})
}
this._state =
produce(this._state, draft => {
this.updateAncestorChainStatisticsReducer(draft, id)
})
this.notify()
return id
}
/**
* Returns whether the item repeated.
*/
public updateItem(itemDraft: ItemDraft, options: UpdateItemOptions = {},
skipValidation: boolean = false, skipEffortCheck = false) {
if (!skipValidation) {
this.validateItemDraft(itemDraft, false)
}
let repeated = false
const itemID = itemDraft.id
const item = this.getItem(itemID)
if (item === undefined) {
throw new Error(`Item with ID ${itemID} does not exist`)
}
const oldStatus = item.status
const newStatus = itemDraft.status
const oldParentID = item.parentID
const newParentID = itemDraft.parentID
const shouldRepeat = (
oldStatus !== ItemStatus.COMPLETED &&
newStatus === ItemStatus.COMPLETED &&
itemDraft.repeat !== undefined &&
!this.getHasAncestorRepeat(item)
)
/*
const oldDueDate = item.dueDate
const newDueDate = itemDraft.dueDate
if (!skipEffortCheck && this.metadataStore.increasePostponementEffort &&
oldDueDate !== undefined &&
(newDueDate === undefined || newDueDate > oldDueDate)) {
var str = ''
for (var i = 0; i < 20; ++i) {
str += Math.floor(Math.random() * 10).toString(10)
}
this.simplePrompt(
'You are postponing a due date. Please enter the following text to proceed: ' +
str).then(input => {
if (input === str) {
this.updateItem(itemDraft, options, skipValidation, skipEffortCheck)
} else {
alert('Error: wrong input.')
}
}).catch(err => {
alert(err)
console.log(err)
})
return
}
*/
this.pushUndo()
this._state = produce(
this._state,
draft => {
this.updateItemReducer(draft, itemDraft, options)
},
)
if (shouldRepeat) {
const subtree = this.getSubtreeItems(itemID)
let repeatSuccessful = false
const currentDate = this.getCurrentDayID()
this._state = produce(this._state, draft => {
repeatSuccessful =
this.repeatSubtreeReducer(draft, itemID, subtree, currentDate)
})
if (repeatSuccessful) {
repeated = true
this._state =
produce(this._state, draft => {
this.removeItemsFromQueueReducer(draft, subtree)
this.smartInsertItemsToQueueReducer(draft, subtree)
})
} else {
this._state =
produce(this._state, draft => {
this.removeItemFromQueueReducer(draft, itemID)
})
}
} else {
if (oldStatus !== newStatus) {
const subtree = this.getSubtreeItems(itemID)
if (newStatus === ItemStatus.ACTIVE) {
this._state =
produce(this._state, draft => {
this.removeItemsFromQueueReducer(draft, subtree)
this.smartInsertItemsToQueueReducer(draft, subtree)
})
} else {
this._state =
produce(this._state, draft => {
this.removeItemsFromQueueReducer(draft, subtree)
})
}
}
}
if (oldParentID !== newParentID && oldParentID !== undefined) {
this._state = produce(this._state, draft => {
this.updateAncestorChainStatisticsReducer(draft, oldParentID)
})
}
this._state = produce(this._state, draft => {
this.updateAncestorChainStatisticsReducer(draft, itemID)
this.autoAdjustQueueReducer(draft)
})
this.notify()
return repeated
}
private simplePrompt(prompt: string) {
// TODO
}
public removeItem(itemID: ItemID) {
this.pushUndo()
this._state =
produce(this._state, draft => {
this.removeItemReducer(draft, itemID)
// This will automatically remove things from queue as well
})
this.notify()
}
public getItem(itemID: ItemID) {
return this._state.items.get(itemID)
}
public hasItem(itemID: ItemID) {
return this._state.items.has(itemID)
}
private editSession(dayID: DayID, type: SessionType, itemID: ItemID,
modification: SessionModificationType,
count: number = 1) {
this.pushUndo()
this._state = produce(
this._state,
draft => {
this.editSessionReducer(draft, dayID, type, itemID, modification, count)
},
)
this.notify()
}
public addSession(dayID: DayID, type: SessionType, itemID: ItemID,
count: number = 1) {
this.editSession(dayID, type, itemID, SessionModificationType.ADD, count)
}
public removeSession(dayID: DayID, type: SessionType, itemID: ItemID,
count: number = 1) {
this.editSession(dayID, type, itemID, SessionModificationType.ADD, -count)
}
private setSession(dayID: DayID, type: SessionType, itemID: ItemID,
count: number = 1) {
this.editSession(dayID, type, itemID, SessionModificationType.SET, count)
}
/**
* Move item to before a specific anchor on queue.
* NOTE: This function searches for itemID using the current state.
* Keep this in mind before chaining reducers on drafts.
*/
public queueMoveToBefore(itemID: ItemID, anchorItemID: ItemID) {
const anchorIndex = this.state.queue.indexOf(anchorItemID)
if (anchorIndex < 0) return
this.queueMoveToIndex(itemID, anchorIndex)
}
/**
* Move item to after a specific anchor on queue.
* NOTE: This function searches for itemID using the current state.
* Keep this in mind before chaining reducers on drafts.
*/
public queueMoveToAfter(itemID: ItemID, anchorItemID: ItemID) {
const anchorIndex = this.state.queue.indexOf(anchorItemID)
if (anchorIndex < 0) return
this.queueMoveToIndex(itemID, anchorIndex + 1)
}
/**
* Move item to before the item pointed to by the given index.
* NOTE: The item pointed to by the given index is considered *before* moving
* the old item.
*/
public queueMoveToIndex(itemID: ItemID, index: number) {
this.pushUndo()
this._state =
produce(this._state, draft => {
this.queueMoveReducer(draft, itemID, index)
})
this.notify()
}
public addQuotaRule(quotaRuleDraft: QuotaRuleDraft<QuotaRule>) {
this.validateQuotaRuleDraft(quotaRuleDraft)
this.pushUndo()
this._state =
produce(this._state, draft => {
this.addQuotaRuleReducer(draft, quotaRuleDraft)
})
this.cleanUpQuotaRules()
this.notify()
}
public getQuotaRule(quotaRuleID: QuotaRuleID) {
return this._state.quotaRules.get(quotaRuleID)
}
public updateQuotaRule(quotaRuleDraft: QuotaRuleDraft<QuotaRule>) {
this.validateQuotaRuleDraft(quotaRuleDraft)
this.pushUndo()
this._state =
produce(this._state, draft => {
this.updateQuotaRuleReducer(draft, quotaRuleDraft)
})
this.cleanUpQuotaRules()
this.notify()
}
public removeQuotaRule(quotaRuleID: QuotaRuleID) {
this.pushUndo()
this._state =
produce(this._state, draft => {
this.removeQuotaRuleReducer(draft, quotaRuleID)
})
this.cleanUpQuotaRules()
this.notify()
}
public quickEditQuotaRule(dayID: DayID, value: number) {
value = Math.max(0, Math.round(value))
const numQuotaRules = this.state.quotaRuleOrder.length
const tempMap = new Map<DayID, number>()
for (let i = numQuotaRules - 1; i >= 0; i--) {
const ruleID = this.state.quotaRuleOrder[i]
const rule = this.getQuotaRule(ruleID)
if (rule === undefined) continue
if (rule.firstDate !== undefined && rule.lastDate !== undefined &&
rule.firstDate === rule.lastDate && isConstantQuotaRule(rule) &&
rule.firstDate === dayID) {
// The quota for the given day is affected by a single-day rule.
const draft = quotaRuleToDraft(rule)
draft.value = value
this.batchEdit(it => {
this.updateQuotaRule(draft)
this.quotaRuleMoveToIndex(ruleID, numQuotaRules)
})
return
}
}
const draft: QuotaRuleDraft<ConstantQuotaRule> = {
type: 'constant',
id: -1,
firstDate: dayID,
lastDate: dayID,
value,
dayOfWeek: [],
}
this.addQuotaRule(draft)
}
private cleanUpQuotaRules() {
const rulesToDelete: QuotaRuleID[] = []
const thresholdDayID = this.getCurrentDayID() -
this.state.settings.quotaRuleAutoDeleteDays
this.state.quotaRules.forEach(quotaRule => {
if (quotaRule.lastDate !== undefined && quotaRule.lastDate <
thresholdDayID) {
rulesToDelete.push(quotaRule.id)
}
})
this._state = produce(this._state, draft => {
this.removeQuotaRulesReducer(draft, rulesToDelete)
})
}
/**
* Move quotaRule to before a specific anchor on quotaRuleOrder.
* NOTE: This function searches for quotaRuleID using the current state.
* Keep this in mind before chaining reducers on drafts.
*/
public quotaRuleMoveToBefore(quotaRuleID: QuotaRuleID,
anchorQuotaRuleID: QuotaRuleID) {
const anchorIndex = this.state.quotaRuleOrder.indexOf(anchorQuotaRuleID)
if (anchorIndex < 0) return
this.quotaRuleMoveToIndex(quotaRuleID, anchorIndex)
}
/**
* Move quotaRule to after a specific anchor on quotaRuleOrder.
* NOTE: This function searches for quotaRuleID using the current state.
* Keep this in mind before chaining reducers on drafts.
*/
public quotaRuleMoveToAfter(quotaRuleID: QuotaRuleID,
anchorQuotaRuleID: QuotaRuleID) {
const anchorIndex = this.state.quotaRuleOrder.indexOf(anchorQuotaRuleID)
if (anchorIndex < 0) return
this.quotaRuleMoveToIndex(quotaRuleID, anchorIndex + 1)
}
/**
* Move quotaRule to before the quotaRule pointed to by the given index.
* NOTE: The quotaRule pointed to by the given index is considered *before*
* moving the old quotaRule.
*/
public quotaRuleMoveToIndex(quotaRuleID: QuotaRuleID, index: number) {
this.pushUndo()
this._state =
produce(this._state, draft => {
this.quotaRuleMoveReducer(draft, quotaRuleID, index)
})
this.notify()
}
public getDayData(dayID: DayID) {
return this._state.timelineData.tryGet(dayID) || DataStore.defaultDayData
}
/**
* Execute func without triggering any notification or undo.
* Once func is returned, subscribers will be notified.
* NOTE: Make sure to catch any error *inside* the func instead of putting try
* outside of batchEdit.
*/
public batchEdit(func: (dataStore: DataStore) => void) {
if (this._freezeNotifyAndUndo === 0) {
this.pushUndo()
}
this._freezeNotifyAndUndo++
func(this)
this._freezeNotifyAndUndo--
if (this._freezeNotifyAndUndo === 0) {
this.notify()
}
}
public getQueuePredecessor(itemID: ItemID) {
const index = this.state.queue.indexOf(itemID)
if (index <= 0) return undefined
return this.state.queue[index - 1]
}
clearUndo() {
this.undoHistory = []
this.redoHistory = []
}
private pushUndo() {
if (this._freezeNotifyAndUndo > 0) return
// TODO optimize: use a ring
this.undoHistory.push(this._state)
if (this.undoHistory.length > this.maxUndoHistory) {
this.undoHistory.shift()
}
this.redoHistory = []
}
canUndo() {
return this.undoHistory.length > 0
}
undo() {
if (this._freezeNotifyAndUndo > 0) return
if (this.undoHistory.length > 0) {
this.redoHistory.push(this._state)
this._state = this.undoHistory.pop()!
}
this.notify()
}
canRedo() {
return this.redoHistory.length > 0
}
redo() {
if (this._freezeNotifyAndUndo > 0) return
if (this.redoHistory.length > 0) {
this.undoHistory.push(this._state)
this._state = this.redoHistory.pop()!
}
this.notify()
}
private notify() {
if (this._freezeNotifyAndUndo > 0) return
this.onChangeSubject.next(this)
}
private _removeAllChildrenOf(draft: Draft<DataStoreState>,
item: Draft<Item>) {
const numChildren = item.childrenIDs.length
for (let i = 0; i < numChildren; ++i) {
const childID = item.childrenIDs[i]
const child = draft.items.get(childID)
if (child === undefined) {
throw new Error(`Child ${childID} not found`)
}
this._removeAllChildrenOf(draft, child)
draft.items.delete(childID)
this.invalidateItemID(draft, childID)
}
item.childrenIDs = []
}
/**
* NOTE: This function searches for itemID references (e.g. sessions) using
* the current state, not the given draft.
* Keep this in mind before chaining reducers on drafts.
*/
private invalidateItemID(draft: Draft<DataStoreState>, itemID: ItemID) {
this._state.timelineData.forEach((dayData, dayID) => {
dayData.sessions.forEach((sessions, type) => {
sessions.forEach((count, sessionItemID) => {
if (sessionItemID === itemID) {
draft.timelineData.tryGet(dayID)!.sessions.get(type)!.delete(itemID)
}
})
})
})
removeValue(draft.queue, itemID)
}
getItemColor(item: Item): Color {
let i: Item | undefined = item
let result = i.color
while (i !== undefined && i.tryUseParentColor && i.parentID !== undefined) {
i = this.getItem(i.parentID)
if (i !== undefined) result = i.color
}
return result
}
getRelativeEffectiveDateRange(item: Item, ancestorID: ItemID): {
deferDate?: DayID,
dueDate?: DayID,
} {
if (item.id === ancestorID) return {}
let i: Item | undefined = item
let result = {
dueDate: i.dueDate,
deferDate: i.deferDate,
}
while (i.parentID !== undefined) {
i = this.getItem(i.parentID)
if (i === undefined) break
if (i.id === ancestorID) break
if (result.deferDate === undefined) {
result.deferDate = i.deferDate
} else {
result.deferDate =
optionalClamp(result.deferDate, i.deferDate, i.dueDate)
}
if (result.dueDate === undefined) {
result.dueDate = i.dueDate
} else {
result.dueDate = optionalClamp(result.dueDate, i.deferDate, i.dueDate)
}
}
return result
}
getEffectiveDeferDate(item: Item): DayID | undefined {
let i: Item | undefined = item
let result = i.deferDate
while (i !== undefined && i.parentID !== undefined) {
i = this.getItem(i.parentID)
if (i === undefined) continue
if (result === undefined) {
result = i.deferDate
} else {
result = optionalClamp(result, i.deferDate, i.dueDate)
}
}
return result
}
getEffectiveDueDate(item: Item): DayID | undefined {
let i: Item | undefined = item
let result = i.dueDate
while (i !== undefined && i.parentID !== undefined) {
i = this.getItem(i.parentID)
if (i === undefined) continue
if (result === undefined) {
result = i.dueDate
} else {
result = optionalClamp(result, i.deferDate, i.dueDate)
}
}
return result
}
getHasAncestorRepeat(item: Item): boolean {
let i: Item | undefined = item
while (i !== undefined && i.parentID !== undefined) {
i = this.getItem(i.parentID)
if (i !== undefined && i.repeat !== undefined) {
return true
}
}
return false
}
getAllEffectiveInfo(): Map<ItemID, EffectiveItemInfo> {
// TODO optimize: use DFS
const result = new Map<ItemID, EffectiveItemInfo>()
this.state.items.forEach(item => {
result.set(item.id, this.getEffectiveInfo(item))
})
return result
}
getEffectiveInfo(item: Item): EffectiveItemInfo {
let i: Item | undefined = item
let result: EffectiveItemInfo = {
deferDate: i.deferDate,
dueDate: i.dueDate,
repeat: i.repeat,
repeatEndDate: i.repeatEndDate,
repeatInterval: i.repeatInterval,
repeatOnCompletion: i.repeatOnCompletion,
hasAncestorRepeat: false,
hasActiveAncestorRepeat: false,
}
let minParentDueDate: DayID | undefined = undefined
while (i !== undefined && i.parentID !== undefined) {
i = this.getItem(i.parentID)
if (i === undefined) continue
if (result.deferDate === undefined) {
result.deferDate = i.deferDate
} else {
result.deferDate =
optionalClamp(result.deferDate, i.deferDate, i.dueDate)
}
if (result.dueDate === undefined) {
result.dueDate = i.dueDate
} else {
result.dueDate = optionalClamp(result.dueDate, i.deferDate, i.dueDate)
}
if (i.dueDate !== undefined) {
if (minParentDueDate === undefined) {
minParentDueDate = i.dueDate
} else {
minParentDueDate = Math.min(minParentDueDate, i.dueDate)
}
}
if (i.repeat !== undefined) {
// Use ancestor repeat if exists
result.repeat = i.repeat
result.repeatEndDate = i.repeatEndDate
result.repeatInterval = i.repeatInterval
result.repeatOnCompletion = i.repeatOnCompletion
result.hasAncestorRepeat = true
result.hasActiveAncestorRepeat = i.status !== ItemStatus.COMPLETED
}
}
// Clamp repeat end date to earliest parent due date
if (minParentDueDate !== undefined) {
if (result.repeatEndDate === undefined) {
result.repeatEndDate = minParentDueDate
} else {
result.repeatEndDate = Math.min(result.repeatEndDate, minParentDueDate)
}
}
return result
}
getRootItems() {
const result: Item[] = []
const numRootItems = this._state.rootItemIDs.length
for (let i = 0; i < numRootItems; i++) {
result.push(this.getItem(this._state.rootItemIDs[i])!)
}
return result
}
generateColor() {
const [r, g, b] = convert.hsl.rgb(
random(0, 360), random(50, 100), random(50, 75))
return Color.rgb(r, g, b)
}
/**
* NOTE: This is created with current state.
* Do not use if state is changed.
*/
createAutoCompleter(filter?: (item: Item) => boolean) {
return new DataStoreAutoCompleter(this, filter)
}
getQualifiedName(item: Item) {
let result = item.name
while (item.parentID !== undefined) {
const parent = this.getItem(item.parentID)
if (parent === undefined) {
throw new Error(`Parent ID ${item.parentID} not found`)
}
item = parent
result = item.name + ' : ' + result
}
return result
}
canBeParentOf(itemID: ItemID, parentID: ItemID) {
let p: ItemID | undefined = parentID
while (p !== undefined) {
if (itemID === p) return false
const parent = this.getItem(p)
if (parent === undefined) {
break
}
p = parent.parentID
}
return true
}
/**
* The indices are guaranteed to be non-negative.
* Higher index means an item comes later in post-order tree traversal.
*/
getPostOrderIndices(): Map<ItemID, number> {
const result = new Map<ItemID, number>()
const count = this.state.rootItemIDs.length
const counter = {value: 1}
for (let i = 0; i < count; i++) {
const item = this.getItem(this.state.rootItemIDs[i])
if (item === undefined) continue
this.getPostOrderIndicesInternal(item, counter, result)
}
return result
}
private getPostOrderIndicesInternal(item: Item, counter: { value: number },
result: Map<ItemID, number>) {
const numChildren = item.childrenIDs.length
for (let i = 0; i < numChildren; i++) {
const child = this.getItem(item.childrenIDs[i])
if (child === undefined) continue
this.getPostOrderIndicesInternal(child, counter, result)
}
result.set(item.id, counter.value)
counter.value++
}
public getSubtreeItems(itemID: ItemID): ItemID[] {
const item = this.getItem(itemID)
if (item === undefined) return []
const result: ItemID[] = []
this.getSubtreeItemsInternal(item, result)
return result
}
private getSubtreeItemsInternal(item: Item, result: ItemID[]) {
result.push(item.id)
const numChildren = item.childrenIDs.length
for (let i = 0; i < numChildren; i++) {
const childID = item.childrenIDs[i]
const child = this.getItem(childID)
if (child === undefined) continue
this.getSubtreeItemsInternal(child, result)
}
}
/**
* NOTE: The returned list will be in bottom-top order.
*/
public getAncestorsPlusSelf(itemID: ItemID): ItemID[] {
const result: ItemID[] = []
let i: Item | undefined = this.getItem(itemID)
while (i !== undefined) {
result.push(i.id)
if (i.parentID === undefined) break
i = this.getItem(i.parentID)
}
return result
}
private setDraftSubtreeStatus(draft: Draft<DataStoreState>, item: Draft<Item>,
status: ItemStatus) {
// TODO optimize: This causes the children ID array to be drafted
item.status = status
const numChildren = item.childrenIDs.length
for (let i = 0; i < numChildren; i++) {
const childID = item.childrenIDs[i]
const child = draft.items.get(childID)
if (child === undefined) continue
this.setDraftSubtreeStatus(draft, child, status)
}
}
/**
* Get the DayID of today, taking into account the "start of day" setting.
*/
getCurrentDayID() {
return dayIDNow(this.state.settings.startOfDayMinutes)
}
/**
* TODO optimize: use draw-based method instead of query-based method
*/
getQuota(rangeFirst: DayID, rangeLast: DayID) {
if (rangeFirst > rangeLast) {
return new Map<DayID, number>()
}
const result = new Map<DayID, number>()
for (let d = rangeFirst; d <= rangeLast; d++) {
result.set(d, 0)
}
for (let i = 0; i < this.state.quotaRuleOrder.length; i++) {
const quotaRule = this.getQuotaRule(this.state.quotaRuleOrder[i])
if (quotaRule === undefined) continue
const applier = DEFAULT_QUOTA_RULE_APPLIER_BY_TYPE.get(quotaRule.type)
if (applier === undefined) continue
applier.apply(quotaRule, rangeFirst, rangeLast, result)
}
return result
}
validateQuotaRuleDraft(quotaRuleDraft: QuotaRuleDraft<QuotaRule>) {
if (quotaRuleDraft.firstDate !== undefined && quotaRuleDraft.lastDate !==
undefined && quotaRuleDraft.firstDate > quotaRuleDraft.lastDate) {
throw {
type: 'invalidRange',
message: 'Error: Invalid range',
}
}
if (isConstantQuotaRule(quotaRuleDraft)) {
if (quotaRuleDraft.value < 0 || !Number.isInteger(quotaRuleDraft.value)) {
throw {
type: 'invalidValue',
message: 'Error: Invalid quota value',
}
}
}
}
/**
* NOTE: This is only valid as long as items are not changed/added/deleted.
*/
computeQueuePriorityProxies(
queue: ItemID[],
postOrderIndices?: Map<ItemID, number>, /* For optional performance*/
): {
itemID: ItemID,
priorityProxy: QueuePriorityProxy,
}[] {
if (postOrderIndices === undefined) {
postOrderIndices = this.getPostOrderIndices()
}
const currentDayID = this.getCurrentDayID()
const result: {
itemID: ItemID,
priorityProxy: QueuePriorityProxy,
}[] = []
const queueSize = queue.length
for (let i = 0; i < queueSize; i++) {
const itemID = queue[i]
const item = this.getItem(itemID)
if (item === undefined) continue
result.push({
itemID,
priorityProxy: getQueuePriorityProxy(
this.getEffectiveDueDate(item), postOrderIndices.get(itemID) || 0),
})
}
// NOTE: Below makes the assumption that items in the queue are unique
const pivots = result.map(
(item, index) => ({index, priorityProxy: item.priorityProxy}))
.filter(item => item.priorityProxy[0] !== undefined)
const lisIndices = longestIncreasingSubsequence(
pivots,
(a, b) => queuePriorityProxyCompare(a.priorityProxy, b.priorityProxy),
)
// Interpolate due dates between pivots
if (lisIndices.length > 0) {
// Note that both pivot 1 and pivot 2 are exclusive.
const interpolateDueDates = (pivot1: number, pivot2: number,
dueDate1: DayID, dueDate2?: DayID) => {
for (let i = pivot1 + 1; i < pivot2; i++) {
if (dueDate2 === undefined) {
result[i].priorityProxy[0] = undefined
} else {
result[i].priorityProxy[0] = Math.round(
clampedLinearMap(pivot1, pivot2, dueDate1, dueDate2, i))
}
}
}
let pivot = pivots[lisIndices[0]]
interpolateDueDates(
-1, pivot.index, Math.min(currentDayID, pivot.priorityProxy[0]!),
pivot.priorityProxy[0]!,
)
for (let i = 1; i < lisIndices.length; ++i) {
const pivot1 = pivots[lisIndices[i - 1]]
const pivot2 = pivots[lisIndices[i]]
interpolateDueDates(
pivot1.index, pivot2.index, pivot1.priorityProxy[0]!,
pivot2.priorityProxy[0]!,
)
}
pivot = pivots[lisIndices[lisIndices.length - 1]]
interpolateDueDates(
pivot.index, result.length,
pivot.priorityProxy[0]!,
undefined,
)
}
// Fix unnatural orderings
for (let i = 1; i < result.length; ++i) {
const item1 = result[i - 1]
const item2 = result[i]
if (queuePriorityProxyCompare(item1.priorityProxy, item2.priorityProxy)
>= 0) { // Unnatural order
item2.priorityProxy[1] = item1.priorityProxy[1] + 1
}
}
return result
}
getSaveFilePath() {
return this.fsUtil.path.join(
this.metadataStore.dataDir, DATA_FILE_NAME)
}
save() {
this.lastSavedMs.next(new Date())
const filePath = this.getSaveFilePath()
const serializedObject = serializeDataStoreStateToObject(this.state)
const text = stringifySerializedObject(serializedObject)
this.fsUtil.safeWriteFileSync(
filePath, text, TEMP_DATA_FILE_NAME_1, TEMP_DATA_FILE_NAME_2)
}
/**
* Return if load successful
*/
load() {
const filePath = this.getSaveFilePath()
try {
const text = this.fsUtil.readFileTextSync(filePath)
if (text === undefined) return false
const serializedObject = parseSerializedObject(text)
this._state = deserializeDataStoreStateFromObject(serializedObject)
this.clearUndo()
this.onReloadSubject.next(this)
this.notify()
} catch (e) {
console.log(e)
return false
}
return true
}
} | the_stack |
import * as UtilInternal from "../../../../main/js/joynr/util/UtilInternal";
import Dispatcher from "../../../../main/js/joynr/dispatching/Dispatcher";
import JoynrMessage from "../../../../main/js/joynr/messaging/JoynrMessage";
import MessagingQos from "../../../../main/js/joynr/messaging/MessagingQos";
import DiscoveryEntryWithMetaInfo from "../../../../main/js/generated/joynr/types/DiscoveryEntryWithMetaInfo";
import * as Reply from "../../../../main/js/joynr/dispatching/types/Reply";
import BroadcastSubscriptionRequest from "../../../../main/js/joynr/dispatching/types/BroadcastSubscriptionRequest";
import MulticastSubscriptionRequest from "../../../../main/js/joynr/dispatching/types/MulticastSubscriptionRequest";
import SubscriptionRequest from "../../../../main/js/joynr/dispatching/types/SubscriptionRequest";
import SubscriptionReply from "../../../../main/js/joynr/dispatching/types/SubscriptionReply";
import SubscriptionStop from "../../../../main/js/joynr/dispatching/types/SubscriptionStop";
import * as MulticastPublication from "../../../../main/js/joynr/dispatching/types/MulticastPublication";
import nanoid from "nanoid";
const providerId = "providerId";
const providerDiscoveryEntry = new DiscoveryEntryWithMetaInfo({
domain: "testProviderDomain",
interfaceName: "interfaceName",
participantId: providerId,
lastSeenDateMs: Date.now(),
expiryDateMs: Date.now() + 60000,
publicKeyId: "publicKeyId",
isLocal: false,
qos: undefined as any,
providerVersion: undefined as any
});
const proxyId = "proxyId";
const noTtlUplift = 0;
const ttlUpliftMs = 10000;
const toleranceMs = 50;
function toEqualWithPositiveTolerance(actual: any, expected: any): { pass: boolean; message: string } {
const result: { pass: boolean; message: string } = {} as any;
if (expected === undefined || expected === null) {
result.pass = false;
result.message = `Expected expectation not to be ${expected}`;
return result;
}
if (actual === undefined || actual === null) {
result.pass = false;
result.message = `Expected value not to be ${actual}`;
return result;
}
const diff = actual - expected;
result.pass = diff >= 0;
if (!result.pass) {
result.message = `Expected ${actual} to be greater or equal than ${expected}`;
return result;
}
result.pass = diff < toleranceMs;
if (result.pass) {
result.message = `${actual} differs less than ${toleranceMs} from ${expected}`;
} else {
result.message = `Expected ${actual} to differ less than ${toleranceMs} from ${expected}`;
}
return result;
}
expect.extend({
toEqualWithPositiveTolerance
});
interface ExtendedMatchers extends jest.Matchers<any> {
toEqualWithPositiveTolerance: (expected: any) => any;
}
describe("libjoynr-js.joynr.ttlUpliftTest", () => {
let dispatcher: Dispatcher, dispatcherWithTtlUplift: any;
let clusterControllerMessagingStub: any, securityManager: any;
let requestReplyManager: any, subscriptionManager: any, publicationManager: any, messageRouter: any;
const subscriptionId = `mySubscriptionId-${nanoid()}`;
const multicastId = `multicastId-${nanoid()}`;
let ttl: number, messagingQos: MessagingQos, expiryDateMs: number, expiryDateWithTtlUplift: any;
let publicationTtlMs: number, subscriptionQos: any;
function receiveJoynrMessage(parameters: any) {
const joynrMessage = new JoynrMessage({
type: parameters.type,
payload: JSON.stringify(parameters.payload)
});
joynrMessage.from = proxyId;
joynrMessage.to = providerId;
joynrMessage.expiryDate = parameters.expiryDate;
return dispatcher.receive(joynrMessage);
}
function receiveJoynrMessageTtlUplift(parameters: any) {
const joynrMessage = new JoynrMessage({
type: parameters.type,
payload: JSON.stringify(parameters.payload)
});
joynrMessage.from = proxyId;
joynrMessage.to = providerId;
joynrMessage.expiryDate = parameters.expiryDate;
return dispatcherWithTtlUplift.receive(joynrMessage);
}
function checkMessageFromProxyWithTolerance(messageType: any, expectedExpiryDate: any) {
expect(clusterControllerMessagingStub.transmit).toHaveBeenCalled();
const msg = clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0];
expect(msg.type).toEqual(messageType);
expect(msg.from).toEqual(proxyId);
expect(msg.to).toEqual(providerId);
(expect(msg.expiryDate) as ExtendedMatchers).toEqualWithPositiveTolerance(expectedExpiryDate);
}
function checkMessageFromProvider(messageType: any, expectedExpiryDate: any) {
expect(clusterControllerMessagingStub.transmit).toHaveBeenCalled();
const msg = clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0];
expect(msg.type).toEqual(messageType);
expect(msg.from).toEqual(providerId);
expect(msg.to).toEqual(proxyId);
expect(msg.expiryDate).toEqual(expectedExpiryDate);
}
function checkRequestReplyMessage(expectedExpiryDate: any) {
checkMessageFromProvider(JoynrMessage.JOYNRMESSAGE_TYPE_REPLY, expectedExpiryDate);
}
function checkSubscriptionReplyMessage(expectedExpiryDate: any) {
checkMessageFromProvider(JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REPLY, expectedExpiryDate);
}
beforeEach(() => {
requestReplyManager = {
handleRequest: jest.fn().mockImplementation((_providerParticipantId, request, cb, replySettings) => {
const reply = Reply.create({
response: "response" as any,
requestReplyId: request.requestReplyId
});
return Promise.resolve(cb(replySettings, reply));
})
};
subscriptionManager = {
handleSubscriptionReply: jest.fn(),
handleMulticastPublication: jest.fn(),
handlePublication: jest.fn()
};
function sendSubscriptionReply(
_proxyParticipantId: string,
_providerParticipantId: string,
subscriptionRequest: any,
callbackDispatcher: any,
settings: any
) {
callbackDispatcher(
settings,
new SubscriptionReply({
subscriptionId: subscriptionRequest.subscriptionId
})
);
}
publicationManager = {
handleSubscriptionRequest: jest.fn().mockImplementation(sendSubscriptionReply),
handleBroadcastSubscriptionRequest: jest.fn().mockImplementation(sendSubscriptionReply),
handleMulticastSubscriptionRequest: jest.fn().mockImplementation(sendSubscriptionReply),
handleSubscriptionStop: jest.fn()
};
messageRouter = {
addMulticastReceiver: jest.fn().mockReturnValue(Promise.resolve()),
removeMulticastReceiver: jest.fn()
};
clusterControllerMessagingStub = {
transmit: jest.fn().mockReturnValue(Promise.resolve())
};
securityManager = {
getCurrentProcessUserId: jest.fn()
};
dispatcher = new Dispatcher(clusterControllerMessagingStub, securityManager, noTtlUplift);
dispatcher.registerRequestReplyManager(requestReplyManager);
dispatcher.registerSubscriptionManager(subscriptionManager);
dispatcher.registerPublicationManager(publicationManager);
dispatcher.registerMessageRouter(messageRouter);
dispatcherWithTtlUplift = new Dispatcher(clusterControllerMessagingStub, securityManager, ttlUpliftMs);
dispatcherWithTtlUplift.registerRequestReplyManager(requestReplyManager);
dispatcherWithTtlUplift.registerSubscriptionManager(subscriptionManager);
dispatcherWithTtlUplift.registerPublicationManager(publicationManager);
dispatcherWithTtlUplift.registerMessageRouter(messageRouter);
ttl = 300;
messagingQos = new MessagingQos({
ttl
});
publicationTtlMs = 1000;
expiryDateMs = Date.now() + ttl;
expiryDateWithTtlUplift = expiryDateMs + ttlUpliftMs;
subscriptionQos = {
expiryDateMs,
publicationTtlMs,
minIntervalMs: 0
};
});
describe("no ttl uplift (default)", () => {
it("send request", () => {
const settings = {
from: proxyId,
toDiscoveryEntry: providerDiscoveryEntry,
messagingQos,
request: "request"
};
dispatcher.sendRequest(settings as any);
checkMessageFromProxyWithTolerance(JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST, expiryDateMs);
});
it("send one way request", () => {
const settings = {
from: proxyId,
toDiscoveryEntry: providerDiscoveryEntry,
messagingQos,
request: "oneWayRequest"
};
dispatcher.sendOneWayRequest(settings as any);
checkMessageFromProxyWithTolerance(JoynrMessage.JOYNRMESSAGE_TYPE_ONE_WAY, expiryDateMs);
});
it("send subscription request", () => {
const settings = {
from: proxyId,
toDiscoveryEntry: providerDiscoveryEntry,
messagingQos,
subscriptionRequest: new SubscriptionRequest({
subscriptionId: "subscriptionId",
subscribedToName: "attributeName",
qos: subscriptionQos
})
};
dispatcher.sendSubscriptionRequest(settings);
checkMessageFromProxyWithTolerance(JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REQUEST, expiryDateMs);
});
it("send broadcast subscription request", () => {
const settings = {
from: proxyId,
toDiscoveryEntry: providerDiscoveryEntry,
messagingQos,
subscriptionRequest: new BroadcastSubscriptionRequest({
subscriptionId: "subscriptionId",
subscribedToName: "broadcastEvent",
qos: subscriptionQos
})
};
dispatcher.sendBroadcastSubscriptionRequest(settings);
checkMessageFromProxyWithTolerance(
JoynrMessage.JOYNRMESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST,
expiryDateMs
);
});
it("send multicast subscription stop", () => {
const settings = {
from: proxyId,
toDiscoveryEntry: providerDiscoveryEntry,
messagingQos,
multicastId: "multicastId",
subscriptionStop: new SubscriptionStop({
subscriptionId: "subscriptionId"
})
};
dispatcher.sendMulticastSubscriptionStop(settings);
checkMessageFromProxyWithTolerance(JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_STOP, expiryDateMs);
});
it("send subscription stop", () => {
const settings = {
from: proxyId,
toDiscoveryEntry: providerDiscoveryEntry,
messagingQos,
subscriptionStop: new SubscriptionStop({
subscriptionId: "subscriptionId"
})
};
dispatcher.sendSubscriptionStop(settings);
checkMessageFromProxyWithTolerance(JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_STOP, expiryDateMs);
});
it("send publication", () => {
const settings = {
from: proxyId,
to: providerId,
expiryDate: expiryDateMs
};
dispatcher.sendPublication(settings, "publication" as any);
checkMessageFromProxyWithTolerance(JoynrMessage.JOYNRMESSAGE_TYPE_PUBLICATION, expiryDateMs);
});
it("send multicast publication", () => {
const settings = {
from: providerId,
expiryDate: expiryDateMs
};
const multicastId = "multicastId";
const publication = MulticastPublication.create({
multicastId
});
dispatcher.sendMulticastPublication(settings, publication);
expect(clusterControllerMessagingStub.transmit).toHaveBeenCalled();
const msg = clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0];
expect(msg.type).toEqual(JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST);
expect(msg.from).toEqual(providerId);
expect(msg.to).toEqual(multicastId);
(expect(msg.expiryDate) as ExtendedMatchers).toEqualWithPositiveTolerance(expiryDateMs);
});
it("request and reply", async () => {
const payload = {
methodName: "methodName"
};
await receiveJoynrMessage({
type: JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST,
payload,
expiryDate: expiryDateMs
});
expect(requestReplyManager.handleRequest).toHaveBeenCalled();
expect(requestReplyManager.handleRequest).toHaveBeenCalledWith(
providerId,
expect.objectContaining({
_typeName: "joynr.Request"
}),
expect.any(Function),
expect.any(Object)
);
checkRequestReplyMessage(expiryDateMs);
});
it("subscription expiry date and subscription reply", () => {
// var expiryDateMs = Date.now() + 100000;
// var publicationTtlMs = 10000;
// var qos = {
// expiryDateMs : expiryDateMs,
// publicationTtlMs : publicationTtlMs,
// minIntervalMs : 0
// };
const payload = {
subscribedToName: "attributeName",
subscriptionId,
qos: subscriptionQos
};
const payloadCopy = UtilInternal.extendDeep({}, payload);
const expectedSubscriptionRequest = new SubscriptionRequest(payloadCopy as any);
receiveJoynrMessage({
type: JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REQUEST,
payload,
expiryDate: expiryDateMs
});
expect(publicationManager.handleSubscriptionRequest).toHaveBeenCalled();
expect(publicationManager.handleSubscriptionRequest).toHaveBeenCalledWith(
proxyId,
providerId,
expectedSubscriptionRequest,
expect.any(Function),
expect.any(Object)
);
checkSubscriptionReplyMessage(expiryDateMs);
});
it("broadcast subscription expiry date and subscription reply", () => {
const payload = {
subscribedToName: "broadcastEvent",
subscriptionId,
qos: subscriptionQos
};
const payloadCopy = UtilInternal.extendDeep({}, payload);
const expectedSubscriptionRequest = new BroadcastSubscriptionRequest(payloadCopy as any);
receiveJoynrMessage({
type: JoynrMessage.JOYNRMESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST,
payload,
expiryDate: expiryDateMs
});
expect(publicationManager.handleBroadcastSubscriptionRequest).toHaveBeenCalled();
expect(publicationManager.handleBroadcastSubscriptionRequest).toHaveBeenCalledWith(
proxyId,
providerId,
expectedSubscriptionRequest,
expect.any(Function),
expect.any(Object)
);
checkSubscriptionReplyMessage(expiryDateMs);
});
it("multicast subscription expiryDate and subscription reply", () => {
const payload = {
subscribedToName: "multicastEvent",
subscriptionId,
multicastId,
qos: subscriptionQos
};
const payloadCopy = UtilInternal.extendDeep({}, payload);
const expectedSubscriptionRequest = new MulticastSubscriptionRequest(payloadCopy as any);
receiveJoynrMessage({
type: JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST_SUBSCRIPTION_REQUEST,
payload,
expiryDate: expiryDateMs
});
expect(publicationManager.handleMulticastSubscriptionRequest).toHaveBeenCalled();
expect(publicationManager.handleMulticastSubscriptionRequest).toHaveBeenCalledWith(
proxyId,
providerId,
expectedSubscriptionRequest,
expect.any(Function),
expect.any(Object)
);
checkSubscriptionReplyMessage(expiryDateMs);
});
}); // describe "no ttl uplift (default)"
describe("with ttlUplift", () => {
it("send request", () => {
const settings = {
from: proxyId,
toDiscoveryEntry: providerDiscoveryEntry,
messagingQos,
request: "request"
};
dispatcherWithTtlUplift.sendRequest(settings);
checkMessageFromProxyWithTolerance(JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST, expiryDateWithTtlUplift);
});
it("send one way request", () => {
const settings = {
from: proxyId,
toDiscoveryEntry: providerDiscoveryEntry,
messagingQos,
request: "oneWayRequest"
};
dispatcherWithTtlUplift.sendOneWayRequest(settings);
checkMessageFromProxyWithTolerance(JoynrMessage.JOYNRMESSAGE_TYPE_ONE_WAY, expiryDateWithTtlUplift);
});
it("send subscription request", () => {
const settings = {
from: proxyId,
toDiscoveryEntry: providerDiscoveryEntry,
messagingQos,
subscriptionRequest: new SubscriptionRequest({
subscriptionId: "subscriptionId",
subscribedToName: "attributeName",
qos: subscriptionQos
})
};
dispatcherWithTtlUplift.sendSubscriptionRequest(settings);
checkMessageFromProxyWithTolerance(
JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REQUEST,
expiryDateWithTtlUplift
);
});
it("send broadcast subscription request", () => {
const settings = {
from: proxyId,
toDiscoveryEntry: providerDiscoveryEntry,
messagingQos,
subscriptionRequest: new BroadcastSubscriptionRequest({
subscriptionId: "subscriptionId",
subscribedToName: "broadcastEvent",
qos: subscriptionQos
})
};
dispatcherWithTtlUplift.sendBroadcastSubscriptionRequest(settings);
checkMessageFromProxyWithTolerance(
JoynrMessage.JOYNRMESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST,
expiryDateWithTtlUplift
);
});
it("send multicast subscription stop", () => {
const settings = {
from: proxyId,
toDiscoveryEntry: providerDiscoveryEntry,
messagingQos,
multicastId: "multicastId",
subscriptionStop: new SubscriptionStop({
subscriptionId: "subscriptionId"
})
};
dispatcherWithTtlUplift.sendMulticastSubscriptionStop(settings);
checkMessageFromProxyWithTolerance(
JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_STOP,
expiryDateWithTtlUplift
);
});
it("send subscription stop", () => {
const settings = {
from: proxyId,
toDiscoveryEntry: providerDiscoveryEntry,
messagingQos,
subscriptionStop: new SubscriptionStop({
subscriptionId: "subscriptionId"
})
};
dispatcherWithTtlUplift.sendSubscriptionStop(settings);
checkMessageFromProxyWithTolerance(
JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_STOP,
expiryDateWithTtlUplift
);
});
it("send publication", () => {
const settings = {
from: proxyId,
to: providerId,
expiryDate: expiryDateMs
};
dispatcherWithTtlUplift.sendPublication(settings, "publication");
checkMessageFromProxyWithTolerance(JoynrMessage.JOYNRMESSAGE_TYPE_PUBLICATION, expiryDateWithTtlUplift);
});
it("send multicast publication", () => {
const settings = {
from: providerId,
expiryDate: expiryDateMs
};
const multicastId = "multicastId";
const publication = MulticastPublication.create({
multicastId
});
dispatcherWithTtlUplift.sendMulticastPublication(settings, publication);
expect(clusterControllerMessagingStub.transmit).toHaveBeenCalled();
const msg = clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0];
expect(msg.type).toEqual(JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST);
expect(msg.from).toEqual(providerId);
expect(msg.to).toEqual(multicastId);
(expect(msg.expiryDate) as ExtendedMatchers).toEqualWithPositiveTolerance(expiryDateWithTtlUplift);
});
it("request and reply", async () => {
const payload = {
methodName: "methodName"
};
await receiveJoynrMessageTtlUplift({
type: JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST,
payload,
expiryDate: expiryDateMs + ttlUpliftMs
});
expect(requestReplyManager.handleRequest).toHaveBeenCalled();
expect(requestReplyManager.handleRequest).toHaveBeenCalledWith(
providerId,
expect.objectContaining({
_typeName: "joynr.Request"
}),
expect.any(Function),
expect.any(Object)
);
checkRequestReplyMessage(expiryDateWithTtlUplift);
});
it("subscription expiry date and subscription reply", () => {
const payload = {
subscribedToName: "attributeName",
subscriptionId,
qos: subscriptionQos
};
const payloadCopy = UtilInternal.extendDeep({}, payload);
const expectedSubscriptionRequest = new SubscriptionRequest(payloadCopy as any);
expectedSubscriptionRequest.qos.expiryDateMs = expiryDateWithTtlUplift;
receiveJoynrMessageTtlUplift({
type: JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REQUEST,
payload,
expiryDate: expiryDateMs + ttlUpliftMs
});
expect(publicationManager.handleSubscriptionRequest).toHaveBeenCalled();
expect(publicationManager.handleSubscriptionRequest).toHaveBeenCalledWith(
proxyId,
providerId,
expectedSubscriptionRequest,
expect.any(Function),
expect.any(Object)
);
checkSubscriptionReplyMessage(expiryDateWithTtlUplift);
});
it("broadcast subscription expiry date and subscription reply", () => {
const payload = {
subscribedToName: "broadcastEvent",
subscriptionId,
qos: subscriptionQos
};
const payloadCopy = UtilInternal.extendDeep({}, payload);
const expectedSubscriptionRequest = new BroadcastSubscriptionRequest(payloadCopy as any);
expectedSubscriptionRequest.qos.expiryDateMs = expiryDateWithTtlUplift;
receiveJoynrMessageTtlUplift({
type: JoynrMessage.JOYNRMESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST,
payload,
expiryDate: expiryDateMs + ttlUpliftMs
});
expect(publicationManager.handleBroadcastSubscriptionRequest).toHaveBeenCalled();
expect(publicationManager.handleBroadcastSubscriptionRequest).toHaveBeenCalledWith(
proxyId,
providerId,
expectedSubscriptionRequest,
expect.any(Function),
expect.any(Object)
);
checkSubscriptionReplyMessage(expiryDateWithTtlUplift);
});
it("multicast subscription expiry date and subscription reply", () => {
const payload = {
subscribedToName: "multicastEvent",
subscriptionId,
multicastId,
qos: subscriptionQos
};
const payloadCopy = UtilInternal.extendDeep({}, payload);
const expectedSubscriptionRequest = new MulticastSubscriptionRequest(payloadCopy as any);
expectedSubscriptionRequest.qos.expiryDateMs = expiryDateWithTtlUplift;
receiveJoynrMessageTtlUplift({
type: JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST_SUBSCRIPTION_REQUEST,
payload,
expiryDate: expiryDateMs + ttlUpliftMs
});
expect(publicationManager.handleMulticastSubscriptionRequest).toHaveBeenCalled();
expect(publicationManager.handleMulticastSubscriptionRequest).toHaveBeenCalledWith(
proxyId,
providerId,
expectedSubscriptionRequest,
expect.any(Function),
expect.any(Object)
);
checkSubscriptionReplyMessage(expiryDateWithTtlUplift);
});
}); // describe "with ttlUplift"
}); // describe ttlUpliftTest | the_stack |
import { Knex } from 'knex'
import { Macroable } from 'macroable'
import { Exception } from '@poppinss/utils'
import { ChainableContract, DBQueryCallback } from '@ioc:Adonis/Lucid/Database'
import { isObject } from '../../utils'
import { RawQueryBuilder } from './Raw'
import { RawBuilder } from '../StaticBuilder/Raw'
import { ReferenceBuilder } from '../StaticBuilder/Reference'
const WRAPPING_METHODS = ['where', 'orWhere', 'whereNot', 'orWhereNot']
/**
* The chainable query builder to consturct SQL queries for selecting, updating and
* deleting records.
*
* The API internally uses the knex query builder. However, many of methods may have
* different API.
*/
export abstract class Chainable extends Macroable implements ChainableContract {
public hasAggregates: boolean = false
public hasGroupBy: boolean = false
public hasUnion: boolean = false
/**
* Collection where clauses in a 2nd array. Calling `wrapExisting`
* adds a new stack item
*/
private whereStack: any[][] = [[]]
/**
* Returns the recent most array from the where stack
*/
private getRecentStackItem() {
return this.whereStack[this.whereStack.length - 1]
}
/**
* Returns the wrapping method for a given where method
*/
private getWrappingMethod(method: string) {
if (WRAPPING_METHODS.includes(method)) {
return {
method: 'where',
wrappingMethod: method,
}
}
if (method.startsWith('or')) {
return {
method: method,
wrappingMethod: 'orWhere',
}
}
return {
method: method,
wrappingMethod: 'where',
}
}
/**
* Applies the where clauses
*/
protected applyWhere() {
this.knexQuery.clearWhere()
if (this.whereStack.length === 1) {
this.whereStack[0].forEach(({ method, args }) => {
this.knexQuery[method](...args)
})
return
}
this.whereStack.forEach((collection) => {
const firstItem = collection.shift()
const wrapper = this.getWrappingMethod(firstItem.method)
this.knexQuery[wrapper.wrappingMethod]((subquery) => {
subquery[wrapper.method](...firstItem.args)
collection.forEach(({ method, args }) => subquery[method](...args))
})
})
}
/**
* An array of selected columns
*/
public get columns(): ChainableContract['columns'] {
return this.knexQuery['_statements']
.filter(({ grouping }) => grouping === 'columns')
.reduce((result: ChainableContract['columns'], { value }) => {
result = result.concat(value)
return result
}, [])
}
/**
* Custom alias for the query results. Ignored if it not a
* subquery
*/
public subQueryAlias?: string
constructor(
public knexQuery: Knex.QueryBuilder,
private queryCallback: DBQueryCallback,
public keysResolver?: (columnName: string) => string
) {
super()
}
/**
* Raises exception when only one argument is passed to a where
* clause and it is a string. It means the value is undefined
*/
private validateWhereSingleArgument(value: any, method: string) {
if (typeof value === 'string') {
throw new Exception(`".${method}" expects value to be defined, but undefined is passed`)
}
}
/**
* Returns the value pair for the `whereBetween` clause
*/
private getBetweenPair(value: any[]): any {
const [lhs, rhs] = value
if (lhs === undefined || rhs === undefined) {
throw new Error('Invalid array for whereBetween value')
}
return [this.transformValue(lhs), this.transformValue(rhs)]
}
/**
* Normalizes the columns aggregates functions to something
* knex can process.
*/
private normalizeAggregateColumns(columns: any, alias?: any): any {
if (columns.constructor === Object) {
return Object.keys(columns).reduce((result, key) => {
const value = columns[key]
result[key] =
typeof value === 'string' ? this.resolveKey(value) : this.transformValue(value)
return result
}, {})
}
if (!alias) {
return columns
}
return {
[alias]:
typeof columns === 'string' ? this.resolveKey(columns) : this.transformValue(columns),
}
}
/**
* Resolves the column name considering raw queries as well.
*/
private resolveColumn(columns: any, checkForObject: boolean = false, returnValue?: any) {
if (columns instanceof RawQueryBuilder) {
return columns['knexQuery']
}
if (columns instanceof RawBuilder) {
return columns.toKnex(this.knexQuery.client)
}
return this.resolveKey(columns, checkForObject, returnValue)
}
/**
* Resolves column names
*/
protected resolveKey(columns: any, checkForObject: boolean = false, returnValue?: any): any {
/**
* If there is no keys resolver in place, then return the
* optional return value or defined column(s)
*/
if (!this.keysResolver) {
return returnValue || columns
}
/**
* If column is a string, then resolve it as a key
*/
if (typeof columns === 'string') {
return columns === '*' ? columns : this.keysResolver(columns)
}
/**
* If check for objects is enabled, then resolve object keys
*/
if (checkForObject && isObject(columns)) {
return Object.keys(columns).reduce((result, column) => {
result[this.keysResolver!(column)] = columns[column]
return result
}, {})
}
/**
* Return the return value or columns as fallback
*/
return returnValue || columns
}
/**
* Apply existing query flags to a new query builder. This is
* done during clone operation
*/
protected applyQueryFlags(query: Chainable) {
query.hasAggregates = this.hasAggregates
query.hasGroupBy = this.hasGroupBy
query.hasUnion = this.hasUnion
query.whereStack = this.whereStack.map((collection) => {
return collection.map((node) => node)
})
}
/**
* Transforms the value to something that knex can internally understand and
* handle. It includes.
*
* 1. Returning the `knexBuilder` for sub queries.
* 2. Returning the `knex.refBuilder` for reference builder.
* 2. Returning the `knexBuilder` for raw queries.
* 3. Wrapping callbacks, so that the end user receives an instance Lucid query
* builder and not knex query builder.
*/
protected transformValue(value: any) {
if (value instanceof Chainable) {
value.applyWhere()
return value.knexQuery
}
if (value instanceof ReferenceBuilder) {
return value.toKnex(this.knexQuery.client)
}
if (typeof value === 'function') {
return this.transformCallback(value)
}
return this.transformRaw(value)
}
/**
* Transforms the user callback to something that knex
* can internally process
*/
protected transformCallback(value: any) {
if (typeof value === 'function') {
return this.queryCallback(value, this.keysResolver)
}
return value
}
/**
* Returns the underlying knex raw query builder for Lucid raw
* query builder
*/
protected transformRaw(value: any) {
if (value instanceof RawQueryBuilder) {
return value['knexQuery']
}
if (value instanceof RawBuilder) {
return value.toKnex(this.knexQuery.client)
}
return value
}
/**
* Define columns for selection
*/
public select(...args: any[]): this {
let columns = args
if (Array.isArray(args[0])) {
columns = args[0]
}
this.knexQuery.select(
columns.map((column) => {
if (typeof column === 'string') {
return this.resolveKey(column, true)
}
return this.transformValue(column)
})
)
return this
}
/**
* Select table for the query. Re-calling this method multiple times will
* use the last selected table
*/
public from(table: any): this {
this.knexQuery.from(this.transformValue(table))
return this
}
/**
* Wrap existing where clauses to its own group
*/
public wrapExisting(): this {
if (this.getRecentStackItem().length) {
this.whereStack.push([])
}
return this
}
/**
* Add a `where` clause
*/
public where(key: any, operator?: any, value?: any): this {
const whereClauses = this.getRecentStackItem()
if (value !== undefined) {
whereClauses.push({
method: 'where',
args: [this.resolveColumn(key), operator, this.transformValue(value)],
})
} else if (operator !== undefined) {
whereClauses.push({
method: 'where',
args: [this.resolveColumn(key), this.transformValue(operator)],
})
} else {
/**
* Only callback is allowed as a standalone param. One must use `whereRaw`
* for raw/sub queries. This is our limitation to have consistent API
*/
this.validateWhereSingleArgument(key, 'where')
whereClauses.push({
method: 'where',
args: [this.resolveColumn(key, true, this.transformCallback(key))],
})
}
return this
}
/**
* Add a `or where` clause
*/
public orWhere(key: any, operator?: any, value?: any): this {
const whereClauses = this.getRecentStackItem()
if (value !== undefined) {
whereClauses.push({
method: 'orWhere',
args: [this.resolveColumn(key), operator, this.transformValue(value)],
})
} else if (operator !== undefined) {
whereClauses.push({
method: 'orWhere',
args: [this.resolveColumn(key), this.transformValue(operator)],
})
} else {
this.validateWhereSingleArgument(key, 'orWhere')
whereClauses.push({
method: 'orWhere',
args: [this.resolveColumn(key, true, this.transformCallback(key))],
})
}
return this
}
/**
* Alias for `where`
*/
public andWhere(key: any, operator?: any, value?: any): this {
return this.where(key, operator, value)
}
/**
* Adding `where not` clause
*/
public whereNot(key: any, operator?: any, value?: any): this {
const whereClauses = this.getRecentStackItem()
if (value !== undefined) {
whereClauses.push({
method: 'whereNot',
args: [this.resolveColumn(key), operator, this.transformValue(value)],
})
} else if (operator !== undefined) {
whereClauses.push({
method: 'whereNot',
args: [this.resolveColumn(key), this.transformValue(operator)],
})
} else {
this.validateWhereSingleArgument(key, 'whereNot')
whereClauses.push({
method: 'whereNot',
args: [this.resolveColumn(key, true, this.transformCallback(key))],
})
}
return this
}
/**
* Adding `or where not` clause
*/
public orWhereNot(key: any, operator?: any, value?: any): this {
const whereClauses = this.getRecentStackItem()
if (value !== undefined) {
whereClauses.push({
method: 'orWhereNot',
args: [this.resolveColumn(key), operator, this.transformValue(value)],
})
} else if (operator !== undefined) {
whereClauses.push({
method: 'orWhereNot',
args: [this.resolveColumn(key), this.transformValue(operator)],
})
} else {
this.validateWhereSingleArgument(key, 'orWhereNot')
whereClauses.push({
method: 'orWhereNot',
args: [this.resolveColumn(key, true, this.transformCallback(key))],
})
}
return this
}
/**
* Alias for [[whereNot]]
*/
public andWhereNot(key: any, operator?: any, value?: any): this {
return this.whereNot(key, operator, value)
}
/**
* Add a where clause on a given column
*/
public whereColumn(column: any, operator: any, comparisonColumn?: any): this {
if (comparisonColumn !== undefined) {
this.where(column, operator, new ReferenceBuilder(comparisonColumn, this.knexQuery.client))
} else {
this.where(column, new ReferenceBuilder(operator, this.knexQuery.client))
}
return this
}
/**
* Add a orWhere clause on a given column
*/
public orWhereColumn(column: any, operator: any, comparisonColumn?: any): this {
if (comparisonColumn !== undefined) {
this.orWhere(column, operator, new ReferenceBuilder(comparisonColumn, this.knexQuery.client))
} else {
this.orWhere(column, new ReferenceBuilder(operator, this.knexQuery.client))
}
return this
}
/**
* Alias for whereColumn
*/
public andWhereColumn(column: any, operator: any, comparisonColumn?: any): this {
return this.whereColumn(column, operator, comparisonColumn)
}
/**
* Add a whereNot clause on a given column
*/
public whereNotColumn(column: any, operator: any, comparisonColumn?: any): this {
if (comparisonColumn !== undefined) {
this.whereNot(column, operator, new ReferenceBuilder(comparisonColumn, this.knexQuery.client))
} else {
this.whereNot(column, new ReferenceBuilder(operator, this.knexQuery.client))
}
return this
}
/**
* Add a orWhereNotColumn clause on a given column
*/
public orWhereNotColumn(column: any, operator: any, comparisonColumn?: any): this {
if (comparisonColumn !== undefined) {
this.orWhereNot(
column,
operator,
new ReferenceBuilder(comparisonColumn, this.knexQuery.client)
)
} else {
this.orWhereNot(column, new ReferenceBuilder(operator, this.knexQuery.client))
}
return this
}
/**
* Alias for whereNotColumn
*/
public andWhereNotColumn(column: any, operator: any, comparisonColumn?: any): this {
return this.whereNotColumn(column, operator, comparisonColumn)
}
/**
* Adding a `where in` clause
*/
public whereIn(columns: any, value: any): this {
value = Array.isArray(value)
? value.map((one) => this.transformValue(one))
: this.transformValue(value)
columns = Array.isArray(columns)
? columns.map((column) => this.resolveColumn(column))
: this.resolveColumn(columns)
const whereClauses = this.getRecentStackItem()
whereClauses.push({
method: 'whereIn',
args: [columns, value],
})
return this
}
/**
* Adding a `or where in` clause
*/
public orWhereIn(columns: any, value: any): this {
value = Array.isArray(value)
? value.map((one) => this.transformValue(one))
: this.transformValue(value)
columns = Array.isArray(columns)
? columns.map((column) => this.resolveColumn(column))
: this.resolveColumn(columns)
const whereClauses = this.getRecentStackItem()
whereClauses.push({
method: 'orWhereIn',
args: [columns, value],
})
return this
}
/**
* Alias for [[whereIn]]
*/
public andWhereIn(key: any, value: any): this {
return this.whereIn(key, value)
}
/**
* Adding a `where not in` clause
*/
public whereNotIn(columns: any, value: any): this {
value = Array.isArray(value)
? value.map((one) => this.transformValue(one))
: this.transformValue(value)
columns = Array.isArray(columns)
? columns.map((column) => this.resolveColumn(column))
: this.resolveColumn(columns)
const whereClauses = this.getRecentStackItem()
whereClauses.push({
method: 'whereNotIn',
args: [columns, value],
})
return this
}
/**
* Adding a `or where not in` clause
*/
public orWhereNotIn(columns: any, value: any): this {
value = Array.isArray(value)
? value.map((one) => this.transformValue(one))
: this.transformValue(value)
columns = Array.isArray(columns)
? columns.map((column) => this.resolveColumn(column))
: this.resolveColumn(columns)
const whereClauses = this.getRecentStackItem()
whereClauses.push({
method: 'orWhereNotIn',
args: [columns, value],
})
return this
}
/**
* Alias for [[whereNotIn]]
*/
public andWhereNotIn(key: any, value: any): this {
return this.whereNotIn(key, value)
}
/**
* Adding `where not null` clause
*/
public whereNull(key: any): this {
const whereClauses = this.getRecentStackItem()
whereClauses.push({
method: 'whereNull',
args: [this.resolveColumn(key)],
})
return this
}
/**
* Adding `or where not null` clause
*/
public orWhereNull(key: any): this {
const whereClauses = this.getRecentStackItem()
whereClauses.push({
method: 'orWhereNull',
args: [this.resolveColumn(key)],
})
return this
}
/**
* Alias for [[whereNull]]
*/
public andWhereNull(key: any): this {
return this.whereNull(key)
}
/**
* Adding `where not null` clause
*/
public whereNotNull(key: any): this {
const whereClauses = this.getRecentStackItem()
whereClauses.push({
method: 'whereNotNull',
args: [this.resolveColumn(key)],
})
return this
}
/**
* Adding `or where not null` clause
*/
public orWhereNotNull(key: any): this {
const whereClauses = this.getRecentStackItem()
whereClauses.push({
method: 'orWhereNotNull',
args: [this.resolveColumn(key)],
})
return this
}
/**
* Alias for [[whereNotNull]]
*/
public andWhereNotNull(key: any): this {
return this.whereNotNull(key)
}
/**
* Add a `where exists` clause
*/
public whereExists(value: any) {
const whereClauses = this.getRecentStackItem()
whereClauses.push({
method: 'whereExists',
args: [this.transformValue(value)],
})
return this
}
/**
* Add a `or where exists` clause
*/
public orWhereExists(value: any) {
const whereClauses = this.getRecentStackItem()
whereClauses.push({
method: 'orWhereExists',
args: [this.transformValue(value)],
})
return this
}
/**
* Alias for [[whereExists]]
*/
public andWhereExists(value: any) {
return this.whereExists(value)
}
/**
* Add a `where not exists` clause
*/
public whereNotExists(value: any) {
const whereClauses = this.getRecentStackItem()
whereClauses.push({
method: 'whereNotExists',
args: [this.transformValue(value)],
})
return this
}
/**
* Add a `or where not exists` clause
*/
public orWhereNotExists(value: any) {
const whereClauses = this.getRecentStackItem()
whereClauses.push({
method: 'orWhereNotExists',
args: [this.transformValue(value)],
})
return this
}
/**
* Alias for [[whereNotExists]]
*/
public andWhereNotExists(value: any) {
return this.whereNotExists(value)
}
/**
* Add where between clause
*/
public whereBetween(key: any, value: [any, any]): this {
const whereClauses = this.getRecentStackItem()
whereClauses.push({
method: 'whereBetween',
args: [this.resolveColumn(key), this.getBetweenPair(value)],
})
return this
}
/**
* Add where between clause
*/
public orWhereBetween(key: any, value: any): this {
const whereClauses = this.getRecentStackItem()
whereClauses.push({
method: 'orWhereBetween',
args: [this.resolveColumn(key), this.getBetweenPair(value)],
})
return this
}
/**
* Alias for [[whereBetween]]
*/
public andWhereBetween(key: any, value: any): this {
return this.whereBetween(key, value)
}
/**
* Add where between clause
*/
public whereNotBetween(key: any, value: any): this {
const whereClauses = this.getRecentStackItem()
whereClauses.push({
method: 'whereNotBetween',
args: [this.resolveColumn(key), this.getBetweenPair(value)],
})
return this
}
/**
* Add where between clause
*/
public orWhereNotBetween(key: any, value: any): this {
const whereClauses = this.getRecentStackItem()
whereClauses.push({
method: 'orWhereNotBetween',
args: [this.resolveColumn(key), this.getBetweenPair(value)],
})
return this
}
/**
* Alias for [[whereNotBetween]]
*/
public andWhereNotBetween(key: any, value: any): this {
return this.whereNotBetween(key, value)
}
/**
* Adding a where clause using raw sql
*/
public whereRaw(sql: any, bindings?: any): this {
const whereClauses = this.getRecentStackItem()
if (bindings) {
bindings = Array.isArray(bindings)
? bindings.map((binding) => this.transformValue(binding))
: bindings
whereClauses.push({
method: 'whereRaw',
args: [sql, bindings],
})
} else {
whereClauses.push({
method: 'whereRaw',
args: [this.transformRaw(sql)],
})
}
return this
}
/**
* Adding a or where clause using raw sql
*/
public orWhereRaw(sql: any, bindings?: any): this {
const whereClauses = this.getRecentStackItem()
if (bindings) {
bindings = Array.isArray(bindings)
? bindings.map((binding) => this.transformValue(binding))
: bindings
whereClauses.push({
method: 'orWhereRaw',
args: [sql, bindings],
})
} else {
whereClauses.push({
method: 'orWhereRaw',
args: [this.transformRaw(sql)],
})
}
return this
}
/**
* Alias for [[whereRaw]]
*/
public andWhereRaw(sql: any, bindings?: any): this {
return this.whereRaw(sql, bindings)
}
/**
* Add a join clause
*/
public join(table: any, first: any, operator?: any, second?: any): this {
if (second !== undefined) {
this.knexQuery.join(table, first, operator, this.transformRaw(second))
} else if (operator !== undefined) {
this.knexQuery.join(table, first, this.transformRaw(operator))
} else {
this.knexQuery.join(table, this.transformRaw(first))
}
return this
}
/**
* Add an inner join clause
*/
public innerJoin(table: any, first: any, operator?: any, second?: any): this {
if (second !== undefined) {
this.knexQuery.innerJoin(table, first, operator, this.transformRaw(second))
} else if (operator !== undefined) {
this.knexQuery.innerJoin(table, first, this.transformRaw(operator))
} else {
this.knexQuery.innerJoin(table, this.transformRaw(first))
}
return this
}
/**
* Add a left join clause
*/
public leftJoin(table: any, first: any, operator?: any, second?: any): this {
if (second !== undefined) {
this.knexQuery.leftJoin(table, first, operator, this.transformRaw(second))
} else if (operator !== undefined) {
this.knexQuery.leftJoin(table, first, this.transformRaw(operator))
} else {
this.knexQuery.leftJoin(table, this.transformRaw(first))
}
return this
}
/**
* Add a left outer join clause
*/
public leftOuterJoin(table: any, first: any, operator?: any, second?: any): this {
if (second !== undefined) {
this.knexQuery.leftOuterJoin(table, first, operator, this.transformRaw(second))
} else if (operator !== undefined) {
this.knexQuery.leftOuterJoin(table, first, this.transformRaw(operator))
} else {
this.knexQuery.leftOuterJoin(table, this.transformRaw(first))
}
return this
}
/**
* Add a right join clause
*/
public rightJoin(table: any, first: any, operator?: any, second?: any): this {
if (second !== undefined) {
this.knexQuery.rightJoin(table, first, operator, this.transformRaw(second))
} else if (operator !== undefined) {
this.knexQuery.rightJoin(table, first, this.transformRaw(operator))
} else {
this.knexQuery.rightJoin(table, this.transformRaw(first))
}
return this
}
/**
* Add a right outer join clause
*/
public rightOuterJoin(table: any, first: any, operator?: any, second?: any): this {
if (second !== undefined) {
this.knexQuery.rightOuterJoin(table, first, operator, this.transformRaw(second))
} else if (operator !== undefined) {
this.knexQuery.rightOuterJoin(table, first, this.transformRaw(operator))
} else {
this.knexQuery.rightOuterJoin(table, this.transformRaw(first))
}
return this
}
/**
* Add a full outer join clause
*/
public fullOuterJoin(table: any, first: any, operator?: any, second?: any): this {
if (second !== undefined) {
this.knexQuery.fullOuterJoin(table, first, operator, this.transformRaw(second))
} else if (operator !== undefined) {
this.knexQuery.fullOuterJoin(table, first, this.transformRaw(operator))
} else {
this.knexQuery.fullOuterJoin(table, this.transformRaw(first))
}
return this
}
/**
* Add a cross join clause
*/
public crossJoin(table: any, first: any, operator?: any, second?: any): this {
if (second !== undefined) {
this.knexQuery.crossJoin(table, first, operator, this.transformRaw(second))
} else if (operator !== undefined) {
this.knexQuery.crossJoin(table, first, this.transformRaw(operator))
} else {
this.knexQuery.crossJoin(table, this.transformRaw(first))
}
return this
}
/**
* Add join clause as a raw query
*/
public joinRaw(sql: any, bindings?: any) {
if (bindings) {
this.knexQuery.joinRaw(sql, bindings)
} else {
this.knexQuery.joinRaw(this.transformRaw(sql))
}
return this
}
/**
* Adds a having clause. The having clause breaks for `postgreSQL` when
* referencing alias columns, since PG doesn't support alias columns
* being referred within `having` clause. The end user has to
* use raw queries in this case.
*/
public having(key: any, operator?: any, value?: any): this {
if (value !== undefined) {
this.knexQuery.having(this.resolveColumn(key), operator, this.transformValue(value))
return this
}
if (operator !== undefined) {
throw new Exception(
'Invalid arguments for "queryBuilder.having". Excepts a callback or key-value pair along with an operator'
)
}
this.knexQuery.having(this.transformValue(key))
return this
}
/**
* Adds or having clause. The having clause breaks for `postgreSQL` when
* referencing alias columns, since PG doesn't support alias columns
* being referred within `having` clause. The end user has to
* use raw queries in this case.
*/
public orHaving(key: any, operator?: any, value?: any): this {
if (value !== undefined) {
this.knexQuery.orHaving(this.resolveColumn(key), operator, this.transformValue(value))
return this
}
if (operator !== undefined) {
throw new Exception(
'Invalid arguments for "queryBuilder.orHaving". Excepts a callback or key-value pair along with an operator'
)
}
this.knexQuery.orHaving(this.transformValue(key))
return this
}
/**
* Alias for [[having]]
*/
public andHaving(key: any, operator?: any, value?: any): this {
return this.having(key, operator, value)
}
/**
* Adding having in clause to the query
*/
public havingIn(key: any, value: any): this {
value = Array.isArray(value)
? value.map((one) => this.transformValue(one))
: this.transformValue(value)
this.knexQuery.havingIn(this.resolveColumn(key), value)
return this
}
/**
* Adding or having in clause to the query
*/
public orHavingIn(key: any, value: any): this {
value = Array.isArray(value)
? value.map((one) => this.transformValue(one))
: this.transformValue(value)
this.knexQuery['orHavingIn'](this.resolveColumn(key), value)
return this
}
/**
* Alias for [[havingIn]]
*/
public andHavingIn(key: any, value: any) {
return this.havingIn(key, value)
}
/**
* Adding having not in clause to the query
*/
public havingNotIn(key: any, value: any): this {
value = Array.isArray(value)
? value.map((one) => this.transformValue(one))
: this.transformValue(value)
this.knexQuery['havingNotIn'](this.resolveColumn(key), value)
return this
}
/**
* Adding or having not in clause to the query
*/
public orHavingNotIn(key: any, value: any): this {
value = Array.isArray(value)
? value.map((one) => this.transformValue(one))
: this.transformValue(value)
this.knexQuery['orHavingNotIn'](this.resolveColumn(key), value)
return this
}
/**
* Alias for [[havingNotIn]]
*/
public andHavingNotIn(key: any, value: any) {
return this.havingNotIn(key, value)
}
/**
* Adding having null clause
*/
public havingNull(key: any): this {
this.knexQuery['havingNull'](this.resolveColumn(key))
return this
}
/**
* Adding or having null clause
*/
public orHavingNull(key: any): this {
this.knexQuery['orHavingNull'](this.resolveColumn(key))
return this
}
/**
* Alias for [[havingNull]] clause
*/
public andHavingNull(key: any): this {
return this.havingNull(key)
}
/**
* Adding having not null clause
*/
public havingNotNull(key: any): this {
this.knexQuery['havingNotNull'](this.resolveColumn(key))
return this
}
/**
* Adding or having not null clause
*/
public orHavingNotNull(key: any): this {
this.knexQuery['orHavingNotNull'](this.resolveColumn(key))
return this
}
/**
* Alias for [[havingNotNull]] clause
*/
public andHavingNotNull(key: any): this {
return this.havingNotNull(key)
}
/**
* Adding `having exists` clause
*/
public havingExists(value: any): this {
this.knexQuery['havingExists'](this.transformValue(value))
return this
}
/**
* Adding `or having exists` clause
*/
public orHavingExists(value: any): this {
this.knexQuery['orHavingExists'](this.transformValue(value))
return this
}
/**
* Alias for [[havingExists]]
*/
public andHavingExists(value: any): this {
return this.havingExists(value)
}
/**
* Adding `having not exists` clause
*/
public havingNotExists(value: any): this {
this.knexQuery['havingNotExists'](this.transformValue(value))
return this
}
/**
* Adding `or having not exists` clause
*/
public orHavingNotExists(value: any): this {
this.knexQuery['orHavingNotExists'](this.transformValue(value))
return this
}
/**
* Alias for [[havingNotExists]]
*/
public andHavingNotExists(value: any): this {
return this.havingNotExists(value)
}
/**
* Adding `having between` clause
*/
public havingBetween(key: any, value: any): this {
this.knexQuery.havingBetween(this.resolveColumn(key), this.getBetweenPair(value))
return this
}
/**
* Adding `or having between` clause
*/
public orHavingBetween(key: any, value: any): this {
this.knexQuery.orHavingBetween(this.resolveColumn(key), this.getBetweenPair(value))
return this
}
/**
* Alias for [[havingBetween]]
*/
public andHavingBetween(key: any, value: any): this {
return this.havingBetween(this.resolveColumn(key), value)
}
/**
* Adding `having not between` clause
*/
public havingNotBetween(key: any, value: any): this {
this.knexQuery.havingNotBetween(this.resolveColumn(key), this.getBetweenPair(value))
return this
}
/**
* Adding `or having not between` clause
*/
public orHavingNotBetween(key: any, value: any): this {
this.knexQuery.orHavingNotBetween(this.resolveColumn(key), this.getBetweenPair(value))
return this
}
/**
* Alias for [[havingNotBetween]]
*/
public andHavingNotBetween(key: any, value: any): this {
return this.havingNotBetween(key, value)
}
/**
* Adding a where clause using raw sql
*/
public havingRaw(sql: any, bindings?: any): this {
if (bindings) {
this.knexQuery.havingRaw(sql, bindings)
} else {
this.knexQuery.havingRaw(this.transformRaw(sql))
}
return this
}
/**
* Adding a where clause using raw sql
*/
public orHavingRaw(sql: any, bindings?: any): this {
if (bindings) {
this.knexQuery.orHavingRaw(sql, bindings)
} else {
this.knexQuery.orHavingRaw(this.transformRaw(sql))
}
return this
}
/**
* Alias for [[havingRaw]]
*/
public andHavingRaw(sql: any, bindings?: any): this {
return this.havingRaw(sql, bindings)
}
/**
* Add distinct clause
*/
public distinct(...columns: any[]): this {
this.knexQuery.distinct(...columns.map((column) => this.resolveKey(column)))
return this
}
/**
* Add distinctOn clause
*/
public distinctOn(...columns: any[]): this {
this.knexQuery.distinctOn(...columns.map((column) => this.resolveKey(column)))
return this
}
/**
* Add group by clause
*/
public groupBy(...columns: any[]): this {
this.hasGroupBy = true
this.knexQuery.groupBy(...columns.map((column) => this.resolveKey(column)))
return this
}
/**
* Add group by clause as a raw query
*/
public groupByRaw(sql: any, bindings?: any): this {
this.hasGroupBy = true
if (bindings) {
this.knexQuery.groupByRaw(sql, bindings)
} else {
this.knexQuery.groupByRaw(this.transformRaw(sql))
}
return this
}
/**
* Add order by clause
*/
public orderBy(column: any, direction?: any): this {
if (typeof column === 'string') {
this.knexQuery.orderBy(this.resolveKey(column), direction)
return this
}
/**
* Here value can be one of the following
* ['age', 'name']
* [{ column: 'age', direction: 'desc' }]
*
* [{ column: Database.query().from('user_logins'), direction: 'desc' }]
*/
if (Array.isArray(column)) {
const transformedColumns = column.map((col) => {
if (typeof col === 'string') {
return { column: this.resolveKey(col) }
}
if (col.column) {
col.column =
typeof col.column === 'string'
? this.resolveKey(col.column)
: this.transformValue(col.column)
return col
}
return col
})
this.knexQuery.orderBy(transformedColumns)
return this
}
this.knexQuery.orderBy(this.transformValue(column), direction)
return this
}
/**
* Add order by clause as a raw query
*/
public orderByRaw(sql: any, bindings?: any): this {
if (bindings) {
this.knexQuery.orderByRaw(sql, bindings)
} else {
this.knexQuery.orderByRaw(this.transformRaw(sql))
}
return this
}
/**
* Define select offset
*/
public offset(value: number): this {
this.knexQuery.offset(value)
return this
}
/**
* Define results limit
*/
public limit(value: number): this {
this.knexQuery.limit(value)
return this
}
/**
* Define union queries
*/
public union(queries: any, wrap?: boolean): this {
this.hasUnion = true
queries = Array.isArray(queries)
? queries.map((one) => this.transformValue(one))
: this.transformValue(queries)
wrap !== undefined ? this.knexQuery.union(queries, wrap) : this.knexQuery.union(queries)
return this
}
/**
* Define union all queries
*/
public unionAll(queries: any, wrap?: boolean): this {
this.hasUnion = true
queries = Array.isArray(queries)
? queries.map((one) => this.transformValue(one))
: this.transformValue(queries)
wrap !== undefined ? this.knexQuery.unionAll(queries, wrap) : this.knexQuery.unionAll(queries)
return this
}
/**
* Define intersect queries
*/
public intersect(queries: any, wrap?: boolean): this {
queries = Array.isArray(queries)
? queries.map((one) => this.transformValue(one))
: this.transformValue(queries)
wrap !== undefined ? this.knexQuery.intersect(queries, wrap) : this.knexQuery.intersect(queries)
return this
}
/**
* Clear select columns
*/
public clearSelect(): this {
this.knexQuery.clearSelect()
return this
}
/**
* Clear where clauses
*/
public clearWhere(): this {
this.whereStack = [[]]
this.knexQuery.clearWhere()
return this
}
/**
* Clear order by
*/
public clearOrder(): this {
this.knexQuery.clearOrder()
return this
}
/**
* Clear having
*/
public clearHaving(): this {
this.knexQuery.clearHaving()
return this
}
/**
* Clear limit
*/
public clearLimit(): this {
this.knexQuery['_single'].limit = null
return this
}
/**
* Clear offset
*/
public clearOffset(): this {
this.knexQuery['_single'].offset = null
return this
}
/**
* Specify `FOR UPDATE` lock mode for a given
* query
*/
public forUpdate(...tableNames: string[]): this {
this.knexQuery.forUpdate(...tableNames)
return this
}
/**
* Specify `FOR SHARE` lock mode for a given
* query
*/
public forShare(...tableNames: string[]): this {
this.knexQuery.forShare(...tableNames)
return this
}
/**
* Skip locked rows
*/
public skipLocked(): this {
this.knexQuery.skipLocked()
return this
}
/**
* Fail when query wants a locked row
*/
public noWait(): this {
this.knexQuery.noWait()
return this
}
/**
* Define `with` CTE
*/
public with(alias: any, query: any): this {
this.knexQuery.with(alias, this.transformValue(query))
return this
}
/**
* Define `with` CTE with recursive keyword
*/
public withRecursive(alias: any, query: any): this {
this.knexQuery.withRecursive(alias, this.transformValue(query))
return this
}
/**
* Define schema for the table
*/
public withSchema(schema: any): this {
this.knexQuery.withSchema(schema)
return this
}
/**
* Define table alias
*/
public as(alias: any): this {
this.subQueryAlias = alias
this.knexQuery.as(alias)
return this
}
/**
* Count rows for the current query
*/
public count(columns: any, alias?: any): this {
this.hasAggregates = true
this.knexQuery.count(this.normalizeAggregateColumns(columns, alias))
return this
}
/**
* Count distinct rows for the current query
*/
public countDistinct(columns: any, alias?: any): this {
this.hasAggregates = true
this.knexQuery.countDistinct(this.normalizeAggregateColumns(columns, alias))
return this
}
/**
* Make use of `min` aggregate function
*/
public min(columns: any, alias?: any): this {
this.hasAggregates = true
this.knexQuery.min(this.normalizeAggregateColumns(columns, alias))
return this
}
/**
* Make use of `max` aggregate function
*/
public max(columns: any, alias?: any): this {
this.hasAggregates = true
this.knexQuery.max(this.normalizeAggregateColumns(columns, alias))
return this
}
/**
* Make use of `avg` aggregate function
*/
public avg(columns: any, alias?: any): this {
this.hasAggregates = true
this.knexQuery.avg(this.normalizeAggregateColumns(columns, alias))
return this
}
/**
* Make use of distinct `avg` aggregate function
*/
public avgDistinct(columns: any, alias?: any): this {
this.hasAggregates = true
this.knexQuery.avgDistinct(this.normalizeAggregateColumns(columns, alias))
return this
}
/**
* Make use of `sum` aggregate function
*/
public sum(columns: any, alias?: any): this {
this.hasAggregates = true
this.knexQuery.sum(this.normalizeAggregateColumns(columns, alias))
return this
}
/**
* Make use of distinct `sum` aggregate function
*/
public sumDistinct(columns: any, alias?: any): this {
this.hasAggregates = true
this.knexQuery.sumDistinct(this.normalizeAggregateColumns(columns, alias))
return this
}
/**
* A shorthand for applying offset and limit based upon
* the current page
*/
public forPage(page: number, perPage: number): this {
/**
* Calculate offset from current page and per page values
*/
const offset = page === 1 ? 0 : perPage * (page - 1)
this.offset(offset).limit(perPage)
return this
}
/**
* Define a query to constraint to be defined when condition is truthy
*/
public if(
condition: any,
matchCallback: (query: this) => any,
noMatchCallback?: (query: this) => any
): this {
let matched: any = condition
if (typeof condition === 'function') {
matched = condition()
}
if (matched) {
matchCallback(this)
} else if (noMatchCallback) {
noMatchCallback(this)
}
return this
}
/**
* Define a query to constraint to be defined when condition is falsy
*/
public unless(
condition: any,
matchCallback: (query: this) => any,
noMatchCallback?: (query: this) => any
): this {
let matched: any = condition
if (typeof condition === 'function') {
matched = condition()
}
if (!matched) {
matchCallback(this)
} else if (noMatchCallback) {
noMatchCallback(this)
}
return this
}
/**
* Define matching blocks just like `if/else if and else`.
*/
public match(
...blocks: ([condition: any, callback: (query: this) => any] | ((query: this) => any))[]
): this {
const matchingBlock = blocks.find((block) => {
if (Array.isArray(block) && block.length === 2) {
if (typeof block[0] === 'function' && block[0]()) {
return true
} else if (block[0]) {
return true
}
}
if (typeof block === 'function') {
return true
}
})
if (!matchingBlock) {
return this
}
if (Array.isArray(matchingBlock)) {
matchingBlock[1](this)
} else {
matchingBlock(this)
}
return this
}
} | the_stack |
module Kiwi.System {
/**
* Detects device support capabilities. Using some elements from System.js by MrDoob and Modernizr
* https://github.com/Modernizr/Modernizr/blob/master/feature-detects/audio.js
*
* @class Device
* @constructor
* @namespace Kiwi.System
*
* @author mrdoob
* @author Modernizr team
*
*/
export class Device {
constructor() {
this._checkAudio();
this._checkBrowser();
this._checkDevice();
this._checkFeatures();
this._checkOS();
}
/**
* The type of object that this is.
* @method objType
* @return {String} "Device"
* @public
*/
public objType() {
return "Device";
}
// Operating System
/**
*
* @property iOS
* @type boolean
* @public
*/
public iOS: boolean = false;
/**
*
* @property android
* @type boolean
* @public
*/
public android: boolean = false;
/**
*
* @property chromeOS
* @type boolean
* @public
*/
public chromeOS: boolean = false;
/**
*
* @property linux
* @type boolean
* @public
*/
public linux: boolean = false;
/**
*
* @property maxOS
* @type boolean
* @public
*/
public macOS: boolean = false;
/**
*
* @property windows
* @type boolean
* @public
*/
public windows: boolean = false;
/**
*
* @property windowsPhone
* @type boolean
* @public
*/
public windowsPhone: boolean = false;
// Features
/**
*
* @property canvas
* @type boolean
* @public
*/
public canvas: boolean = false;
/**
*
* @property file
* @type boolean
* @public
*/
public file: boolean = false;
/**
*
* @property fileSystem
* @type boolean
* @public
*/
public fileSystem: boolean = false;
/**
*
* @property localStorage
* @type boolean
* @public
*/
public localStorage: boolean = false;
/**
*
* @property webGL
* @type boolean
* @public
*/
public webGL: boolean = false;
/**
*
* @property worker
* @type boolean
* @public
*/
public worker: boolean = false;
/**
*
* @property blob
* @type boolean
* @public
*/
public blob: boolean = false;
/**
*
* @property touch
* @type boolean
* @public
*/
public touch: boolean = false;
/**
* If the type of touch events are pointers (event msPointers)
* @property pointerEnabled
* @type boolean
* @public
*/
public pointerEnabled: boolean = false;
// Browser
/**
*
* @property arora
* @type boolean
* @public
*/
public arora: boolean = false;
/**
*
* @property chrome
* @type boolean
* @public
*/
public chrome: boolean = false;
/**
*
* @property epiphany
* @type boolean
* @public
*/
public epiphany: boolean = false;
/**
*
* @property firefox
* @type boolean
* @public
*/
public firefox: boolean = false;
/**
*
* @property ie
* @type boolean
* @public
*/
public ie: boolean = false;
/**
*
* @property ieVersion
* @type Number
* @public
*/
public ieVersion: number = 0;
/**
*
* @property ieMobile
* @type boolean
* @public
*/
public ieMobile: boolean = false;
/**
*
* @property mobileSafari
* @type boolean
* @public
*/
public mobileSafari: boolean = false;
/**
*
* @property midori
* @type boolean
* @public
*/
public midori: boolean = false;
/**
*
* @property opera
* @type boolean
* @public
*/
public opera: boolean = false;
/**
*
* @property safari
* @type boolean
* @public
*/
public safari: boolean = false;
/**
*
* @property webApp
* @type boolean
* @public
*/
public webApp: boolean = false;
// Audio
/**
*
* @property audioData
* @type boolean
* @public
*/
public audioData: boolean = false;
/**
*
* @property webaudio
* @type boolean
* @public
*/
public webaudio: boolean = false;
/**
*
* @property ogg
* @type boolean
* @public
*/
public ogg: boolean = false;
/**
*
* @property mp3
* @type boolean
* @public
*/
public mp3: boolean = false;
/**
*
* @property wav
* @type boolean
* @public
*/
public wav: boolean = false;
/**
*
* @property m4a
* @type boolean
* @public
*/
public m4a: boolean = false;
// Device
/**
*
* @property iPhone
* @type boolean
* @public
*/
public iPhone: boolean = false;
/**
*
* @property iPhone4
* @type boolean
* @public
*/
public iPhone4: boolean = false;
/**
*
* @property iPad
* @type boolean
* @public
*/
public iPad: boolean = false;
/**
*
* @property pixelRatio
* @type Number
* @public
*/
public pixelRatio: number = 0;
/**
*
* @method _checkOS
* @private
*/
private _checkOS() {
var ua = navigator.userAgent;
if (/Android/.test(ua))
{
this.android = true;
}
else if (/CrOS/.test(ua))
{
this.chromeOS = true;
}
else if (/iP[ao]d|iPhone/i.test(ua))
{
this.iOS = true;
}
else if (/Linux/.test(ua))
{
this.linux = true;
}
else if (/Mac OS/.test(ua))
{
this.macOS = true;
}
else if(/Windows Phone/.test(ua)) {
this.windowsPhone = true;
}
else if (/Windows/.test(ua))
{
this.windows = true;
}
}
/**
*
* @method _checkFeatures
* @private
*/
private _checkFeatures() {
if (typeof window['Blob'] !== 'undefined') this.blob = true;
// Check availability of rendering contexts
this.canvas = !!window['CanvasRenderingContext2D'];
this.webGL = !!window['WebGLRenderingContext'];
try
{
this.localStorage = !!localStorage.getItem;
}
catch (error)
{
this.localStorage = false;
}
this.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob'];
this.fileSystem = !!window['requestFileSystem'];
this.worker = !!window['Worker'];
if ('ontouchstart' in document.documentElement ||
(window.navigator.msPointerEnabled && window.navigator.msMaxTouchPoints > 0) ||
((<any>window.navigator).pointerEnabled && (<any>window.navigator).maxTouchPoints > 0))
{
this.touch = true;
}
if ((<any>window.navigator).pointerEnabled || window.navigator.msPointerEnabled ) {
this.pointerEnabled = true;
}
}
/**
*
* @method _checkBrowser
* @private
*/
private _checkBrowser() {
var ua = navigator.userAgent;
var an = navigator.appName;
if (/Arora/.test(ua))
{
this.arora = true;
}
else if (/Chrome/.test(ua))
{
this.chrome = true;
}
else if (/Epiphany/.test(ua))
{
this.epiphany = true;
}
else if (/Firefox/.test(ua))
{
this.firefox = true;
}
else if (/Mobile Safari/.test(ua))
{
this.mobileSafari = true;
}
else if (/MSIE (\d+\.\d+);/.test(ua)) //Will Detect 10- versions of IE
{
this.ie = true;
this.ieVersion = parseInt(RegExp.$1);
if ( /IEMobile/.test(ua) ) {
this.ieMobile = true;
}
}
else if (/Trident/.test(ua)) //Will Detect 11+ versions for IE
{
this.ie = true;
/rv:(\d+\.\d+)\)/.test(ua);
this.ieVersion = parseInt(RegExp.$1);
}
else if (/Midori/.test(ua))
{
this.midori = true;
}
else if (/Opera/.test(ua))
{
this.opera = true;
}
else if (/Safari/.test(ua))
{
this.safari = true;
}
// WebApp mode in iOS
if (navigator['standalone'])
{
this.webApp = true;
}
}
/**
*
* @method _checkAudio
* @private
*/
private _checkAudio() {
this.audioData = !!(window['Audio']);
this.webaudio = !!(window['webkitAudioContext'] || window['AudioContext']);
var audioElement:HTMLAudioElement = <HTMLAudioElement> document.createElement('audio');
var result = false;
try
{
if (result = !!audioElement.canPlayType)
{
if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''))
{
this.ogg = true;
}
if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, ''))
{
this.mp3 = true;
}
// Mimetypes accepted:
// developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
// bit.ly/iphoneoscodecs
if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''))
{
this.wav = true;
}
if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, ''))
{
this.m4a = true;
}
}
} catch (e) { }
}
/**
*
* @method _checkDevice
* @private
*/
private _checkDevice() {
this.pixelRatio = window['devicePixelRatio'] || 1;
this.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') != -1;
this.iPhone4 = (this.pixelRatio == 2 && this.iPhone);
this.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') != -1;
}
/**
*
* @method getAll
* @return {String}
* @public
*/
public getAll(): string {
var output: string = '';
output = output.concat('Device\n');
output = output.concat('iPhone : ' + this.iPhone + '\n');
output = output.concat('iPhone4 : ' + this.iPhone4 + '\n');
output = output.concat('iPad : ' + this.iPad + '\n');
output = output.concat('\n');
output = output.concat('Operating System\n');
output = output.concat('iOS: ' + this.iOS + '\n');
output = output.concat('Android: ' + this.android + '\n');
output = output.concat('ChromeOS: ' + this.chromeOS + '\n');
output = output.concat('Linux: ' + this.linux + '\n');
output = output.concat('MacOS: ' + this.macOS + '\n');
output = output.concat('Windows: ' + this.windows + '\n');
output = output.concat('\n');
output = output.concat('Browser\n');
output = output.concat('Arora: ' + this.arora + '\n');
output = output.concat('Chrome: ' + this.chrome + '\n');
output = output.concat('Epiphany: ' + this.epiphany + '\n');
output = output.concat('Firefox: ' + this.firefox + '\n');
output = output.concat('Internet Explorer: ' + this.ie + ' (' + this.ieVersion + ')\n');
output = output.concat('Mobile Safari: ' + this.mobileSafari + '\n');
output = output.concat('Midori: ' + this.midori + '\n');
output = output.concat('Opera: ' + this.opera + '\n');
output = output.concat('Safari: ' + this.safari + '\n');
output = output.concat('\n');
output = output.concat('Features\n');
output = output.concat('Blob: ' + this.blob + '\n');
output = output.concat('Canvas: ' + this.canvas + '\n');
output = output.concat('File: ' + this.file + '\n');
output = output.concat('FileSystem: ' + this.fileSystem + '\n');
output = output.concat('LocalStorage: ' + this.localStorage + '\n');
output = output.concat('WebGL: ' + this.webGL + '\n');
output = output.concat('Worker: ' + this.worker + '\n');
output = output.concat('Touch: ' + this.touch + '\n');
output = output.concat('\n');
output = output.concat('Audio\n');
output = output.concat('Audio Data: ' + this.canvas + '\n');
output = output.concat('Web Audio: ' + this.canvas + '\n');
output = output.concat('Can play OGG: ' + this.canvas + '\n');
output = output.concat('Can play MP3: ' + this.canvas + '\n');
output = output.concat('Can play M4A: ' + this.canvas + '\n');
output = output.concat('Can play WAV: ' + this.canvas + '\n');
return output;
}
}
} | the_stack |
import Vue, { CreateElement } from 'vue';
import { Component, Inject, InjectReactive, Prop, ProvideReactive } from 'vue-property-decorator';
import { Action, State } from 'vuex-class';
import { arrayUnique } from '../../../../utils/array';
import { objectPick } from '../../../../utils/object';
import { updateServerTimeOffset } from '../../../../utils/server-time';
import { sleep } from '../../../../utils/utils';
import { uuidv4 } from '../../../../utils/uuid';
import { Api } from '../../../../_common/api/api.service';
import { getCookie } from '../../../../_common/cookie/cookie.service';
import {
DrawerStore,
DrawerStoreKey,
setStickerStreak,
} from '../../../../_common/drawer/drawer-store';
import { Fireside } from '../../../../_common/fireside/fireside.model';
import { FiresideRole } from '../../../../_common/fireside/role/role.model';
import {
createFiresideRTCProducer,
destroyFiresideRTCProducer,
stopStreaming,
} from '../../../../_common/fireside/rtc/producer';
import {
createFiresideRTC,
destroyFiresideRTC,
FiresideRTCHost,
renewRTCAudienceTokens,
} from '../../../../_common/fireside/rtc/rtc';
import { Growls } from '../../../../_common/growls/growls.service';
import { StickerPlacement } from '../../../../_common/sticker/placement/placement.model';
import { addStickerToTarget } from '../../../../_common/sticker/target/target-controller';
import { AppState, AppStore } from '../../../../_common/store/app-store';
import { User } from '../../../../_common/user/user.model';
import { Store } from '../../../store';
import { ChatStore, ChatStoreKey, clearChat, loadChat } from '../../chat/chat-store';
import { joinInstancedRoomChannel, leaveChatRoom, setGuestChatToken } from '../../chat/client';
import {
EVENT_STICKER_PLACEMENT,
EVENT_STREAMING_UID,
EVENT_UPDATE,
FiresideChannel,
} from '../../grid/fireside-channel';
import {
FiresideController,
FiresideControllerKey,
updateFiresideExpiryValues,
} from '../controller/controller';
import { StreamSetupModal } from '../stream/setup/setup-modal.service';
interface GridStickerPlacementPayload {
user_id: number;
streak: number;
sticker_placement: Partial<StickerPlacement>;
}
@Component({})
export class AppFiresideContainer extends Vue {
@ProvideReactive(FiresideControllerKey)
@Prop({ type: FiresideController, required: true })
controller!: FiresideController;
@AppState user!: AppStore['user'];
@State grid!: Store['grid'];
@Action loadGrid!: Store['loadGrid'];
@InjectReactive(ChatStoreKey)
chatStore!: ChatStore;
@Inject(DrawerStoreKey)
drawerStore!: DrawerStore;
get chat() {
return this.chatStore.chat;
}
created() {
if (!this.$slots.default) {
throw Error('AppFiresideContainer requires a default slot.');
}
this.controller.onRetry = this.onRetry;
}
render(h: CreateElement) {
return h('div', {}, this.$slots.default);
}
async mounted() {
const c = this.controller;
c.chat = this.chat;
// TODO: Do we want to do this?
if (c.status === 'joined') {
this.disconnect();
}
c.hasExpiryWarning = false;
if (c.fireside.blocked) {
c.status = 'blocked';
console.debug(`[Fireside] Blocked from joining blocked user's fireside.`);
return;
}
if (!this.grid) {
this.loadGrid();
}
if (!this.chat) {
loadChat(this.chatStore);
}
// Set up watchers to initiate connection once one of them boots up.
this.$watch('chat.connected', () => this.watchChat());
this.$watch('grid.connected', () => this.watchGrid());
// Both services may already be connected (watchers wouldn't fire),
// so try joining manually now.
this.tryJoin();
}
destroyed() {
this.controller.onRetry = null;
this.drawerStore.streak = null;
this.disconnect();
this.grid?.unsetGuestToken();
if (this.chat?.isGuest) {
clearChat(this.chatStore);
}
}
watchChat() {
const c = this.controller;
if (this.chat?.connected) {
this.tryJoin();
}
// Only disconnect when not connected and it previous registered a different state.
// This watcher runs once initially when chat is not connected, and we don't want to call
// disconnect in that case.
else if (c.chatPreviousConnectedState !== null) {
this.disconnect();
}
c.chat = this.chat;
c.chatPreviousConnectedState = this.chat?.connected === true;
}
watchGrid() {
const c = this.controller;
if (this.grid?.connected) {
this.tryJoin();
}
// Only disconnect when not connected and it previous registered a different state.
// This watcher runs once initially when grid is not connected, and we don't want to call
// disconnect in that case.
else if (this.grid && c.gridPreviousConnectedState !== null) {
this.disconnect();
}
c.gridPreviousConnectedState = this.grid?.connected ?? null;
}
private async tryJoin() {
const c = this.controller;
// Only try to join when disconnected (or for the first "initial" load).
if (c.status === 'disconnected' || c.status === 'initial') {
c.status = 'loading';
// Make sure the services are connected.
while (!this.grid?.connected) {
console.debug('[FIRESIDE] Wait for Grid...');
if (this.grid && !this.user && !this.grid.isGuest) {
console.info('[FIRESIDE] Enabling guest access to grid');
const authToken = await this.getAuthToken();
if (!authToken) {
throw new Error('Could not fetch guest token. This should be impossible');
}
await this.grid.setGuestToken(authToken);
}
await sleep(250);
}
while (!this.chat?.connected) {
console.debug('[FIRESIDE] Wait for Chat...');
if (this.chat && !this.user && !this.chat.isGuest) {
console.info('[FIRESIDE] Enabling guest access to chat');
const authToken = await this.getAuthToken();
if (!authToken) {
throw new Error('Could not fetch guest token. This should be impossible');
}
await setGuestChatToken(this.chat, authToken);
}
await sleep(250);
}
this.join();
}
}
private async join() {
console.debug(`[FIRESIDE] Joining fireside.`);
const c = this.controller;
// --- Make sure common join conditions are met.
if (
!c.fireside ||
!this.grid ||
!this.grid.connected ||
!this.grid.socket ||
!this.chat ||
!this.chat.connected
) {
console.debug(`[FIRESIDE] General connection error.`);
c.status = 'setup-failed';
return;
}
const authToken = await this.getAuthToken();
if (!authToken) {
console.debug(`[FIRESIDE] Setup failure 1.`);
c.status = 'setup-failed';
return;
}
// --- Refetch fireside information and check that it's not yet expired.
const canProceed = await this._fetchForStreaming({ assignRouteStatus: true });
if (!canProceed) {
return;
}
// Maybe they are blocked now?
if (c.fireside.blocked) {
c.status = 'blocked';
console.debug(`[Fireside] Blocked from joining blocked user's fireside.`);
return;
}
// Make sure it's still joinable.
if (!c.fireside.isOpen()) {
console.debug(`[FIRESIDE] Fireside is expired, and cannot be joined.`);
c.status = 'expired';
return;
}
// --- Make them join the fireside (if they aren't already).
if (this.user && !c.fireside.role) {
const rolePayload = await Api.sendRequest(`/web/fireside/join/${c.fireside.hash}`);
if (!rolePayload || !rolePayload.success || !rolePayload.role) {
console.debug(`[FIRESIDE] Failed to acquire a role.`);
c.status = 'setup-failed';
return;
}
c.fireside.role = new FiresideRole(rolePayload.role);
}
// --- Join Grid channel.
const channel = new FiresideChannel(c.fireside, this.grid.socket, this.user, authToken);
// Subscribe to the update event.
channel.on(EVENT_UPDATE, this.onGridUpdateFireside.bind(this));
channel.on(EVENT_STREAMING_UID, this.onGridStreamingUidAdded.bind(this));
channel.on(EVENT_STICKER_PLACEMENT, this.onGridStickerPlacement.bind(this));
try {
await new Promise<void>((resolve, reject) => {
channel
.join()
.receive('error', reject)
.receive('ok', () => {
c.gridChannel = channel;
this.grid!.channels.push(channel);
resolve();
});
});
} catch (error) {
console.debug(`[FIRESIDE] Setup failure 3.`, error);
if (error && error.reason === 'blocked') {
c.status = 'blocked';
} else {
c.status = 'setup-failed';
}
return;
}
// Now join the chat's room channel.
try {
const chatChannel = await joinInstancedRoomChannel(this.chat, c.fireside.chat_room_id);
if (!chatChannel) {
console.debug(`[FIRESIDE] Setup failure 4.`);
c.status = 'setup-failed';
return;
}
c.chatChannel = chatChannel;
} catch (error) {
console.debug(`[FIRESIDE] Setup failure 5.`, error);
c.status = 'setup-failed';
return;
}
c.chatChannel.on('kick_member', (data: any) => {
if (this.user && data.user_id === this.user.id) {
Growls.info(this.$gettext(`You've been kicked from the fireside.`));
this.$router.push({ name: 'home' });
}
});
c.status = 'joined';
console.debug(`[FIRESIDE] Successfully joined fireside.`);
// Set up the expiry interval to check if the fireside is expired.
this.clearExpiryCheck();
c.expiryInterval = setInterval(this.expiryCheck.bind(this), 1000);
this.expiryCheck();
this.setupExpiryInfoInterval();
updateFiresideExpiryValues(c);
}
private async _fetchForStreaming({ assignRouteStatus = true }) {
const c = this.controller;
try {
const payload = await Api.sendRequest(
`/web/fireside/fetch-for-streaming/${c.fireside.hash}`,
undefined,
{ detach: true }
);
if (!payload.fireside) {
console.debug(`[FIRESIDE] Trying to load fireside, but it was not found.`);
if (assignRouteStatus) {
c.status = 'setup-failed';
}
return false;
}
if (payload.serverTime) {
updateServerTimeOffset(payload.serverTime);
}
c.fireside.assign(payload.fireside);
// If they have a host role, or if this fireside is actively
// streaming, we'll get streaming tokens from the fetch payload. In
// that case, we want to set up the RTC stuff.
this.upsertRtc(payload, { checkJoined: false });
} catch (error) {
console.debug(`[FIRESIDE] Setup failure 2.`, error);
if (assignRouteStatus) {
c.status = 'setup-failed';
}
return false;
}
return true;
}
private async getAuthToken() {
if (this.user) {
return await getCookie('frontend');
}
let token = sessionStorage.getItem('fireside-token');
if (!token) {
token = uuidv4();
sessionStorage.setItem('fireside-token', token);
}
return token;
}
private disconnect() {
const c = this.controller;
if (!c || c.status === 'disconnected') {
return;
}
this.clearExpiryCheck();
this.destroyExpiryInfoInterval();
console.debug(`[FIRESIDE] Disconnecting from fireside.`);
c.status = 'disconnected';
if (this.grid && this.grid.connected && c.gridChannel) {
c.gridChannel.leave();
}
c.gridChannel = null;
if (this.chat && this.chat.connected && c.chatChannel) {
leaveChatRoom(this.chat, c.chatChannel.room);
}
c.chatChannel = null;
StreamSetupModal.close();
this.destroyRtc();
console.debug(`[FIRESIDE] Disconnected from fireside.`);
}
private clearExpiryCheck() {
const c = this.controller;
if (c.expiryInterval) {
clearInterval(c.expiryInterval);
c.expiryInterval = null;
}
}
private expiryCheck() {
const c = this.controller;
if (!c || c.status !== 'joined' || !c.fireside) {
return;
}
if (!c.fireside.isOpen()) {
this.disconnect();
c.status = 'expired';
}
}
private destroyExpiryInfoInterval() {
const c = this.controller;
if (c.updateInterval) {
clearInterval(c.updateInterval);
c.updateInterval = null;
}
}
private setupExpiryInfoInterval() {
const c = this.controller;
this.destroyExpiryInfoInterval();
c.updateInterval = setInterval(() => updateFiresideExpiryValues(c), 1000);
}
private async upsertRtc(
payload: any,
options: {
checkJoined?: boolean;
hosts?: FiresideRTCHost[];
} = {
checkJoined: true,
}
) {
const { checkJoined = true, hosts } = options;
const c = this.controller;
if (!c || !c.fireside || (checkJoined && c.status !== 'joined')) {
return;
}
// If they don't have tokens yet, then they don't need to set up the RTC
// stuff.
if (!payload.videoToken || !payload.chatToken) {
return;
}
if (c.rtc === null) {
c.rtc = createFiresideRTC(
c.fireside,
this.user?.id ?? null,
payload.streamingAppId,
payload.streamingUid,
payload.videoChannelName,
payload.videoToken,
payload.chatChannelName,
payload.chatToken,
hosts ?? this.getHostsFromStreamingInfo(payload) ?? [],
{ isMuted: c.isMuted }
);
} else if (!c.rtc.producer) {
renewRTCAudienceTokens(c.rtc, payload.videoToken, payload.chatToken);
}
}
private getHostsFromStreamingInfo(streamingInfo: any) {
if (!streamingInfo.hosts) {
return;
}
const streamingUids = streamingInfo.streamingUids ?? [];
const hosts: FiresideRTCHost[] = (User.populate(streamingInfo.hosts ?? []) as User[]).map(
user => ({
user,
uids: streamingUids[user.id] ?? [],
})
);
return hosts;
}
private destroyRtc() {
const c = this.controller;
if (!c.rtc) {
return;
}
destroyFiresideRTC(c.rtc);
c.rtc = null;
}
private onRetry() {
this.disconnect();
this.tryJoin();
}
async onGridUpdateFireside(payload: any) {
const c = this.controller;
if (!c.fireside || !payload.fireside) {
return;
}
const updatedFireside = new Fireside(payload.fireside);
const oldCommunityLinks = c.fireside.community_links;
for (const updatedLink of updatedFireside.community_links) {
const oldLink = oldCommunityLinks.find(
i => i.community.id === updatedLink.community.id
);
if (!oldLink) {
continue;
}
// Preserve the old Community model from the link, otherwise we will
// overwrite perms.
Object.assign(updatedLink, objectPick(oldLink, ['community']));
}
Object.assign(
c.fireside,
objectPick(updatedFireside, [
'user',
'header_media_item',
'title',
'expires_on',
'is_expired',
'is_streaming',
'is_draft',
'member_count',
'community_links',
])
);
const priorHosts = c.rtc?.hosts ?? [];
const newHosts = this.getHostsFromStreamingInfo(payload.streaming_info)?.map(newHost => {
const priorHost = priorHosts.find(i => i.user.id === newHost.user.id);
if (priorHost) {
// Transfer over all previously assigned uids to the new host.
newHost.uids.push(...priorHost.uids);
arrayUnique(newHost.uids);
}
return newHost;
});
if (newHosts) {
const wasHost = priorHosts.some(host => host.user.id === this.user?.id);
const isHost = newHosts.some(host => host.user.id === this.user?.id);
if (c.rtc && newHosts.length > 0) {
// If we have an RTC, replace our old hosts with the new ones we
// just got.
c.rtc.hosts.splice(0, c.rtc.hosts.length);
c.rtc.hosts.push(...newHosts);
}
// If our host state changed, we need to update anything else
// depending on streaming.
if (isHost !== wasHost) {
// If we don't actually have an RTC created yet, take us through
// the normal Host initialization.
if (!c.rtc) {
await this._fetchForStreaming({ assignRouteStatus: false });
this.expiryCheck();
return;
}
try {
// Validate our streamingUid. If this fails, we're unable to
// stream.
const response = await Api.sendRequest(
'/web/dash/fireside/generate-streaming-tokens/' + c.fireside.id,
{ streaming_uid: c.rtc.streamingUid },
{ detach: true }
);
if (response?.success !== true) {
throw new Error(response);
}
// Manually update our role to something where we can stream.
if (c.fireside.role) {
c.fireside.role.role = 'cohost';
c.fireside.role.can_stream_audio = true;
c.fireside.role.can_stream_video = true;
}
} catch (_) {
// If our host state changed, downgrade ourselves to an audience member.
if (!isHost && wasHost && c.fireside.role) {
c.fireside.role.role = 'audience';
c.fireside.role.can_stream_audio = false;
c.fireside.role.can_stream_video = false;
}
}
if (c.fireside.role?.canStream === true) {
// Grab a producer if we don't have one and we're now able
// to stream.
c.rtc.producer ??= createFiresideRTCProducer(c.rtc);
Growls.info(
this.$gettext(
`You've been added as a host to this fireside. Hop into the stream!`
)
);
} else if (c.rtc.producer) {
// If our role doesn't allow us to stream and we have a
// producer, tear it down and clean it up.
await stopStreaming(c.rtc.producer);
destroyFiresideRTCProducer(c.rtc.producer);
c.rtc.producer = null;
// TODO: If this Fireside was a draft, we may need to
// re-initialize this component to see if they still have
// permissions to view it.
Growls.info(this.$gettext(`You've been removed as a host for this fireside.`));
}
}
}
this.expiryCheck();
// We don't update host streaming info through this. Only the audience
// streaming info is done through Grid.
if (c.fireside.role?.canStream === true) {
return;
}
if (c.fireside.is_streaming && payload.streaming_info) {
this.upsertRtc(payload.streaming_info, { hosts: newHosts });
} else {
this.destroyRtc();
}
}
onGridStreamingUidAdded(payload: any) {
console.debug('[FIRESIDE] Grid streaming uid added.', payload);
const c = this.controller;
if (!c.rtc || !payload.streaming_uid || !payload.user) {
return;
}
const user = new User(payload.user);
const host = c.rtc.hosts.find(host => host.user.id === user.id);
if (host) {
host.user = user;
if (host.uids.indexOf(payload.streaming_uid) === -1) {
host.uids.push(payload.streaming_uid);
}
} else {
c.rtc.hosts.push({
user: user,
uids: [payload.streaming_uid],
});
}
}
onGridStickerPlacement(payload: GridStickerPlacementPayload) {
console.debug('[FIRESIDE] Grid sticker placement received.', payload, payload.streak);
const c = this.controller;
const placement = new StickerPlacement(payload.sticker_placement);
setStickerStreak(this.drawerStore, placement.sticker, payload.streak);
// This happens automatically when we're placing our own sticker. Ignore
// it here so we don't do it twice.
if (payload.user_id !== this.user?.id) {
addStickerToTarget(c.stickerTargetController, placement);
c.fireside.addStickerToCount(placement.sticker);
}
}
} | the_stack |
import { CurrencyManager } from '@requestnetwork/currency';
import { IdentityTypes, PaymentTypes, RequestLogicTypes } from '@requestnetwork/types';
import { EventEmitter } from 'events';
import Request from '../../src/api/request';
const mockRequestLogic: RequestLogicTypes.IRequestLogic = {
async createRequest(): Promise<any> {
return;
},
async createEncryptedRequest(): Promise<any> {
return;
},
async computeRequestId(): Promise<any> {
return;
},
async acceptRequest(): Promise<any> {
return Object.assign(new EventEmitter(), { meta: {} });
},
async cancelRequest(): Promise<any> {
return Object.assign(new EventEmitter(), { meta: {} });
},
async increaseExpectedAmountRequest(): Promise<any> {
return Object.assign(new EventEmitter(), { meta: {} });
},
async reduceExpectedAmountRequest(): Promise<any> {
return Object.assign(new EventEmitter(), { meta: {} });
},
async addExtensionsDataRequest(): Promise<any> {
return Object.assign(new EventEmitter(), { meta: {} });
},
async getRequestFromId(): Promise<any> {
return { meta: {}, result: { request: { requestId: '1' }, pending: null } };
},
async getRequestsByTopic(): Promise<any> {
return {
meta: {},
result: {
requests: [],
},
};
},
async getRequestsByMultipleTopics(): Promise<any> {
return {
meta: {},
result: {
requests: [],
},
};
},
};
const mockPaymentNetwork: PaymentTypes.IPaymentNetwork = {
async createExtensionsDataForCreation(): Promise<any> {
return;
},
async createExtensionsDataForAddPaymentInformation(): Promise<any> {
return { meta: {} };
},
async createExtensionsDataForAddRefundInformation(): Promise<any> {
return { meta: {} };
},
async getBalance(): Promise<any> {
return;
},
};
const mockDeclarativePaymentNetwork: PaymentTypes.IPaymentNetwork = {
async createExtensionsDataForCreation(): Promise<any> {
return;
},
async createExtensionsDataForAddPaymentInformation(): Promise<any> {
return { meta: {} };
},
async createExtensionsDataForAddRefundInformation(): Promise<any> {
return { meta: {} };
},
async createExtensionsDataForDeclareReceivedPayment(): Promise<any> {
return;
},
async createExtensionsDataForDeclareReceivedRefund(): Promise<any> {
return;
},
async createExtensionsDataForDeclareSentPayment(): Promise<any> {
return;
},
async createExtensionsDataForDeclareSentRefund(): Promise<any> {
return;
},
async getBalance(): Promise<any> {
return;
},
} as PaymentTypes.IPaymentNetwork;
const signatureIdentity: IdentityTypes.IIdentity = {
type: IdentityTypes.TYPE.ETHEREUM_ADDRESS,
value: '0x627306090abab3a6e1400e9345bc60c78a8bef57',
};
const bitcoinAddress = 'mgPKDuVmuS9oeE2D9VPiCQriyU14wxWS1v';
const currencyManager = CurrencyManager.getDefault();
// Most of the tests are done as integration tests in ../index.test.ts
/* eslint-disable @typescript-eslint/no-unused-expressions */
describe('api/request', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('exists', async () => {
expect(Request).toBeDefined();
const request = new Request('1', mockRequestLogic, currencyManager);
/* eslint-disable @typescript-eslint/unbound-method */
expect(typeof request.accept).toBe('function');
expect(typeof request.cancel).toBe('function');
expect(typeof request.increaseExpectedAmountRequest).toBe('function');
expect(typeof request.reduceExpectedAmountRequest).toBe('function');
expect(typeof request.getData).toBe('function');
/* eslint-enable @typescript-eslint/unbound-method */
});
it('emits error at the creation', async () => {
const testingEmitter = new EventEmitter();
const request = new Request('1', mockRequestLogic, currencyManager, {
requestLogicCreateResult: testingEmitter as any,
});
// eslint-disable-next-line
const handleError = jest.fn((error: any) => {
expect(error).toBe('error for test purpose');
});
request.on('error', handleError);
testingEmitter.emit('error', 'error for test purpose');
// 'error must be emitted'
expect(handleError).toHaveBeenCalled();
});
describe('accept', () => {
it('calls request-logic', async () => {
const spy = jest.spyOn(mockRequestLogic, 'acceptRequest');
const request = new Request('1', mockRequestLogic, currencyManager);
await request.accept(signatureIdentity);
expect(spy).toHaveBeenCalledTimes(1);
});
it('calls request-logic and payment network', async () => {
const spyReqLog = jest.spyOn(mockRequestLogic, 'acceptRequest');
const spyPayNet = jest.spyOn(
mockPaymentNetwork,
'createExtensionsDataForAddRefundInformation',
);
const request = new Request('1', mockRequestLogic, currencyManager, {
paymentNetwork: mockPaymentNetwork,
});
await request.accept(signatureIdentity, { refundAddress: bitcoinAddress });
expect(spyPayNet).toHaveBeenCalledTimes(1);
expect(spyReqLog).toHaveBeenCalledTimes(1);
});
it('cannot call accept and add refund address without payment network', async () => {
const request = new Request('1', mockRequestLogic, currencyManager);
await expect(
request.accept(signatureIdentity, { refundAddress: bitcoinAddress }),
).rejects.toThrowError('Cannot add refund information without payment network');
});
});
describe('cancel', () => {
it('calls request-logic', async () => {
const spy = jest.spyOn(mockRequestLogic, 'cancelRequest');
const request = new Request('1', mockRequestLogic, currencyManager);
await request.cancel(signatureIdentity);
expect(spy).toHaveBeenCalledTimes(1);
});
it('calls request-logic and payment network', async () => {
const spyReqLog = jest.spyOn(mockRequestLogic, 'cancelRequest');
const spyPayNet = jest.spyOn(
mockPaymentNetwork,
'createExtensionsDataForAddRefundInformation',
);
const request = new Request('1', mockRequestLogic, currencyManager, {
paymentNetwork: mockPaymentNetwork,
});
await request.cancel(signatureIdentity, { refundAddress: bitcoinAddress });
expect(spyPayNet).toHaveBeenCalledTimes(1);
expect(spyReqLog).toHaveBeenCalledTimes(1);
});
it('cannot call cancel and add refund address without payment network', async () => {
const request = new Request('1', mockRequestLogic, currencyManager);
await expect(
request.cancel(signatureIdentity, { refundAddress: bitcoinAddress }),
).rejects.toThrowError('Cannot add refund information without payment network');
});
});
describe('increaseExpectedAmountRequest', () => {
it('calls request-logic', async () => {
const spy = jest.spyOn(mockRequestLogic, 'increaseExpectedAmountRequest');
const request = new Request('1', mockRequestLogic, currencyManager);
await request.increaseExpectedAmountRequest(3, signatureIdentity);
expect(spy).toHaveBeenCalledTimes(1);
});
it('calls request-logic and payment network', async () => {
const spyReqLog = jest.spyOn(mockRequestLogic, 'increaseExpectedAmountRequest');
const spyPayNet = jest.spyOn(
mockPaymentNetwork,
'createExtensionsDataForAddRefundInformation',
);
const request = new Request('1', mockRequestLogic, currencyManager, {
paymentNetwork: mockPaymentNetwork,
});
await request.increaseExpectedAmountRequest(3, signatureIdentity, {
refundAddress: bitcoinAddress,
});
expect(spyPayNet).toHaveBeenCalledTimes(1);
expect(spyReqLog).toHaveBeenCalledTimes(1);
});
it('cannot call increase and add refund address without payment network', async () => {
const request = new Request('1', mockRequestLogic, currencyManager);
await expect(
request.increaseExpectedAmountRequest(3, signatureIdentity, {
refundAddress: bitcoinAddress,
}),
).rejects.toThrowError('Cannot add refund information without payment network');
});
});
describe('reduceExpectedAmountRequest', () => {
it('calls request-logic', async () => {
const spy = jest.spyOn(mockRequestLogic, 'reduceExpectedAmountRequest');
const request = new Request('1', mockRequestLogic, currencyManager);
await request.reduceExpectedAmountRequest(3, signatureIdentity);
expect(spy).toHaveBeenCalledTimes(1);
});
it('calls request-logic and payment network', async () => {
const spyReqLog = jest.spyOn(mockRequestLogic, 'reduceExpectedAmountRequest');
const spyPayNet = jest.spyOn(
mockPaymentNetwork,
'createExtensionsDataForAddPaymentInformation',
);
const request = new Request('1', mockRequestLogic, currencyManager, {
paymentNetwork: mockPaymentNetwork,
});
await request.reduceExpectedAmountRequest(3, signatureIdentity, {
refundAddress: bitcoinAddress,
});
expect(spyPayNet).toHaveBeenCalledTimes(1);
expect(spyReqLog).toHaveBeenCalledTimes(1);
});
it('cannot call reduce and add payment address without payment network', async () => {
const request = new Request('1', mockRequestLogic, currencyManager);
await expect(
request.reduceExpectedAmountRequest('1', signatureIdentity, {
paymentInformation: bitcoinAddress,
}),
).rejects.toThrowError('Cannot add payment information without payment network');
});
});
describe('addPaymentInformation', () => {
it('calls request-logic and payment network', async () => {
const spyReqLog = jest.spyOn(mockRequestLogic, 'addExtensionsDataRequest');
const spyPayNet = jest.spyOn(
mockPaymentNetwork,
'createExtensionsDataForAddPaymentInformation',
);
const request = new Request('1', mockRequestLogic, currencyManager, {
paymentNetwork: mockPaymentNetwork,
});
await request.addPaymentInformation({ paymentAddress: bitcoinAddress }, signatureIdentity);
expect(spyPayNet).toHaveBeenCalledTimes(1);
expect(spyReqLog).toHaveBeenCalledTimes(1);
});
it('cannot add payment address without payment network', async () => {
const request = new Request('1', mockRequestLogic, currencyManager);
await expect(
request.addPaymentInformation({ paymentAddress: bitcoinAddress }, signatureIdentity),
).rejects.toThrowError('Cannot add payment information without payment network');
});
});
describe('addRefundInformation', () => {
it('calls request-logic and payment network', async () => {
const spyReqLog = jest.spyOn(mockRequestLogic, 'addExtensionsDataRequest');
const spyPayNet = jest.spyOn(
mockPaymentNetwork,
'createExtensionsDataForAddRefundInformation',
);
const request = new Request('1', mockRequestLogic, currencyManager, {
paymentNetwork: mockPaymentNetwork,
});
await request.addRefundInformation({ refundAddress: bitcoinAddress }, signatureIdentity);
expect(spyPayNet).toHaveBeenCalledTimes(1);
expect(spyReqLog).toHaveBeenCalledTimes(1);
});
it('cannot add payment address without payment network', async () => {
const request = new Request('1', mockRequestLogic, currencyManager);
await expect(
request.addRefundInformation({ refundAddress: bitcoinAddress }, signatureIdentity),
).rejects.toThrowError('Cannot add refund information without payment network');
});
});
describe('declareSentPayment', () => {
it('calls request-logic and payment network', async () => {
const spyReqLog = jest.spyOn(mockRequestLogic, 'addExtensionsDataRequest');
const spyPayNet = jest.spyOn(
mockDeclarativePaymentNetwork as any,
'createExtensionsDataForDeclareSentPayment',
);
const request = new Request('1', mockRequestLogic, currencyManager, {
paymentNetwork: mockDeclarativePaymentNetwork,
});
await request.declareSentPayment('1000', 'sent', signatureIdentity);
expect(spyPayNet).toHaveBeenCalledTimes(1);
expect(spyReqLog).toHaveBeenCalledTimes(1);
});
it('cannot declare sent payment if no payment network', async () => {
const request = new Request('1', mockRequestLogic, currencyManager);
await expect(
request.declareSentPayment('1000', 'sent', signatureIdentity),
).rejects.toThrowError('Cannot declare sent payment without payment network');
});
it('cannot declare sent payment if payment network is not declarative', async () => {
const request = new Request('1', mockRequestLogic, currencyManager, {
paymentNetwork: mockPaymentNetwork,
});
await expect(
request.declareSentPayment('1000', 'sent', signatureIdentity),
).rejects.toThrowError('Cannot declare sent payment without declarative payment network');
});
});
describe('declareSentRefund', () => {
it('calls request-logic and payment network', async () => {
const spyReqLog = jest.spyOn(mockRequestLogic, 'addExtensionsDataRequest');
const spyPayNet = jest.spyOn(
mockDeclarativePaymentNetwork as any,
'createExtensionsDataForDeclareSentRefund',
);
const request = new Request('1', mockRequestLogic, currencyManager, {
paymentNetwork: mockDeclarativePaymentNetwork,
});
await request.declareSentRefund('1000', 'sent', signatureIdentity);
expect(spyPayNet).toHaveBeenCalledTimes(1);
expect(spyReqLog).toHaveBeenCalledTimes(1);
});
it('cannot declare sent refund if no payment network', async () => {
const request = new Request('1', mockRequestLogic, currencyManager);
await expect(
request.declareSentRefund('1000', 'sent', signatureIdentity),
).rejects.toThrowError('Cannot declare sent refund without payment network');
});
it('cannot declare sent refund if payment network is not declarative', async () => {
const request = new Request('1', mockRequestLogic, currencyManager, {
paymentNetwork: mockPaymentNetwork,
});
await expect(
request.declareSentRefund('1000', 'sent', signatureIdentity),
).rejects.toThrowError('Cannot declare sent refund without declarative payment network');
});
});
describe('declareReceivedPayment', () => {
it('calls request-logic and payment network', async () => {
const spyReqLog = jest.spyOn(mockRequestLogic, 'addExtensionsDataRequest');
const spyPayNet = jest.spyOn(
mockDeclarativePaymentNetwork as any,
'createExtensionsDataForDeclareReceivedPayment',
);
const request = new Request('1', mockRequestLogic, currencyManager, {
paymentNetwork: mockDeclarativePaymentNetwork,
});
await request.declareReceivedPayment('1000', 'received', signatureIdentity);
expect(spyPayNet).toHaveBeenCalledTimes(1);
expect(spyReqLog).toHaveBeenCalledTimes(1);
});
it('cannot declare received payment if no payment network', async () => {
const request = new Request('1', mockRequestLogic, currencyManager);
await expect(
request.declareReceivedPayment('1000', 'received', signatureIdentity),
).rejects.toThrowError('Cannot declare received payment without payment network');
});
it('cannot declare received payment if payment network is not declarative', async () => {
const request = new Request('1', mockRequestLogic, currencyManager, {
paymentNetwork: mockPaymentNetwork,
});
await expect(
request.declareReceivedPayment('1000', 'received', signatureIdentity),
).rejects.toThrowError('Cannot declare received payment without declarative payment network');
});
});
describe('declareReceivedRefund', () => {
it('calls request-logic and payment network', async () => {
const spyReqLog = jest.spyOn(mockRequestLogic, 'addExtensionsDataRequest');
const spyPayNet = jest.spyOn(
mockDeclarativePaymentNetwork as any,
'createExtensionsDataForDeclareReceivedRefund',
);
const request = new Request('1', mockRequestLogic, currencyManager, {
paymentNetwork: mockDeclarativePaymentNetwork,
});
await request.declareReceivedRefund('1000', 'received', signatureIdentity);
expect(spyPayNet).toHaveBeenCalledTimes(1);
expect(spyReqLog).toHaveBeenCalledTimes(1);
});
it('cannot declare received refund if no payment network', async () => {
const request = new Request('1', mockRequestLogic, currencyManager);
await expect(
request.declareReceivedRefund('1000', 'received', signatureIdentity),
).rejects.toThrowError('Cannot declare received refund without payment network');
});
it('cannot declare received refund if payment network is not declarative', async () => {
const request = new Request('1', mockRequestLogic, currencyManager, {
paymentNetwork: mockPaymentNetwork,
});
await expect(
request.declareReceivedRefund('1000', 'received', signatureIdentity),
).rejects.toThrowError('Cannot declare received refund without declarative payment network');
});
});
describe('refresh', () => {
it('calls request-logic', async () => {
const mockRequestLogicWithRequest: RequestLogicTypes.IRequestLogic = {
async createRequest(): Promise<any> {
return;
},
async createEncryptedRequest(): Promise<any> {
return;
},
async computeRequestId(): Promise<any> {
return;
},
async acceptRequest(): Promise<any> {
return { meta: {} };
},
async cancelRequest(): Promise<any> {
return { meta: {} };
},
async increaseExpectedAmountRequest(): Promise<any> {
return { meta: {} };
},
async reduceExpectedAmountRequest(): Promise<any> {
return { meta: {} };
},
async addExtensionsDataRequest(): Promise<any> {
return { meta: {}, result: {} };
},
async getRequestFromId(): Promise<any> {
return {
meta: {},
result: {
pending: {},
request: {},
},
};
},
async getRequestsByTopic(): Promise<any> {
return {
meta: {},
result: {
requests: [],
},
};
},
async getRequestsByMultipleTopics(): Promise<any> {
return {
meta: {},
result: {
requests: [],
},
};
},
};
const spy = jest.spyOn(mockRequestLogicWithRequest, 'getRequestFromId');
const request = new Request('1', mockRequestLogicWithRequest, currencyManager);
await request.refresh();
expect(spy).toHaveBeenCalledTimes(1);
});
});
}); | the_stack |
import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion';
import {DOWN_ARROW} from '@angular/cdk/keycodes';
import {
Directive,
ElementRef,
EventEmitter,
Inject,
Input,
OnDestroy,
Optional,
Output,
AfterViewInit,
OnChanges,
SimpleChanges,
} from '@angular/core';
import {
AbstractControl,
ControlValueAccessor,
ValidationErrors,
Validator,
ValidatorFn,
} from '@angular/forms';
import {DateAdapter, MAT_DATE_FORMATS, MatDateFormats} from '@angular/material/core';
import {Subscription, Subject} from 'rxjs';
import {createMissingDateImplError} from './datepicker-errors';
import {
ExtractDateTypeFromSelection,
MatDateSelectionModel,
DateSelectionModelChange,
} from './date-selection-model';
/**
* An event used for datepicker input and change events. We don't always have access to a native
* input or change event because the event may have been triggered by the user clicking on the
* calendar popup. For consistency, we always use MatDatepickerInputEvent instead.
*/
export class MatDatepickerInputEvent<D, S = unknown> {
/** The new value for the target datepicker input. */
value: D | null;
constructor(
/** Reference to the datepicker input component that emitted the event. */
public target: MatDatepickerInputBase<S, D>,
/** Reference to the native input element associated with the datepicker input. */
public targetElement: HTMLElement,
) {
this.value = this.target.value;
}
}
/** Function that can be used to filter out dates from a calendar. */
export type DateFilterFn<D> = (date: D | null) => boolean;
/** Base class for datepicker inputs. */
@Directive()
export abstract class MatDatepickerInputBase<S, D = ExtractDateTypeFromSelection<S>>
implements ControlValueAccessor, AfterViewInit, OnChanges, OnDestroy, Validator
{
/** Whether the component has been initialized. */
private _isInitialized: boolean;
/** The value of the input. */
@Input()
get value(): D | null {
return this._model ? this._getValueFromModel(this._model.selection) : this._pendingValue;
}
set value(value: any) {
this._assignValueProgrammatically(value);
}
protected _model: MatDateSelectionModel<S, D> | undefined;
/** Whether the datepicker-input is disabled. */
@Input()
get disabled(): boolean {
return !!this._disabled || this._parentDisabled();
}
set disabled(value: BooleanInput) {
const newValue = coerceBooleanProperty(value);
const element = this._elementRef.nativeElement;
if (this._disabled !== newValue) {
this._disabled = newValue;
this.stateChanges.next(undefined);
}
// We need to null check the `blur` method, because it's undefined during SSR.
// In Ivy static bindings are invoked earlier, before the element is attached to the DOM.
// This can cause an error to be thrown in some browsers (IE/Edge) which assert that the
// element has been inserted.
if (newValue && this._isInitialized && element.blur) {
// Normally, native input elements automatically blur if they turn disabled. This behavior
// is problematic, because it would mean that it triggers another change detection cycle,
// which then causes a changed after checked error if the input element was focused before.
element.blur();
}
}
private _disabled: boolean;
/** Emits when a `change` event is fired on this `<input>`. */
@Output() readonly dateChange: EventEmitter<MatDatepickerInputEvent<D, S>> = new EventEmitter<
MatDatepickerInputEvent<D, S>
>();
/** Emits when an `input` event is fired on this `<input>`. */
@Output() readonly dateInput: EventEmitter<MatDatepickerInputEvent<D, S>> = new EventEmitter<
MatDatepickerInputEvent<D, S>
>();
/** Emits when the internal state has changed */
readonly stateChanges = new Subject<void>();
_onTouched = () => {};
_validatorOnChange = () => {};
private _cvaOnChange: (value: any) => void = () => {};
private _valueChangesSubscription = Subscription.EMPTY;
private _localeSubscription = Subscription.EMPTY;
/**
* Since the value is kept on the model which is assigned in an Input,
* we might get a value before we have a model. This property keeps track
* of the value until we have somewhere to assign it.
*/
private _pendingValue: D | null;
/** The form control validator for whether the input parses. */
private _parseValidator: ValidatorFn = (): ValidationErrors | null => {
return this._lastValueValid
? null
: {'matDatepickerParse': {'text': this._elementRef.nativeElement.value}};
};
/** The form control validator for the date filter. */
private _filterValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const controlValue = this._dateAdapter.getValidDateOrNull(
this._dateAdapter.deserialize(control.value),
);
return !controlValue || this._matchesFilter(controlValue)
? null
: {'matDatepickerFilter': true};
};
/** The form control validator for the min date. */
private _minValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const controlValue = this._dateAdapter.getValidDateOrNull(
this._dateAdapter.deserialize(control.value),
);
const min = this._getMinDate();
return !min || !controlValue || this._dateAdapter.compareDate(min, controlValue) <= 0
? null
: {'matDatepickerMin': {'min': min, 'actual': controlValue}};
};
/** The form control validator for the max date. */
private _maxValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const controlValue = this._dateAdapter.getValidDateOrNull(
this._dateAdapter.deserialize(control.value),
);
const max = this._getMaxDate();
return !max || !controlValue || this._dateAdapter.compareDate(max, controlValue) >= 0
? null
: {'matDatepickerMax': {'max': max, 'actual': controlValue}};
};
/** Gets the base validator functions. */
protected _getValidators(): ValidatorFn[] {
return [this._parseValidator, this._minValidator, this._maxValidator, this._filterValidator];
}
/** Gets the minimum date for the input. Used for validation. */
abstract _getMinDate(): D | null;
/** Gets the maximum date for the input. Used for validation. */
abstract _getMaxDate(): D | null;
/** Gets the date filter function. Used for validation. */
protected abstract _getDateFilter(): DateFilterFn<D> | undefined;
/** Registers a date selection model with the input. */
_registerModel(model: MatDateSelectionModel<S, D>): void {
this._model = model;
this._valueChangesSubscription.unsubscribe();
if (this._pendingValue) {
this._assignValue(this._pendingValue);
}
this._valueChangesSubscription = this._model.selectionChanged.subscribe(event => {
if (this._shouldHandleChangeEvent(event)) {
const value = this._getValueFromModel(event.selection);
this._lastValueValid = this._isValidValue(value);
this._cvaOnChange(value);
this._onTouched();
this._formatValue(value);
this.dateInput.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
this.dateChange.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
}
});
}
/** Opens the popup associated with the input. */
protected abstract _openPopup(): void;
/** Assigns a value to the input's model. */
protected abstract _assignValueToModel(model: D | null): void;
/** Converts a value from the model into a native value for the input. */
protected abstract _getValueFromModel(modelValue: S): D | null;
/** Combined form control validator for this input. */
protected abstract _validator: ValidatorFn | null;
/** Predicate that determines whether the input should handle a particular change event. */
protected abstract _shouldHandleChangeEvent(event: DateSelectionModelChange<S>): boolean;
/** Whether the last value set on the input was valid. */
protected _lastValueValid = false;
constructor(
protected _elementRef: ElementRef<HTMLInputElement>,
@Optional() public _dateAdapter: DateAdapter<D>,
@Optional() @Inject(MAT_DATE_FORMATS) private _dateFormats: MatDateFormats,
) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this._dateAdapter) {
throw createMissingDateImplError('DateAdapter');
}
if (!this._dateFormats) {
throw createMissingDateImplError('MAT_DATE_FORMATS');
}
}
// Update the displayed date when the locale changes.
this._localeSubscription = _dateAdapter.localeChanges.subscribe(() => {
this._assignValueProgrammatically(this.value);
});
}
ngAfterViewInit() {
this._isInitialized = true;
}
ngOnChanges(changes: SimpleChanges) {
if (dateInputsHaveChanged(changes, this._dateAdapter)) {
this.stateChanges.next(undefined);
}
}
ngOnDestroy() {
this._valueChangesSubscription.unsubscribe();
this._localeSubscription.unsubscribe();
this.stateChanges.complete();
}
/** @docs-private */
registerOnValidatorChange(fn: () => void): void {
this._validatorOnChange = fn;
}
/** @docs-private */
validate(c: AbstractControl): ValidationErrors | null {
return this._validator ? this._validator(c) : null;
}
// Implemented as part of ControlValueAccessor.
writeValue(value: D): void {
this._assignValueProgrammatically(value);
}
// Implemented as part of ControlValueAccessor.
registerOnChange(fn: (value: any) => void): void {
this._cvaOnChange = fn;
}
// Implemented as part of ControlValueAccessor.
registerOnTouched(fn: () => void): void {
this._onTouched = fn;
}
// Implemented as part of ControlValueAccessor.
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
_onKeydown(event: KeyboardEvent) {
const isAltDownArrow = event.altKey && event.keyCode === DOWN_ARROW;
if (isAltDownArrow && !this._elementRef.nativeElement.readOnly) {
this._openPopup();
event.preventDefault();
}
}
_onInput(value: string) {
const lastValueWasValid = this._lastValueValid;
let date = this._dateAdapter.parse(value, this._dateFormats.parse.dateInput);
this._lastValueValid = this._isValidValue(date);
date = this._dateAdapter.getValidDateOrNull(date);
if (!this._dateAdapter.sameDate(date, this.value)) {
this._assignValue(date);
this._cvaOnChange(date);
this.dateInput.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
} else {
// Call the CVA change handler for invalid values
// since this is what marks the control as dirty.
if (value && !this.value) {
this._cvaOnChange(date);
}
if (lastValueWasValid !== this._lastValueValid) {
this._validatorOnChange();
}
}
}
_onChange() {
this.dateChange.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
}
/** Handles blur events on the input. */
_onBlur() {
// Reformat the input only if we have a valid value.
if (this.value) {
this._formatValue(this.value);
}
this._onTouched();
}
/** Formats a value and sets it on the input element. */
protected _formatValue(value: D | null) {
this._elementRef.nativeElement.value = value
? this._dateAdapter.format(value, this._dateFormats.display.dateInput)
: '';
}
/** Assigns a value to the model. */
private _assignValue(value: D | null) {
// We may get some incoming values before the model was
// assigned. Save the value so that we can assign it later.
if (this._model) {
this._assignValueToModel(value);
this._pendingValue = null;
} else {
this._pendingValue = value;
}
}
/** Whether a value is considered valid. */
private _isValidValue(value: D | null): boolean {
return !value || this._dateAdapter.isValid(value);
}
/**
* Checks whether a parent control is disabled. This is in place so that it can be overridden
* by inputs extending this one which can be placed inside of a group that can be disabled.
*/
protected _parentDisabled() {
return false;
}
/** Programmatically assigns a value to the input. */
protected _assignValueProgrammatically(value: D | null) {
value = this._dateAdapter.deserialize(value);
this._lastValueValid = this._isValidValue(value);
value = this._dateAdapter.getValidDateOrNull(value);
this._assignValue(value);
this._formatValue(value);
}
/** Gets whether a value matches the current date filter. */
_matchesFilter(value: D | null): boolean {
const filter = this._getDateFilter();
return !filter || filter(value);
}
}
/**
* Checks whether the `SimpleChanges` object from an `ngOnChanges`
* callback has any changes, accounting for date objects.
*/
export function dateInputsHaveChanged(
changes: SimpleChanges,
adapter: DateAdapter<unknown>,
): boolean {
const keys = Object.keys(changes);
for (let key of keys) {
const {previousValue, currentValue} = changes[key];
if (adapter.isDateInstance(previousValue) && adapter.isDateInstance(currentValue)) {
if (!adapter.sameDate(previousValue, currentValue)) {
return true;
}
} else {
return true;
}
}
return false;
} | the_stack |
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { resolve } from 'path';
import { chmodSync, statSync } from 'fs';
import del from 'del';
import { mkdirp, write, read, getChildPaths, copyAll, getFileHash, untar, gunzip } from '../fs';
const TMP = resolve(__dirname, '../__tmp__');
const FIXTURES = resolve(__dirname, '../__fixtures__');
const FOO_TAR_PATH = resolve(FIXTURES, 'foo_dir.tar.gz');
const FOO_GZIP_PATH = resolve(FIXTURES, 'foo.txt.gz');
const BAR_TXT_PATH = resolve(FIXTURES, 'foo_dir/bar.txt');
const WORLD_EXECUTABLE = resolve(FIXTURES, 'bin/world_executable');
const isWindows = /^win/.test(process.platform);
// get the mode of a file as a string, like 777, or 644,
function getCommonMode(path: string) {
return statSync(path).mode.toString(8).slice(-3);
}
function assertNonAbsoluteError(error: any) {
expect(error).toBeInstanceOf(Error);
expect(error.message).toContain('Please use absolute paths');
}
// ensure WORLD_EXECUTABLE is actually executable by all
beforeAll(async () => {
chmodSync(WORLD_EXECUTABLE, 0o777);
});
// clean and recreate TMP directory
beforeEach(async () => {
await del(TMP);
await mkdirp(TMP);
});
// cleanup TMP directory
afterAll(async () => {
await del(TMP);
});
describe('mkdirp()', () => {
it('rejects if path is not absolute', async () => {
try {
await mkdirp('foo/bar');
throw new Error('Expected mkdirp() to reject');
} catch (error) {
assertNonAbsoluteError(error);
}
});
it('makes directory and necessary parent directories', async () => {
const destination = resolve(TMP, 'a/b/c/d/e/f/g');
expect(await mkdirp(destination)).toBe(undefined);
expect(statSync(destination).isDirectory()).toBe(true);
});
});
describe('write()', () => {
it('rejects if path is not absolute', async () => {
try {
// @ts-expect-error missing content intentional
await write('foo/bar');
throw new Error('Expected write() to reject');
} catch (error) {
assertNonAbsoluteError(error);
}
});
it('writes content to a file with existing parent directory', async () => {
const destination = resolve(TMP, 'a');
expect(await write(destination, 'bar')).toBe(undefined);
expect(await read(destination)).toBe('bar');
});
it('writes content to a file with missing parents', async () => {
const destination = resolve(TMP, 'a/b/c/d/e');
expect(await write(destination, 'bar')).toBe(undefined);
expect(await read(destination)).toBe('bar');
});
});
describe('read()', () => {
it('rejects if path is not absolute', async () => {
try {
await read('foo/bar');
throw new Error('Expected read() to reject');
} catch (error) {
assertNonAbsoluteError(error);
}
});
it('reads file, resolves with result', async () => {
expect(await read(BAR_TXT_PATH)).toBe('bar\n');
});
});
describe('getChildPaths()', () => {
it('rejects if path is not absolute', async () => {
try {
await getChildPaths('foo/bar');
throw new Error('Expected getChildPaths() to reject');
} catch (error) {
assertNonAbsoluteError(error);
}
});
it('resolves with absolute paths to the children of directory', async () => {
const path = resolve(FIXTURES, 'foo_dir');
expect((await getChildPaths(path)).sort()).toEqual([
resolve(FIXTURES, 'foo_dir/.bar'),
BAR_TXT_PATH,
resolve(FIXTURES, 'foo_dir/foo'),
]);
});
it('rejects with ENOENT if path does not exist', async () => {
try {
await getChildPaths(resolve(FIXTURES, 'notrealpath'));
throw new Error('Expected getChildPaths() to reject');
} catch (error) {
expect(error).toHaveProperty('code', 'ENOENT');
}
});
});
describe('copyAll()', () => {
it('rejects if source path is not absolute', async () => {
try {
await copyAll('foo/bar', __dirname);
throw new Error('Expected copyAll() to reject');
} catch (error) {
assertNonAbsoluteError(error);
}
});
it('rejects if destination path is not absolute', async () => {
try {
await copyAll(__dirname, 'foo/bar');
throw new Error('Expected copyAll() to reject');
} catch (error) {
assertNonAbsoluteError(error);
}
});
it('rejects if neither path is not absolute', async () => {
try {
await copyAll('foo/bar', 'foo/bar');
throw new Error('Expected copyAll() to reject');
} catch (error) {
assertNonAbsoluteError(error);
}
});
it.skip('copies files and directories from source to dest, creating dest if necessary, respecting mode', async () => {
const path777 = resolve(FIXTURES, 'bin/world_executable');
const path644 = resolve(FIXTURES, 'foo_dir/bar.txt');
// we're seeing flaky failures because the resulting files sometimes have
// 755 permissions. Unless there's a bug in vinyl-fs I can't figure out
// where the issue might be, so trying to validate the mode first to narrow
// down where the issue might be
expect(getCommonMode(path777)).toBe(isWindows ? '666' : '777');
expect(getCommonMode(path644)).toBe(isWindows ? '666' : '644');
const destination = resolve(TMP, 'a/b/c');
await copyAll(FIXTURES, destination);
expect((await getChildPaths(resolve(destination, 'foo_dir'))).sort()).toEqual([
resolve(destination, 'foo_dir/bar.txt'),
resolve(destination, 'foo_dir/foo'),
]);
expect(getCommonMode(path777)).toBe(isWindows ? '666' : '777');
expect(getCommonMode(path644)).toBe(isWindows ? '666' : '644');
});
it('applies select globs if specified, ignores dot files', async () => {
const destination = resolve(TMP, 'a/b/c/d');
await copyAll(FIXTURES, destination, {
select: ['**/*bar*'],
});
try {
statSync(resolve(destination, 'bin/world_executable'));
throw new Error('expected bin/world_executable to not by copied');
} catch (error) {
expect(error).toHaveProperty('code', 'ENOENT');
}
try {
statSync(resolve(destination, 'foo_dir/.bar'));
throw new Error('expected foo_dir/.bar to not by copied');
} catch (error) {
expect(error).toHaveProperty('code', 'ENOENT');
}
expect(await read(resolve(destination, 'foo_dir/bar.txt'))).toBe('bar\n');
});
it('supports select globs and dot option together', async () => {
const destination = resolve(TMP, 'a/b/c/d');
await copyAll(FIXTURES, destination, {
select: ['**/*bar*'],
dot: true,
});
try {
statSync(resolve(destination, 'bin/world_executable'));
throw new Error('expected bin/world_executable to not by copied');
} catch (error) {
expect(error).toHaveProperty('code', 'ENOENT');
}
expect(await read(resolve(destination, 'foo_dir/bar.txt'))).toBe('bar\n');
expect(await read(resolve(destination, 'foo_dir/.bar'))).toBe('dotfile\n');
});
it('supports atime and mtime', async () => {
const destination = resolve(TMP, 'a/b/c/d/e');
const time = new Date(1425298511000);
await copyAll(FIXTURES, destination, {
time,
});
const barTxt = statSync(resolve(destination, 'foo_dir/bar.txt'));
const fooDir = statSync(resolve(destination, 'foo_dir'));
// precision is platform specific
const oneDay = 86400000;
expect(Math.abs(barTxt.atimeMs - time.getTime())).toBeLessThan(oneDay);
expect(Math.abs(fooDir.atimeMs - time.getTime())).toBeLessThan(oneDay);
expect(Math.abs(barTxt.mtimeMs - time.getTime())).toBeLessThan(oneDay);
});
});
describe('getFileHash()', () => {
it('rejects if path is not absolute', async () => {
try {
await getFileHash('foo/bar', 'some content');
throw new Error('Expected getFileHash() to reject');
} catch (error) {
assertNonAbsoluteError(error);
}
});
it('resolves with the sha1 hash of a file', async () => {
expect(await getFileHash(BAR_TXT_PATH, 'sha1')).toBe(
'e242ed3bffccdf271b7fbaf34ed72d089537b42f'
);
});
it('resolves with the sha256 hash of a file', async () => {
expect(await getFileHash(BAR_TXT_PATH, 'sha256')).toBe(
'7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730'
);
});
it('resolves with the md5 hash of a file', async () => {
expect(await getFileHash(BAR_TXT_PATH, 'md5')).toBe('c157a79031e1c40f85931829bc5fc552');
});
});
describe('untar()', () => {
it('rejects if source path is not absolute', async () => {
try {
await untar('foo/bar', '**/*');
throw new Error('Expected untar() to reject');
} catch (error) {
assertNonAbsoluteError(error);
}
});
it('rejects if destination path is not absolute', async () => {
try {
await untar(__dirname, '**/*');
throw new Error('Expected untar() to reject');
} catch (error) {
assertNonAbsoluteError(error);
}
});
it('rejects if neither path is not absolute', async () => {
try {
await untar('foo/bar', '**/*');
throw new Error('Expected untar() to reject');
} catch (error) {
assertNonAbsoluteError(error);
}
});
it('extracts tarbar from source into destination, creating destination if necessary', async () => {
const destination = resolve(TMP, 'a/b/c/d/e/f');
await untar(FOO_TAR_PATH, destination);
expect(await read(resolve(destination, 'foo_dir/bar.txt'))).toBe('bar\n');
expect(await read(resolve(destination, 'foo_dir/foo/foo.txt'))).toBe('foo\n');
});
it('passed thrid argument to Extract class, overriding path with destination', async () => {
const destination = resolve(TMP, 'a/b/c');
await untar(FOO_TAR_PATH, destination, {
path: '/dev/null',
strip: 1,
});
expect(await read(resolve(destination, 'bar.txt'))).toBe('bar\n');
expect(await read(resolve(destination, 'foo/foo.txt'))).toBe('foo\n');
});
});
describe('gunzip()', () => {
it('rejects if source path is not absolute', async () => {
try {
await gunzip('foo/bar', '**/*');
throw new Error('Expected gunzip() to reject');
} catch (error) {
assertNonAbsoluteError(error);
}
});
it('rejects if destination path is not absolute', async () => {
try {
await gunzip(__dirname, '**/*');
throw new Error('Expected gunzip() to reject');
} catch (error) {
assertNonAbsoluteError(error);
}
});
it('rejects if neither path is not absolute', async () => {
try {
await gunzip('foo/bar', '**/*');
throw new Error('Expected gunzip() to reject');
} catch (error) {
assertNonAbsoluteError(error);
}
});
it('extracts gzip from source into destination, creating destination if necessary', async () => {
const destination = resolve(TMP, 'z/y/x/v/u/t/foo.txt');
await gunzip(FOO_GZIP_PATH, destination);
expect(await read(resolve(destination))).toBe('foo\n');
});
}); | the_stack |
interface AttributeProps {
name: string;
size: number;
data?: any;
}
interface UniformProps {
type: string;
value: Array<number>;
location?: WebGLUniformLocation;
}
interface GeometryProps {
vertices?: Array<Array<object>>;
normal?: Array<Array<object>>;
}
interface BufferProps {
location: number;
buffer: WebGLBuffer;
size: number;
}
interface InstanceProps {
attributes?: Array<AttributeProps>;
vertex?: string;
fragment?: string;
geometry?: GeometryProps;
mode?: number;
modifiers?: object;
multiplier?: number;
uniforms: {
[key: string]: UniformProps;
};
}
interface RendererProps {
canvas?: HTMLCanvasElement;
context?: object;
contextType?: string;
settings?: object;
debug?: boolean;
}
const positionMap = ['x', 'y', 'z'];
/**
* Class representing an instance.
*/
class Instance {
public gl: WebGLRenderingContext;
public vertex: string;
public fragment: string;
public program: WebGLProgram;
public uniforms: {
[key: string]: UniformProps;
};
public geometry: GeometryProps;
public attributes: Array<AttributeProps>;
public attributeKeys: Array<string>;
public multiplier: number;
public modifiers: Array<Function>;
public buffers: Array<BufferProps>;
public uniformMap: object;
public mode: number;
public onRender?: Function;
/**
* Create an instance.
*/
constructor(props: InstanceProps) {
// Assign default parameters
Object.assign(this, {
uniforms: {},
geometry: { vertices: [{ x: 0, y: 0, z: 0 }] },
mode: 0,
modifiers: {},
attributes: [],
multiplier: 1,
buffers: [],
});
// Assign optional parameters
Object.assign(this, props);
// Prepare all required pieces
this.prepareProgram();
this.prepareUniforms();
this.prepareAttributes();
}
/**
* Compile a shader.
*/
compileShader(type: number, source: string) {
const shader = this.gl.createShader(type);
this.gl.shaderSource(shader, source);
this.gl.compileShader(shader);
return shader;
}
/**
* Create a program.
*/
prepareProgram() {
const { gl, vertex, fragment } = this;
// Create a new shader program
const program = gl.createProgram();
// Attach the vertex shader
gl.attachShader(program, this.compileShader(35633, vertex));
// Attach the fragment shader
gl.attachShader(program, this.compileShader(35632, fragment));
// Link the program
gl.linkProgram(program);
// Use the program
gl.useProgram(program);
// Assign it to the instance
this.program = program;
}
/**
* Create uniforms.
*/
prepareUniforms() {
const keys = Object.keys(this.uniforms);
for (let i = 0; i < keys.length; i += 1) {
const location = this.gl.getUniformLocation(this.program, keys[i]);
this.uniforms[keys[i]].location = location;
}
}
/**
* Create buffer attributes.
*/
prepareAttributes() {
if (typeof this.geometry.vertices !== 'undefined') {
this.attributes.push({
name: 'aPosition',
size: 3,
});
}
if (typeof this.geometry.normal !== 'undefined') {
this.attributes.push({
name: 'aNormal',
size: 3,
});
}
this.attributeKeys = [];
// Convert all attributes to be useable in the shader
for (let i = 0; i < this.attributes.length; i += 1) {
this.attributeKeys.push(this.attributes[i].name);
this.prepareAttribute(this.attributes[i]);
}
}
/**
* Prepare a single attribute.
*/
prepareAttribute(attribute: AttributeProps) {
const { geometry, multiplier } = this;
const { vertices, normal } = geometry;
// Create an array for the attribute to store data
const attributeBufferData = new Float32Array(multiplier * vertices.length * attribute.size);
// Repeat the process for the provided multiplier
for (let j = 0; j < multiplier; j += 1) {
// Set data used as default or the attribute modifier
const data = attribute.data && attribute.data(j, multiplier);
// Calculate the offset for the right place in the array
let offset = j * vertices.length * attribute.size;
// Loop over vertices length
for (let k = 0; k < vertices.length; k += 1) {
// Loop over attribute size
for (let l = 0; l < attribute.size; l += 1) {
// Check if a modifier is provided
const modifier = this.modifiers[attribute.name];
if (typeof modifier !== 'undefined') {
// Handle attribute modifier
attributeBufferData[offset] = modifier(data, k, l, this);
} else if (attribute.name === 'aPosition') {
// Handle position values
attributeBufferData[offset] = vertices[k][positionMap[l]];
} else if (attribute.name === 'aNormal') {
// Handle normal values
attributeBufferData[offset] = normal[k][positionMap[l]];
} else {
// Handle other attributes
attributeBufferData[offset] = data[l];
}
offset += 1;
}
}
}
this.attributes[this.attributeKeys.indexOf(attribute.name)].data = attributeBufferData;
this.prepareBuffer(this.attributes[this.attributeKeys.indexOf(attribute.name)]);
}
/**
* Create a buffer with an attribute.
*/
prepareBuffer(attribute: AttributeProps) {
const { data, name, size } = attribute;
const buffer = this.gl.createBuffer();
this.gl.bindBuffer(34962, buffer);
this.gl.bufferData(34962, data, 35044);
const location = this.gl.getAttribLocation(this.program, name);
this.gl.enableVertexAttribArray(location);
this.gl.vertexAttribPointer(location, size, 5126, false, 0, 0);
this.buffers[this.attributeKeys.indexOf(attribute.name)] = { buffer, location, size };
}
/**
* Render the instance.
*/
render(renderUniforms: object) {
const { uniforms, multiplier, gl } = this;
// Use the program of the instance
gl.useProgram(this.program);
// Bind the buffers for the instance
for (let i = 0; i < this.buffers.length; i += 1) {
const { location, buffer, size } = this.buffers[i];
gl.enableVertexAttribArray(location);
gl.bindBuffer(34962, buffer);
gl.vertexAttribPointer(location, size, 5126, false, 0, 0);
}
// Update the shared uniforms from the renderer
Object.keys(renderUniforms).forEach(key => {
uniforms[key].value = renderUniforms[key].value;
});
// Map the uniforms to the context
Object.keys(uniforms).forEach(key => {
const { type, location, value } = uniforms[key];
this.uniformMap[type](location, value);
});
// Draw the magic to the screen
gl.drawArrays(this.mode, 0, multiplier * this.geometry.vertices.length);
// Hook for uniform updates
if (this.onRender) this.onRender(this);
}
/**
* Destroy the instance.
*/
destroy() {
for (let i = 0; i < this.buffers.length; i += 1) {
this.gl.deleteBuffer(this.buffers[i].buffer);
}
this.gl.deleteProgram(this.program);
this.gl = null;
}
}
/**
* Class representing a Renderer.
*/
class Renderer {
public clearColor: Array<GLclampf>;
public onRender: Function;
public onSetup: Function;
public uniformMap: object;
public gl: WebGLRenderingContext;
public canvas: HTMLCanvasElement;
public devicePixelRatio: number;
public clip: Array<number>;
public instances: Map<string, Instance>;
public position: {
x: number;
y: number;
z: number;
};
public uniforms: {
[key: string]: UniformProps;
};
public shouldRender: boolean;
public debug: boolean;
/**
* Create a renderer.
*/
constructor(props: RendererProps) {
const {
canvas = document.querySelector('canvas'),
context = {},
contextType = 'experimental-webgl',
settings = {},
debug = false,
} = props || {};
// Get context with optional parameters
const gl = <WebGLRenderingContext>canvas.getContext(
contextType,
Object.assign(
{
alpha: false,
antialias: false,
},
context
)
);
// Assign program parameters
Object.assign(this, {
gl,
canvas,
uniforms: {},
instances: new Map(),
shouldRender: true,
});
// Assign default parameters
Object.assign(this, {
devicePixelRatio: 1,
clearColor: [1, 1, 1, 1],
position: { x: 0, y: 0, z: 2 },
clip: [0.001, 100],
debug,
});
// Assign optional parameters
Object.assign(this, settings);
// Create uniform mapping object
this.uniformMap = {
float: (loc, val) => gl.uniform1f(loc, val),
vec2: (loc, val) => gl.uniform2fv(loc, val),
vec3: (loc, val) => gl.uniform3fv(loc, val),
vec4: (loc, val) => gl.uniform4fv(loc, val),
mat2: (loc, val) => gl.uniformMatrix2fv(loc, false, val),
mat3: (loc, val) => gl.uniformMatrix3fv(loc, false, val),
mat4: (loc, val) => gl.uniformMatrix4fv(loc, false, val),
};
// Enable depth
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
// Set clear values
if (gl.getContextAttributes().alpha === false) {
// @ts-ignore
gl.clearColor(...this.clearColor);
gl.clearDepth(1.0);
}
// Hook for gl context changes before first render
if (this.onSetup) this.onSetup(gl);
// Handle resize events
window.addEventListener('resize', () => this.resize());
// Start the renderer
this.resize();
this.render();
}
/**
* Handle resize events.
*/
resize() {
const { gl, canvas, devicePixelRatio, position } = this;
canvas.width = canvas.clientWidth * devicePixelRatio;
canvas.height = canvas.clientHeight * devicePixelRatio;
const bufferWidth = gl.drawingBufferWidth;
const bufferHeight = gl.drawingBufferHeight;
const ratio = bufferWidth / bufferHeight;
gl.viewport(0, 0, bufferWidth, bufferHeight);
const angle = Math.tan(45 * 0.5 * (Math.PI / 180));
// prettier-ignore
const projectionMatrix = [
0.5 / angle, 0, 0, 0,
0, 0.5 * (ratio / angle), 0, 0,
0, 0, -(this.clip[1] + this.clip[0]) / (this.clip[1] - this.clip[0]), -1, 0, 0,
-2 * this.clip[1] * (this.clip[0] / (this.clip[1] - this.clip[0])), 0,
];
// prettier-ignore
const viewMatrix = [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
];
// prettier-ignore
const modelMatrix = [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
position.x, position.y, (ratio < 1 ? 1 : ratio) * -position.z, 1,
];
this.uniforms.uProjectionMatrix = {
type: 'mat4',
value: projectionMatrix,
};
this.uniforms.uViewMatrix = {
type: 'mat4',
value: viewMatrix,
};
this.uniforms.uModelMatrix = {
type: 'mat4',
value: modelMatrix,
};
}
/**
* Toggle the active state of the renderer.
*/
toggle(shouldRender: boolean) {
if (shouldRender === this.shouldRender) return;
this.shouldRender = typeof shouldRender !== 'undefined' ? shouldRender : !this.shouldRender;
if (this.shouldRender) this.render();
}
/**
* Render the total scene.
*/
render() {
this.gl.clear(16640);
this.instances.forEach(instance => {
instance.render(this.uniforms);
});
if (this.onRender) this.onRender(this);
if (this.shouldRender) requestAnimationFrame(() => this.render());
}
/**
* Add an instance to the renderer.
*/
add(key: string, settings: InstanceProps) {
if (typeof settings === 'undefined') {
settings = { uniforms: {} };
}
if (typeof settings.uniforms === 'undefined') {
settings.uniforms = {};
}
Object.assign(settings.uniforms, JSON.parse(JSON.stringify(this.uniforms)));
Object.assign(settings, {
gl: this.gl,
uniformMap: this.uniformMap,
});
const instance = new Instance(settings);
this.instances.set(key, instance);
if (this.debug) {
// debug vertex shader
const vertexDebug = this.gl.createShader(this.gl.VERTEX_SHADER);
this.gl.shaderSource(vertexDebug, settings.vertex);
this.gl.compileShader(vertexDebug);
if (!this.gl.getShaderParameter(vertexDebug, this.gl.COMPILE_STATUS)) {
console.error(this.gl.getShaderInfoLog(vertexDebug));
}
// debug fragment shader
const fragmentDebug = this.gl.createShader(this.gl.FRAGMENT_SHADER);
this.gl.shaderSource(fragmentDebug, settings.fragment);
this.gl.compileShader(fragmentDebug);
if (!this.gl.getShaderParameter(fragmentDebug, this.gl.COMPILE_STATUS)) {
console.error(this.gl.getShaderInfoLog(fragmentDebug));
}
}
return instance;
}
/**
* Remove an instance from the renderer.
*/
remove(key: string) {
const instance = this.instances.get(key);
if (typeof instance === 'undefined') return;
instance.destroy();
this.instances.delete(key);
}
/**
* Destroy the renderer and its instances.
*/
destroy() {
this.instances.forEach((instance, key) => {
instance.destroy();
this.instances.delete(key);
});
this.toggle(false);
}
}
export default Renderer; | the_stack |
import { TextEditor, Disposable } from 'atom';
import * as path from 'path';
import View from './view';
import { validator, loadFile } from './validator';
import { Shader, SoundShader, OscData, Pass } from './constants';
import Config, { RcDiff } from './config';
import { Playable } from './playable';
import Player from './player';
import PlayerServer from './player-server';
import { INITIAL_SHADER, INITIAL_SOUND_SHADER } from './constants';
import OscLoader from './osc-loader';
import Recorder, { RecordingMode } from './recorder';
import * as glslify from 'glslify-lite';
import * as prebuilt from 'glslang-validator-prebuilt';
interface AppState {
isPlaying: boolean;
activeEditorDisposer?: Disposable;
editorDisposer?: Disposable;
editor?: TextEditor;
}
export default class App {
private player: Playable;
private view: View | null = null;
private state: AppState;
private glslangValidatorPath: string = prebuilt.path;
private lastShader: Shader = INITIAL_SHADER;
private lastSoundShader: SoundShader = INITIAL_SOUND_SHADER;
private osc: OscLoader | null = null;
private recorder: Recorder = new Recorder();
private config: Config;
public constructor(config: Config) {
const rc = config.rc;
this.view = new View((atom.workspace as any).getElement()); // eslint-disable-line
this.player = new Player(this.view, rc, false, this.lastShader);
this.config = config;
this.config.on('change', this.onChange);
this.state = {
isPlaying: false,
};
}
public destroy(): void {
this.player.destroy();
if (this.osc) {
this.osc.destroy();
}
}
private onAnyChanges = ({ added }: RcDiff): void => {
if (added.glslangValidatorPath) {
this.glslangValidatorPath = added.glslangValidatorPath;
}
if (added.server !== undefined) {
if (this.player) {
this.player.command({ type: 'STOP' });
}
const rc = this.config.createRc();
if (added.server) {
if (this.view !== null) {
this.view.destroy();
}
this.player = new PlayerServer(added.server, {
rc,
isPlaying: this.state.isPlaying,
projectPath: this.config.projectPath,
lastShader: this.lastShader,
});
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.view = new View((atom.workspace as any).element);
this.player = new Player(
this.view,
rc,
this.state.isPlaying,
this.lastShader,
);
}
}
if (added.osc !== undefined) {
const port = added.osc;
const osc = this.osc;
if (osc && (!port || osc.port !== parseInt(port.toString(), 10))) {
osc.destroy();
this.osc = null;
}
if (port && !this.osc) {
const oscLoader = new OscLoader(port);
this.osc = oscLoader;
oscLoader.on('message', this.onOsc);
oscLoader.on('reload', (): void => this.loadLastShader());
}
}
};
private onChange = (rcDiff: RcDiff): void => {
this.onAnyChanges(rcDiff);
this.player.onChange(rcDiff);
this.loadLastShader();
this.loadLastSoundShader();
};
private onOsc = (data: OscData): void => {
this.player.command({ type: 'SET_OSC', data });
};
public toggle(): void {
return this.state.isPlaying ? this.stop() : this.play();
}
public play(): void {
this.state.isPlaying = true;
this.player.command({ type: 'PLAY' });
this.config.play();
}
public stop(): void {
this.state.isPlaying = false;
this.player.command({ type: 'STOP' });
this.player.command({ type: 'STOP_SOUND' });
this.config.stop();
this.stopWatching();
this.stopRecording();
}
public watchActiveShader(): void {
if (this.state.activeEditorDisposer) {
return;
}
this.watchShader();
this.state.activeEditorDisposer = atom.workspace.onDidChangeActiveTextEditor(
(): void => {
this.watchShader();
},
);
}
public watchShader(): void {
if (this.state.editorDisposer) {
this.state.editorDisposer.dispose();
this.state.editorDisposer = undefined;
}
const editor = atom.workspace.getActiveTextEditor();
this.state.editor = editor;
this.loadShaderOfEditor(editor);
if (editor !== undefined) {
this.state.editorDisposer = editor.onDidStopChanging((): void => {
this.loadShaderOfEditor(editor);
});
}
}
public loadShader(): void {
const editor = atom.workspace.getActiveTextEditor();
this.loadShaderOfEditor(editor);
}
public loadSoundShader(): Promise<void> {
const editor = atom.workspace.getActiveTextEditor();
return this.loadShaderOfEditor(editor, true);
}
public playSound(): void {
this.loadSoundShader().then((): void =>
this.player.command({ type: 'PLAY_SOUND' }),
);
}
public stopSound(): void {
this.player.command({ type: 'STOP_SOUND' });
}
private loadLastShader(): void {
if (!this.lastShader) {
return;
}
this.player.command({ type: 'LOAD_SHADER', shader: this.lastShader });
}
private loadLastSoundShader(): void {
if (!this.lastSoundShader) {
return;
}
this.player.command({
type: 'LOAD_SOUND_SHADER',
shader: this.lastSoundShader,
});
}
public stopWatching(): void {
this.state.editor = undefined;
if (this.state.activeEditorDisposer) {
this.state.activeEditorDisposer.dispose();
this.state.activeEditorDisposer = undefined;
}
if (this.state.editorDisposer) {
this.state.editorDisposer.dispose();
this.state.editorDisposer = undefined;
}
}
private createPasses(
rcPasses: Pass[],
openedShader: string,
openedFilepath: string,
extension: string,
dirname: string,
useGlslify: boolean,
isGLSL3: boolean,
): Promise<Pass[]> {
if (rcPasses.length === 0) {
rcPasses.push({});
}
const finalPass = rcPasses.length - 1;
return Promise.all(
rcPasses.map(async (rcPass, i) => {
const pass: Pass = {
MODEL: rcPass.MODEL,
TARGET: rcPass.TARGET,
FLOAT: rcPass.FLOAT,
WIDTH: rcPass.WIDTH,
HEIGHT: rcPass.HEIGHT,
BLEND: rcPass.BLEND,
GLSL3: isGLSL3,
};
if (!rcPass.fs && !rcPass.vs) {
if (extension === '.vert' || extension === '.vs') {
pass.vs = openedShader;
} else {
pass.fs = openedShader;
}
} else {
// TODO: load from editor if the file is same as opened file
if (rcPass.vs) {
const filepath = path.resolve(dirname, rcPass.vs);
if (filepath === openedFilepath) {
pass.vs = openedShader;
} else {
pass.vs = await loadFile(
this.glslangValidatorPath,
filepath,
useGlslify,
);
}
if (
i === finalPass &&
(extension === '.frag' || extension === '.fs')
) {
pass.fs = openedShader;
}
}
if (rcPass.fs) {
const filepath = path.resolve(dirname, rcPass.fs);
if (filepath === openedFilepath) {
pass.fs = openedShader;
} else {
pass.fs = await loadFile(
this.glslangValidatorPath,
filepath,
useGlslify,
);
}
if (
i === finalPass &&
(extension === '.vert' || extension === '.vs')
) {
pass.vs = openedShader;
}
}
}
return pass;
}),
);
}
private async loadShaderOfEditor(
editor?: TextEditor,
isSound?: boolean,
): Promise<void> {
// Do nothing if no files are open/active
if (editor === undefined) {
return;
}
const filepath = editor.getPath();
if (filepath === undefined) {
return;
}
const dirname = path.dirname(filepath);
const m = (filepath || '').match(/(\.(?:glsl|frag|vert|fs|vs))$/);
if (!m) {
console.error("The filename for current doesn't seems to be GLSL.");
return Promise.resolve();
}
const extension = m[1];
let shader = editor.getText();
try {
// Detect changes of settings
let headComment = (shader.match(
/(?:\/\*)((?:.|\n|\r|\n\r)*?)(?:\*\/)/,
) || [])[1];
headComment = headComment || '{}'; // suppress JSON5 parse errors
let diff;
if (isSound) {
diff = this.config.setSoundSettingsByString(
filepath,
headComment,
);
} else {
diff = this.config.setFileSettingsByString(
filepath,
headComment,
);
}
const rc = diff.newConfig;
this.onAnyChanges(diff);
this.player.onChange(diff);
// Compile the shader with glslify-lite
if (rc.glslify) {
shader = await glslify.compile(shader, {
basedir: path.dirname(filepath),
});
}
// Validate compiled shader
if (!isSound) {
await validator(this.glslangValidatorPath, shader, extension);
}
const matcharray =
shader.split('\n')[0].match(/(#version 300 es)/) || [];
const isGLSL3 = !!matcharray[0];
const passes = await this.createPasses(
rc.PASSES,
shader,
filepath,
extension,
dirname,
rc.glslify,
isGLSL3,
);
if (isSound) {
this.lastSoundShader = shader;
return this.player.command({
type: 'LOAD_SOUND_SHADER',
shader,
});
} else {
this.lastShader = passes;
return this.player.command({
type: 'LOAD_SHADER',
shader: passes,
});
}
} catch (e) {
console.error(e);
}
}
public toggleFullscreen(): void {
this.player.command({ type: 'TOGGLE_FULLSCREEN' });
}
public async startRecording(): Promise<void> {
if (this.view === null) {
return;
}
const canvas = this.view.getCanvas();
const fps = 60 / this.config.rc.frameskip;
const width = canvas.offsetWidth; // We don't consider pixelRatio here so that outputs don't get gigantic
const height = canvas.offsetHeight;
const dst = this.config.projectPath;
this.player.command({ type: 'START_RECORDING' });
this.recorder.start(canvas, fps, width, height, dst);
}
public async stopRecording(): Promise<void> {
this.recorder.stop();
this.player.command({ type: 'STOP_RECORDING' });
}
public setRecordingMode(mode: RecordingMode): void {
this.recorder.setRecordingMode(mode);
}
public insertTime(): void {
this.player.query({ type: 'TIME' }).then(
(time: number): void => {
const editor = atom.workspace.getActiveTextEditor();
if (editor) {
editor.insertText(time.toString());
}
},
(err: string): void => {
console.error(err);
atom.notifications.addError('[VEDA] Failed to get time.');
},
);
}
} | the_stack |
"use strict";
import assert = require("assert");
import fs = require("fs");
import mkdirp = require("mkdirp");
import path = require("path");
import slash = require("slash");
import { Platform, PluginTestingFramework, ProjectManager, setupTestRunScenario, setupUpdateScenario, ServerUtil, TestBuilder, TestConfig, TestUtil } from "code-push-plugin-testing-framework";
import Q = require("q");
import del = require("del");
//////////////////////////////////////////////////////////////////////////////////////////
// Create the platforms to run the tests on.
interface RNPlatform {
/**
* Returns the name of the bundle to be created for this platform.
*/
getBundleName(): string;
/**
* Returns whether or not this platform supports diffs.
*/
isDiffsSupported(): boolean;
/**
* Returns the path to the binary of the given project on this platform.
*/
getBinaryPath(projectDirectory: string): string;
/**
* Installs the platform on the given project.
*/
installPlatform(projectDirectory: string): Q.Promise<void>;
/**
* Installs the binary of the given project on this platform.
*/
installApp(projectDirectory: string): Q.Promise<void>;
/**
* Builds the binary of the project on this platform.
*/
buildApp(projectDirectory: string): Q.Promise<void>;
}
class RNAndroid extends Platform.Android implements RNPlatform {
constructor() {
super(new Platform.AndroidEmulatorManager());
}
/**
* Returns the name of the bundle to be created for this platform.
*/
getBundleName(): string {
return "index.android.bundle";
}
/**
* Returns whether or not this platform supports diffs.
*/
isDiffsSupported(): boolean {
return false;
}
/**
* Returns the path to the binary of the given project on this platform.
*/
getBinaryPath(projectDirectory: string): string {
return path.join(projectDirectory, TestConfig.TestAppName, "android", "app", "build", "outputs", "apk", "release", "app-release.apk");
}
/**
* Installs the platform on the given project.
*/
installPlatform(projectDirectory: string): Q.Promise<void> {
const innerprojectDirectory: string = path.join(projectDirectory, TestConfig.TestAppName);
const gradleContent: string = slash(path.join(innerprojectDirectory, "node_modules", "react-native-code-push", "android", "codepush.gradle"));
//// Set up gradle to build CodePush with the app
// Add CodePush to android/app/build.gradle
const buildGradle = path.join(innerprojectDirectory, "android", "app", "build.gradle");
TestUtil.replaceString(buildGradle,
"apply from: \"../../node_modules/react-native/react.gradle\"",
"apply from: \"../../node_modules/react-native/react.gradle\"\napply from: \"" + gradleContent + "\"");
// Add CodePush to android/settings.gradle
const settingsGradle = path.join(innerprojectDirectory, "android", "settings.gradle");
TestUtil.replaceString(settingsGradle,
"include ':app'",
"include ':app', ':react-native-code-push'\nproject(':react-native-code-push').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-code-push/android/app')");
//// Set the app version to 1.0.0 instead of 1.0
// Set the app version to 1.0.0 in android/app/build.gradle
TestUtil.replaceString(buildGradle, "versionName \"1.0\"", "versionName \"1.0.0\"");
// Set the app version to 1.0.0 in AndroidManifest.xml
TestUtil.replaceString(path.join(innerprojectDirectory, "android", "app", "src", "main", "AndroidManifest.xml"), "android:versionName=\"1.0\"", "android:versionName=\"1.0.0\"");
//// Replace the MainApplication.java with the correct server url and deployment key
const string = path.join(innerprojectDirectory, "android", "app", "src", "main", "res", "values", "strings.xml");
const AndroidManifest = path.join(innerprojectDirectory, "android", "app", "src", "main", "AndroidManifest.xml");
TestUtil.replaceString(string, TestUtil.SERVER_URL_PLACEHOLDER, this.getServerUrl());
TestUtil.replaceString(string, TestUtil.ANDROID_KEY_PLACEHOLDER, this.getDefaultDeploymentKey());
TestUtil.replaceString(AndroidManifest, "android:allowBackup=\"false\"", "android:allowBackup=\"false\"" + "\n\t" + "android:usesCleartextTraffic=\"true\"");
return Q<void>(null);
}
/**
* Installs the binary of the given project on this platform.
*/
installApp(projectDirectory: string): Q.Promise<void> {
const androidDirectory: string = path.join(projectDirectory, TestConfig.TestAppName, "android");
return TestUtil.getProcessOutput("adb install -r " + this.getBinaryPath(projectDirectory), { cwd: androidDirectory }).then(() => { return null; });
}
/**
* Build function of the test application, the command depends on the OS
*/
buildFunction(androidDirectory: string): Q.Promise<void> {
if (process.platform === "darwin") {
return TestUtil.getProcessOutput(`./gradlew assembleRelease --daemon`, { noLogStdOut: true, cwd: androidDirectory })
.then(() => { return null; });
} else {
return TestUtil.getProcessOutput(`gradlew assembleRelease --daemon`, { noLogStdOut: true, cwd: androidDirectory })
.then(() => { return null; });
}
}
/**
* Builds the binary of the project on this platform.
*/
buildApp(projectDirectory: string): Q.Promise<void> {
// In order to run on Android without the package manager, we must create a release APK and then sign it with the debug certificate.
const androidDirectory: string = path.join(projectDirectory, TestConfig.TestAppName, "android");
// If the build fails for the first time, try rebuild app again
try {
return this.buildFunction(androidDirectory);
} catch {
return this.buildFunction(androidDirectory);
}
}
}
class RNIOS extends Platform.IOS implements RNPlatform {
constructor() {
super(new Platform.IOSEmulatorManager());
}
/**
* Returns the name of the bundle to be created for this platform.
*/
getBundleName(): string {
return "main.jsbundle";
}
/**
* Returns whether or not this platform supports diffs.
*/
isDiffsSupported(): boolean {
return true;
}
/**
* Returns the path to the binary of the given project on this platform.
*/
getBinaryPath(projectDirectory: string): string {
return path.join(projectDirectory, TestConfig.TestAppName, "ios", "build", "Build", "Products", "Release-iphonesimulator", TestConfig.TestAppName + ".app");
}
/**
* Installs the platform on the given project.
*/
installPlatform(projectDirectory: string): Q.Promise<void> {
const iOSProject: string = path.join(projectDirectory, TestConfig.TestAppName, "ios");
const infoPlistPath: string = path.join(iOSProject, TestConfig.TestAppName, "Info.plist");
const appDelegatePath: string = path.join(iOSProject, TestConfig.TestAppName, "AppDelegate.m");
// Install the Podfile
return TestUtil.getProcessOutput("pod install", { cwd: iOSProject })
// Put the IOS deployment key in the Info.plist
.then(TestUtil.replaceString.bind(undefined, infoPlistPath,
"</dict>\n</plist>",
"<key>CodePushDeploymentKey</key>\n\t<string>" + this.getDefaultDeploymentKey() + "</string>\n\t<key>CodePushServerURL</key>\n\t<string>" + this.getServerUrl() + "</string>\n\t</dict>\n</plist>"))
// Set the app version to 1.0.0 instead of 1.0 in the Info.plist
.then(TestUtil.replaceString.bind(undefined, infoPlistPath, "1.0", "1.0.0"))
// Fix the linker flag list in project.pbxproj (pod install adds an extra comma)
.then(TestUtil.replaceString.bind(undefined, path.join(iOSProject, TestConfig.TestAppName + ".xcodeproj", "project.pbxproj"),
"\"[$][(]inherited[)]\",\\s*[)];", "\"$(inherited)\"\n\t\t\t\t);"))
// Add the correct bundle identifier
.then(TestUtil.replaceString.bind(undefined, path.join(iOSProject, TestConfig.TestAppName + ".xcodeproj", "project.pbxproj"),
"PRODUCT_BUNDLE_IDENTIFIER = [^;]*", "PRODUCT_BUNDLE_IDENTIFIER = \"" + TestConfig.TestNamespace + "\""))
// Copy the AppDelegate.m to the project
.then(TestUtil.copyFile.bind(undefined,
path.join(TestConfig.templatePath, "ios", TestConfig.TestAppName, "AppDelegate.m"),
appDelegatePath, true))
.then<void>(TestUtil.replaceString.bind(undefined, appDelegatePath, TestUtil.CODE_PUSH_TEST_APP_NAME_PLACEHOLDER, TestConfig.TestAppName));
}
/**
* Installs the binary of the given project on this platform.
*/
installApp(projectDirectory: string): Q.Promise<void> {
return TestUtil.getProcessOutput("xcrun simctl install booted " + this.getBinaryPath(projectDirectory)).then(() => { return null; });
}
/**
* Maps project directories to whether or not they have built an IOS project before.
*
* The first build of an IOS project does not always succeed, so we always try again when it fails.
*
* EXAMPLE:
* {
* "TEMP_DIR/test-run": true,
* "TEMP_DIR/updates": false
* }
*/
private static iosFirstBuild: any = {};
/**
* Builds the binary of the project on this platform.
*/
buildApp(projectDirectory: string): Q.Promise<void> {
const iOSProject: string = path.join(projectDirectory, TestConfig.TestAppName, "ios");
return this.getEmulatorManager().getTargetEmulator()
.then((targetEmulator: string) => {
const hashRegEx = /[(][0-9A-Z-]*[)]/g;
const hashWithParen = targetEmulator.match(hashRegEx)[0];
const hash = hashWithParen.substr(1, hashWithParen.length - 2);
return TestUtil.getProcessOutput("xcodebuild -workspace " + path.join(iOSProject, TestConfig.TestAppName) + ".xcworkspace -scheme " + TestConfig.TestAppName +
" -configuration Release -destination \"platform=iOS Simulator,id=" + hash + "\" -derivedDataPath build EXCLUDED_ARCHS=arm64", { cwd: iOSProject, maxBuffer: 1024 * 1024 * 500, noLogStdOut: true });
})
.then<void>(
() => { return null; },
() => {
// The first time an iOS project is built, it fails because it does not finish building libReact.a before it builds the test app.
// Simply build again to fix the issue.
if (!RNIOS.iosFirstBuild[projectDirectory]) {
const iosBuildFolder = path.join(iOSProject, "build");
if (fs.existsSync(iosBuildFolder)) {
del.sync([iosBuildFolder], { force: true });
}
RNIOS.iosFirstBuild[projectDirectory] = true;
return this.buildApp(projectDirectory);
}
return null;
});
}
}
const supportedTargetPlatforms: Platform.IPlatform[] = [new RNAndroid(), new RNIOS()];
//////////////////////////////////////////////////////////////////////////////////////////
// Create the ProjectManager to use for the tests.
class RNProjectManager extends ProjectManager {
/**
* Returns the name of the plugin being tested, ie Cordova or React-Native
*/
public getPluginName(): string {
return "React-Native";
}
/**
* Copies over the template files into the specified project, overwriting existing files.
*/
public copyTemplate(templatePath: string, projectDirectory: string): Q.Promise<void> {
function copyDirectoryRecursively(directoryFrom: string, directoryTo: string): Q.Promise<void> {
const promises: Q.Promise<void>[] = [];
fs.readdirSync(directoryFrom).forEach(file => {
let fileStats: fs.Stats;
const fileInFrom: string = path.join(directoryFrom, file);
const fileInTo: string = path.join(directoryTo, file);
try { fileStats = fs.statSync(fileInFrom); } catch (e) { /* fs.statSync throws if the file doesn't exist. */ }
// If it is a file, just copy directly
if (fileStats && fileStats.isFile()) {
promises.push(TestUtil.copyFile(fileInFrom, fileInTo, true));
}
else {
// If it is a directory, create the directory if it doesn't exist on the target and then copy over
if (!fs.existsSync(fileInTo)) mkdirp.sync(fileInTo);
promises.push(copyDirectoryRecursively(fileInFrom, fileInTo));
}
});
// Chain promise so that it maintains Q.Promise<void> type instead of Q.Promise<void[]>
return Q.all<void>(promises).then(() => { return null; });
}
return copyDirectoryRecursively(templatePath, path.join(projectDirectory, TestConfig.TestAppName));
}
/**
* Creates a new test application at the specified path, and configures it
* with the given server URL, android and ios deployment keys.
*/
public setupProject(projectDirectory: string, templatePath: string, appName: string, appNamespace: string, version?: string): Q.Promise<void> {
if (fs.existsSync(projectDirectory)) {
del.sync([projectDirectory], { force: true });
}
mkdirp.sync(projectDirectory);
return TestUtil.getProcessOutput("react-native init " + appName, { cwd: projectDirectory, timeout: 30 * 60 * 1000 })
.then((e) => { console.log(`"react-native init ${appName}" success. cwd=${projectDirectory}`); return e; })
.then(this.copyTemplate.bind(this, templatePath, projectDirectory))
.then<void>(TestUtil.getProcessOutput.bind(undefined, TestConfig.thisPluginInstallString, { cwd: path.join(projectDirectory, TestConfig.TestAppName) }))
.then(() => { return null; })
.catch((error) => {
console.log(`"react-native init ${appName} failed". cwd=${projectDirectory}`, error);
throw new Error(error);
});
}
/** JSON mapping project directories to the current scenario
*
* EXAMPLE:
* {
* "TEMP_DIR/test-run": "scenarios/scenarioCheckForUpdate.js",
* "TEMP_DIR/updates": "scenarios/updateSync.js"
* }
*/
private static currentScenario: any = {};
/** JSON mapping project directories to whether or not they've built the current scenario
*
* EXAMPLE:
* {
* "TEMP_DIR/test-run": "true",
* "TEMP_DIR/updates": "false"
* }
*/
private static currentScenarioHasBuilt: any = {};
/**
* Sets up the scenario for a test in an already existing project.
*/
public setupScenario(projectDirectory: string, appId: string, templatePath: string, jsPath: string, targetPlatform: Platform.IPlatform, version?: string): Q.Promise<void> {
// We don't need to anything if it is the current scenario.
if (RNProjectManager.currentScenario[projectDirectory] === jsPath) return Q<void>(null);
RNProjectManager.currentScenario[projectDirectory] = jsPath;
RNProjectManager.currentScenarioHasBuilt[projectDirectory] = false;
const indexHtml = "index.js";
const templateIndexPath = path.join(templatePath, indexHtml);
const destinationIndexPath = path.join(projectDirectory, TestConfig.TestAppName, indexHtml);
const scenarioJs = "scenarios/" + jsPath;
console.log("Setting up scenario " + jsPath + " in " + projectDirectory);
// Copy index html file and replace
return TestUtil.copyFile(templateIndexPath, destinationIndexPath, true)
.then<void>(TestUtil.replaceString.bind(undefined, destinationIndexPath, TestUtil.CODE_PUSH_TEST_APP_NAME_PLACEHOLDER, TestConfig.TestAppName))
.then<void>(TestUtil.replaceString.bind(undefined, destinationIndexPath, TestUtil.SERVER_URL_PLACEHOLDER, targetPlatform.getServerUrl()))
.then<void>(TestUtil.replaceString.bind(undefined, destinationIndexPath, TestUtil.INDEX_JS_PLACEHOLDER, scenarioJs))
.then<void>(TestUtil.replaceString.bind(undefined, destinationIndexPath, TestUtil.CODE_PUSH_APP_VERSION_PLACEHOLDER, version));
}
/**
* Creates a CodePush update package zip for a project.
*/
public createUpdateArchive(projectDirectory: string, targetPlatform: Platform.IPlatform, isDiff?: boolean): Q.Promise<string> {
const bundleFolder: string = path.join(projectDirectory, TestConfig.TestAppName, "CodePush/");
const bundleName: string = (<RNPlatform><any>targetPlatform).getBundleName();
const bundlePath: string = path.join(bundleFolder, bundleName);
const deferred = Q.defer<string>();
fs.exists(bundleFolder, (exists) => {
if (exists) del.sync([bundleFolder], { force: true });
mkdirp.sync(bundleFolder);
deferred.resolve(undefined);
});
return deferred.promise
.then(TestUtil.getProcessOutput.bind(undefined, "react-native bundle --platform " + targetPlatform.getName() + " --entry-file index." + targetPlatform.getName() + ".js --bundle-output " + bundlePath + " --assets-dest " + bundleFolder + " --dev false",
{ cwd: path.join(projectDirectory, TestConfig.TestAppName) }))
.then<string>(TestUtil.archiveFolder.bind(undefined, bundleFolder, "", path.join(projectDirectory, TestConfig.TestAppName, "update.zip"), isDiff));
}
/** JSON file containing the platforms the plugin is currently installed for.
* Keys must match targetPlatform.getName()!
*
* EXAMPLE:
* {
* "android": true,
* "ios": false
* }
*/
private static platformsJSON: string = "platforms.json";
/**
* Prepares a specific platform for tests.
*/
public preparePlatform(projectDirectory: string, targetPlatform: Platform.IPlatform): Q.Promise<void> {
const deferred = Q.defer<string>();
const platformsJSONPath = path.join(projectDirectory, RNProjectManager.platformsJSON);
// We create a JSON file in the project folder to contain the installed platforms.
// Check the file to see if the plugin for this platform has been installed and update the file appropriately.
fs.exists(platformsJSONPath, (exists) => {
if (!exists) {
fs.writeFileSync(platformsJSONPath, "{}");
}
const platformJSON = eval("(" + fs.readFileSync(platformsJSONPath, "utf8") + ")");
if (platformJSON[targetPlatform.getName()] === true) deferred.reject("Platform " + targetPlatform.getName() + " is already installed in " + projectDirectory + "!");
else {
platformJSON[targetPlatform.getName()] = true;
fs.writeFileSync(platformsJSONPath, JSON.stringify(platformJSON));
deferred.resolve(undefined);
}
});
return deferred.promise
.then<void>(() => {
return (<RNPlatform><any>targetPlatform).installPlatform(projectDirectory);
}, (error: any) => { /* The platform is already installed! */ console.log(error); return null; });
}
/**
* Cleans up a specific platform after tests.
*/
public cleanupAfterPlatform(projectDirectory: string, targetPlatform: Platform.IPlatform): Q.Promise<void> {
// Can't uninstall from command line, so noop.
return Q<void>(null);
}
/**
* Runs the test app on the given target / platform.
*/
public runApplication(projectDirectory: string, targetPlatform: Platform.IPlatform): Q.Promise<void> {
console.log("Running project in " + projectDirectory + " on " + targetPlatform.getName());
return Q<void>(null)
.then(() => {
// Build if this scenario has not yet been built.
if (!RNProjectManager.currentScenarioHasBuilt[projectDirectory]) {
RNProjectManager.currentScenarioHasBuilt[projectDirectory] = true;
return (<RNPlatform><any>targetPlatform).buildApp(projectDirectory);
}
})
.then(() => {
// Uninstall the app so that the installation is clean and no files are left around for each test.
return targetPlatform.getEmulatorManager().uninstallApplication(TestConfig.TestNamespace);
})
.then(() => {
// Install and launch the app.
return (<RNPlatform><any>targetPlatform).installApp(projectDirectory)
.then<void>(targetPlatform.getEmulatorManager().launchInstalledApplication.bind(undefined, TestConfig.TestNamespace));
});
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Scenarios used in the tests.
const ScenarioCheckForUpdatePath = "scenarioCheckForUpdate.js";
const ScenarioCheckForUpdateCustomKey = "scenarioCheckForUpdateCustomKey.js";
const ScenarioDisallowRestartImmediate = "scenarioDisallowRestartImmediate.js";
const ScenarioDisallowRestartOnResume = "scenarioDisallowRestartOnResume.js";
const ScenarioDisallowRestartOnSuspend = "scenarioDisallowRestartOnSuspend.js";
const ScenarioDownloadUpdate = "scenarioDownloadUpdate.js";
const ScenarioInstall = "scenarioInstall.js";
const ScenarioInstallOnResumeWithRevert = "scenarioInstallOnResumeWithRevert.js";
const ScenarioInstallOnSuspendWithRevert = "scenarioInstallOnSuspendWithRevert.js";
const ScenarioInstallOnRestartWithRevert = "scenarioInstallOnRestartWithRevert.js";
const ScenarioInstallWithRevert = "scenarioInstallWithRevert.js";
const ScenarioInstallRestart2x = "scenarioInstallRestart2x.js";
const ScenarioSync1x = "scenarioSync.js";
const ScenarioSyncResume = "scenarioSyncResume.js";
const ScenarioSyncSuspend = "scenarioSyncSuspend.js";
const ScenarioSyncResumeDelay = "scenarioSyncResumeDelay.js";
const ScenarioSyncRestartDelay = "scenarioSyncRestartDelay.js";
const ScenarioSyncSuspendDelay = "scenarioSyncSuspendDelay.js";
const ScenarioSync2x = "scenarioSync2x.js";
const ScenarioRestart = "scenarioRestart.js";
const ScenarioRestart2x = "scenarioRestart2x.js";
const ScenarioSyncMandatoryDefault = "scenarioSyncMandatoryDefault.js";
const ScenarioSyncMandatoryResume = "scenarioSyncMandatoryResume.js";
const ScenarioSyncMandatoryRestart = "scenarioSyncMandatoryRestart.js";
const ScenarioSyncMandatorySuspend = "scenarioSyncMandatorySuspend.js";
const UpdateDeviceReady = "updateDeviceReady.js";
const UpdateNotifyApplicationReady = "updateNotifyApplicationReady.js";
const UpdateSync = "updateSync.js";
const UpdateSync2x = "updateSync2x.js";
const UpdateNotifyApplicationReadyConditional = "updateNARConditional.js";
//////////////////////////////////////////////////////////////////////////////////////////
// Initialize the tests.
PluginTestingFramework.initializeTests(new RNProjectManager(), supportedTargetPlatforms,
(projectManager: ProjectManager, targetPlatform: Platform.IPlatform) => {
TestBuilder.describe("#window.codePush.checkForUpdate",
() => {
TestBuilder.it("window.codePush.checkForUpdate.noUpdate", false,
(done: Mocha.Done) => {
const noUpdateResponse = ServerUtil.createDefaultResponse();
noUpdateResponse.is_available = false;
noUpdateResponse.target_binary_range = "0.0.1";
ServerUtil.updateResponse = { update_info: noUpdateResponse };
ServerUtil.testMessageCallback = (requestBody: any) => {
try {
assert.strictEqual(requestBody.message, ServerUtil.TestMessage.CHECK_UP_TO_DATE);
done();
} catch (e) {
done(e);
}
};
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
});
TestBuilder.it("window.codePush.checkForUpdate.sendsBinaryHash", false,
(done: Mocha.Done) => {
if (!(<RNPlatform><any>targetPlatform).isDiffsSupported()) {
console.log(targetPlatform.getName() + " does not send a binary hash!");
done();
return;
}
const noUpdateResponse = ServerUtil.createDefaultResponse();
noUpdateResponse.is_available = false;
noUpdateResponse.target_binary_range = "0.0.1";
ServerUtil.updateCheckCallback = (request: any) => {
try {
assert(request.query.package_hash);
} catch (e) {
done(e);
}
};
ServerUtil.updateResponse = { update_info: noUpdateResponse };
ServerUtil.testMessageCallback = (requestBody: any) => {
try {
assert.strictEqual(requestBody.message, ServerUtil.TestMessage.CHECK_UP_TO_DATE);
done();
} catch (e) {
done(e);
}
};
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
});
TestBuilder.it("window.codePush.checkForUpdate.noUpdate.updateAppVersion", false,
(done: Mocha.Done) => {
const updateAppVersionResponse = ServerUtil.createDefaultResponse();
updateAppVersionResponse.is_available = true;
updateAppVersionResponse.target_binary_range = "2.0.0";
updateAppVersionResponse.update_app_version = true;
ServerUtil.updateResponse = { update_info: updateAppVersionResponse };
ServerUtil.testMessageCallback = (requestBody: any) => {
try {
assert.strictEqual(requestBody.message, ServerUtil.TestMessage.CHECK_UP_TO_DATE);
done();
} catch (e) {
done(e);
}
};
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
});
TestBuilder.it("window.codePush.checkForUpdate.update", true,
(done: Mocha.Done) => {
const updateResponse = ServerUtil.createUpdateResponse();
ServerUtil.updateResponse = { update_info: updateResponse };
ServerUtil.testMessageCallback = (requestBody: any) => {
try {
assert.strictEqual(requestBody.message, ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE);
assert.notStrictEqual(requestBody.args[0], null);
const remotePackage: any = requestBody.args[0];
assert.strictEqual(remotePackage.downloadUrl, updateResponse.download_url);
assert.strictEqual(remotePackage.isMandatory, updateResponse.is_mandatory);
assert.strictEqual(remotePackage.label, updateResponse.label);
assert.strictEqual(remotePackage.packageHash, updateResponse.package_hash);
assert.strictEqual(remotePackage.packageSize, updateResponse.package_size);
assert.strictEqual(remotePackage.deploymentKey, targetPlatform.getDefaultDeploymentKey());
done();
} catch (e) {
done(e);
}
};
ServerUtil.updateCheckCallback = (request: any) => {
try {
assert.notStrictEqual(null, request);
assert.strictEqual(request.query.deployment_key, targetPlatform.getDefaultDeploymentKey());
} catch (e) {
done(e);
}
};
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
});
TestBuilder.it("window.codePush.checkForUpdate.error", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = "invalid {{ json";
ServerUtil.testMessageCallback = (requestBody: any) => {
try {
assert.strictEqual(requestBody.message, ServerUtil.TestMessage.CHECK_ERROR);
done();
} catch (e) {
done(e);
}
};
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
});
}, ScenarioCheckForUpdatePath);
TestBuilder.describe("#window.codePush.checkForUpdate.customKey",
() => {
TestBuilder.it("window.codePush.checkForUpdate.customKey.update", false,
(done: Mocha.Done) => {
const updateResponse = ServerUtil.createUpdateResponse();
ServerUtil.updateResponse = { update_info: updateResponse };
ServerUtil.updateCheckCallback = (request: any) => {
try {
assert.notStrictEqual(null, request);
assert.strictEqual(request.query.deployment_key, "CUSTOM-DEPLOYMENT-KEY");
done();
} catch (e) {
done(e);
}
};
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
});
}, ScenarioCheckForUpdateCustomKey);
TestBuilder.describe("#remotePackage.download",
() => {
TestBuilder.it("remotePackage.download.success", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
/* pass the path to any file for download (here, index.js) to make sure the download completed callback is invoked */
ServerUtil.updatePackagePath = path.join(TestConfig.templatePath, "index.js");
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED])
.then(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("remotePackage.download.error", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
/* pass an invalid update url */
ServerUtil.updateResponse.update_info.download_url = "http://invalid_url";
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_ERROR])
.then(() => { done(); }, (e) => { done(e); });
});
}, ScenarioDownloadUpdate);
TestBuilder.describe("#localPackage.install",
() => {
// // CHANGE THIS TEST CASE, accepts both a jsbundle and a zip
// TestBuilder.it("localPackage.install.unzip.error",
// (done: Mocha.Done) => {
// ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
// /* pass an invalid zip file, here, index.js */
// ServerUtil.updatePackagePath = path.join(TestConfig.templatePath, "index.js");
// var deferred = Q.defer<void>();
// deferred.promise.then(() => { done(); }, (e) => { done(e); });
// ServerUtil.testMessageCallback = PluginTestingFramework.verifyMessages([
// ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
// ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
// ServerUtil.TestMessage.INSTALL_ERROR], deferred);
// projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
// }, false),
TestBuilder.it("localPackage.install.handlesDiff.againstBinary", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
/* create an update */
setupUpdateScenario(projectManager, targetPlatform, UpdateNotifyApplicationReady, "Diff Update 1")
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.then<void>(() => {
/* run the app again to ensure it was not reverted */
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("localPackage.install.immediately", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
/* create an update */
setupUpdateScenario(projectManager, targetPlatform, UpdateNotifyApplicationReady, "Update 1")
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.then<void>(() => {
/* run the app again to ensure it was not reverted */
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.done(() => { done(); }, (e) => { done(e); });
});
}, ScenarioInstall);
TestBuilder.describe("#localPackage.install.revert",
() => {
TestBuilder.it("localPackage.install.revert.dorevert", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
/* create an update */
setupUpdateScenario(projectManager, targetPlatform, UpdateDeviceReady, "Update 1 (bad update)")
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.then<void>(() => {
/* restart the app to ensure it was reverted and send it another update */
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.then<void>(() => {
/* restart the app again to ensure it was reverted again and send the same update and expect it to reject it */
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.UPDATE_FAILED_PREVIOUSLY]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("localPackage.install.revert.norevert", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
/* create an update */
setupUpdateScenario(projectManager, targetPlatform, UpdateNotifyApplicationReady, "Update 1 (good update)")
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.then<void>(() => {
/* run the app again to ensure it was not reverted */
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.done(() => { done(); }, (e) => { done(e); });
});
}, ScenarioInstallWithRevert);
TestBuilder.describe("#localPackage.installOnNextResume",
() => {
TestBuilder.it("localPackage.installOnNextResume.dorevert", true,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
setupUpdateScenario(projectManager, targetPlatform, UpdateDeviceReady, "Update 1")
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.UPDATE_INSTALLED]);
})
.then<void>(() => {
/* resume the application */
targetPlatform.getEmulatorManager().resumeApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.then<void>(() => {
/* restart to revert it */
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.UPDATE_FAILED_PREVIOUSLY]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("localPackage.installOnNextResume.norevert", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
/* create an update */
setupUpdateScenario(projectManager, targetPlatform, UpdateNotifyApplicationReady, "Update 1 (good update)")
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.UPDATE_INSTALLED]);
})
.then<void>(() => {
/* resume the application */
targetPlatform.getEmulatorManager().resumeApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.then<void>(() => {
/* restart to make sure it did not revert */
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.done(() => { done(); }, (e) => { done(e); });
});
}, ScenarioInstallOnResumeWithRevert);
TestBuilder.describe("#localPackage.installOnNextSuspend",
() => {
TestBuilder.it("localPackage.installOnNextSuspend.dorevert", true,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
setupUpdateScenario(projectManager, targetPlatform, UpdateDeviceReady, "Update 1")
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.UPDATE_INSTALLED]);
})
.then<void>(() => {
/* resume the application */
targetPlatform.getEmulatorManager().resumeApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.then<void>(() => {
/* restart to revert it */
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.UPDATE_FAILED_PREVIOUSLY]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("localPackage.installOnNextSuspend.norevert", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
/* create an update */
setupUpdateScenario(projectManager, targetPlatform, UpdateNotifyApplicationReady, "Update 1 (good update)")
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.UPDATE_INSTALLED]);
})
.then<void>(() => {
/* resume the application */
targetPlatform.getEmulatorManager().resumeApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.then<void>(() => {
/* restart to make sure it did not revert */
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.done(() => { done(); }, (e) => { done(e); });
});
}, ScenarioInstallOnSuspendWithRevert);
TestBuilder.describe("localPackage installOnNextRestart",
() => {
TestBuilder.it("localPackage.installOnNextRestart.dorevert", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
setupUpdateScenario(projectManager, targetPlatform, UpdateDeviceReady, "Update 1")
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.UPDATE_INSTALLED]);
})
.then<void>(() => {
/* restart the application */
console.log("Update hash: " + ServerUtil.updateResponse.update_info.package_hash);
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.then<void>(() => {
/* restart the application */
console.log("Update hash: " + ServerUtil.updateResponse.update_info.package_hash);
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.UPDATE_FAILED_PREVIOUSLY]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("localPackage.installOnNextRestart.norevert", true,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
/* create an update */
setupUpdateScenario(projectManager, targetPlatform, UpdateNotifyApplicationReady, "Update 1 (good update)")
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.UPDATE_INSTALLED]);
})
.then<void>(() => {
/* "resume" the application - run it again */
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.then<void>(() => {
/* run again to make sure it did not revert */
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("localPackage.installOnNextRestart.revertToPrevious", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
/* create an update */
setupUpdateScenario(projectManager, targetPlatform, UpdateNotifyApplicationReadyConditional, "Update 1 (good update)")
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.UPDATE_INSTALLED]);
})
.then<void>(() => {
/* run good update, set up another (bad) update */
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
setupUpdateScenario(projectManager, targetPlatform, UpdateDeviceReady, "Update 2 (bad update)")
.then(() => { return targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace); });
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE,
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.UPDATE_INSTALLED]);
})
.then<void>(() => {
/* run the bad update without calling notifyApplicationReady */
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.then<void>(() => {
/* run the good update and don't call notifyApplicationReady - it should not revert */
ServerUtil.testMessageResponse = ServerUtil.TestMessageResponse.SKIP_NOTIFY_APPLICATION_READY;
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE,
ServerUtil.TestMessage.SKIPPED_NOTIFY_APPLICATION_READY]);
})
.then<void>(() => {
/* run the application again */
ServerUtil.testMessageResponse = undefined;
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE,
ServerUtil.TestMessage.UPDATE_FAILED_PREVIOUSLY]);
})
.done(() => { done(); }, (e) => { done(e); });
});
}, ScenarioInstallOnRestartWithRevert);
TestBuilder.describe("#codePush.restartApplication",
() => {
TestBuilder.it("codePush.restartApplication.checkPackages", true,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
setupUpdateScenario(projectManager, targetPlatform, UpdateNotifyApplicationReady, "Update 1")
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.PENDING_PACKAGE, [null]),
new ServerUtil.AppMessage(ServerUtil.TestMessage.CURRENT_PACKAGE, [null]),
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UPDATE_INSTALLED]),
new ServerUtil.AppMessage(ServerUtil.TestMessage.PENDING_PACKAGE, [ServerUtil.updateResponse.update_info.package_hash]),
new ServerUtil.AppMessage(ServerUtil.TestMessage.CURRENT_PACKAGE, [null]),
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.then<void>(() => {
/* restart the application */
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.done(() => { done(); }, (e) => { done(e); });
});
}, ScenarioRestart);
TestBuilder.describe("#codePush.restartApplication.2x",
() => {
TestBuilder.it("blocks when a restart is in progress and doesn't crash if there is a pending package", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
setupTestRunScenario(projectManager, targetPlatform, ScenarioInstallRestart2x)
.then(setupUpdateScenario.bind(this, projectManager, targetPlatform, UpdateDeviceReady, "Update 1"))
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.UPDATE_INSTALLED,
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("doesn't block when the restart is ignored", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
setupTestRunScenario(projectManager, targetPlatform, ScenarioRestart2x)
.then(setupUpdateScenario.bind(this, projectManager, targetPlatform, UpdateDeviceReady, "Update 1"))
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.UPDATE_INSTALLED,
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.done(() => { done(); }, (e) => { done(e); });
});
});
TestBuilder.describe("#window.codePush.sync",
() => {
// We test the functionality with sync twice--first, with sync only called once,
// then, with sync called again while the first sync is still running.
TestBuilder.describe("#window.codePush.sync 1x",
() => {
// Tests where sync is called just once
TestBuilder.it("window.codePush.sync.noupdate", false,
(done: Mocha.Done) => {
const noUpdateResponse = ServerUtil.createDefaultResponse();
noUpdateResponse.is_available = false;
noUpdateResponse.target_binary_range = "0.0.1";
ServerUtil.updateResponse = { update_info: noUpdateResponse };
Q({})
.then<void>(p => {
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UP_TO_DATE])]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("window.codePush.sync.checkerror", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = "invalid {{ json";
Q({})
.then<void>(p => {
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_ERROR])]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("window.codePush.sync.downloaderror", false,
(done: Mocha.Done) => {
const invalidUrlResponse = ServerUtil.createUpdateResponse();
invalidUrlResponse.download_url = "http://" + path.join(TestConfig.templatePath, "invalid_path.zip");
ServerUtil.updateResponse = { update_info: invalidUrlResponse };
Q({})
.then<void>(p => {
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_ERROR])]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("window.codePush.sync.dorevert", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
/* create an update */
setupUpdateScenario(projectManager, targetPlatform, UpdateDeviceReady, "Update 1 (bad update)")
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.then<void>(() => {
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UP_TO_DATE])]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("window.codePush.sync.update", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
/* create an update */
setupUpdateScenario(projectManager, targetPlatform, UpdateSync, "Update 1 (good update)")
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE,
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UP_TO_DATE])]);
})
.then<void>(() => {
// restart the app and make sure it didn't roll out!
const noUpdateResponse = ServerUtil.createDefaultResponse();
noUpdateResponse.is_available = false;
noUpdateResponse.target_binary_range = "0.0.1";
ServerUtil.updateResponse = { update_info: noUpdateResponse };
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE,
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UP_TO_DATE])]);
})
.done(() => { done(); }, (e) => { done(e); });
});
}, ScenarioSync1x);
TestBuilder.describe("#window.codePush.sync 2x",
() => {
// Tests where sync is called again before the first sync finishes
TestBuilder.it("window.codePush.sync.2x.noupdate", false,
(done: Mocha.Done) => {
const noUpdateResponse = ServerUtil.createDefaultResponse();
noUpdateResponse.is_available = false;
noUpdateResponse.target_binary_range = "0.0.1";
ServerUtil.updateResponse = { update_info: noUpdateResponse };
Q({})
.then<void>(p => {
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_IN_PROGRESS]),
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UP_TO_DATE])]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("window.codePush.sync.2x.checkerror", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = "invalid {{ json";
Q({})
.then<void>(p => {
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_IN_PROGRESS]),
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_ERROR])]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("window.codePush.sync.2x.downloaderror", false,
(done: Mocha.Done) => {
const invalidUrlResponse = ServerUtil.createUpdateResponse();
invalidUrlResponse.download_url = "http://" + path.join(TestConfig.templatePath, "invalid_path.zip");
ServerUtil.updateResponse = { update_info: invalidUrlResponse };
Q({})
.then<void>(p => {
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_IN_PROGRESS]),
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_ERROR])]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("window.codePush.sync.2x.dorevert", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
/* create an update */
setupUpdateScenario(projectManager, targetPlatform, UpdateDeviceReady, "Update 1 (bad update)")
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_IN_PROGRESS]),
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.then<void>(() => {
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_IN_PROGRESS]),
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UP_TO_DATE])]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("window.codePush.sync.2x.update", true,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
/* create an update */
setupUpdateScenario(projectManager, targetPlatform, UpdateSync2x, "Update 1 (good update)")
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_IN_PROGRESS]),
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE,
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_IN_PROGRESS]),
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UP_TO_DATE])]);
})
.then<void>(() => {
// restart the app and make sure it didn't roll out!
const noUpdateResponse = ServerUtil.createDefaultResponse();
noUpdateResponse.is_available = false;
noUpdateResponse.target_binary_range = "0.0.1";
ServerUtil.updateResponse = { update_info: noUpdateResponse };
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE,
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_IN_PROGRESS]),
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UP_TO_DATE])]);
})
.done(() => { done(); }, (e) => { done(e); });
});
}, ScenarioSync2x);
});
TestBuilder.describe("#window.codePush.sync minimum background duration tests",
() => {
TestBuilder.it("defaults to no minimum for Resume mode", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
setupTestRunScenario(projectManager, targetPlatform, ScenarioSyncResume).then<string>(() => {
return setupUpdateScenario(projectManager, targetPlatform, UpdateSync, "Update 1 (good update)");
})
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UPDATE_INSTALLED])]);
})
.then<void>(() => {
const noUpdateResponse = ServerUtil.createDefaultResponse();
noUpdateResponse.is_available = false;
noUpdateResponse.target_binary_range = "0.0.1";
ServerUtil.updateResponse = { update_info: noUpdateResponse };
targetPlatform.getEmulatorManager().resumeApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE,
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UP_TO_DATE])]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("min background duration 5s for Resume mode", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
setupTestRunScenario(projectManager, targetPlatform, ScenarioSyncResumeDelay).then<string>(() => {
return setupUpdateScenario(projectManager, targetPlatform, UpdateSync, "Update 1 (good update)");
})
.then((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UPDATE_INSTALLED])]);
})
.then(() => {
const noUpdateResponse = ServerUtil.createDefaultResponse();
noUpdateResponse.is_available = false;
noUpdateResponse.target_binary_range = "0.0.1";
ServerUtil.updateResponse = { update_info: noUpdateResponse };
return targetPlatform.getEmulatorManager().resumeApplication(TestConfig.TestNamespace, 3 * 1000);
})
.then(() => {
targetPlatform.getEmulatorManager().resumeApplication(TestConfig.TestNamespace, 6 * 1000);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE,
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UP_TO_DATE])]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("defaults to no minimum for Suspend mode", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
setupTestRunScenario(projectManager, targetPlatform, ScenarioSyncSuspend).then<string>(() => {
return setupUpdateScenario(projectManager, targetPlatform, UpdateSync, "Update 1 (good update)");
})
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UPDATE_INSTALLED])]);
})
.then<void>(() => {
const noUpdateResponse = ServerUtil.createDefaultResponse();
noUpdateResponse.is_available = false;
noUpdateResponse.target_binary_range = "0.0.1";
ServerUtil.updateResponse = { update_info: noUpdateResponse };
targetPlatform.getEmulatorManager().resumeApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE,
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UP_TO_DATE])]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("min background duration 5s for Suspend mode", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
setupTestRunScenario(projectManager, targetPlatform, ScenarioSyncSuspendDelay).then<string>(() => {
return setupUpdateScenario(projectManager, targetPlatform, UpdateSync, "Update 1 (good update)");
})
.then((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UPDATE_INSTALLED])]);
})
.then(() => {
const noUpdateResponse = ServerUtil.createDefaultResponse();
noUpdateResponse.is_available = false;
noUpdateResponse.target_binary_range = "0.0.1";
ServerUtil.updateResponse = { update_info: noUpdateResponse };
return targetPlatform.getEmulatorManager().resumeApplication(TestConfig.TestNamespace, 3 * 1000);
})
.then(() => {
targetPlatform.getEmulatorManager().resumeApplication(TestConfig.TestNamespace, 6 * 1000);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE,
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UP_TO_DATE])]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("has no effect on restart", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
setupTestRunScenario(projectManager, targetPlatform, ScenarioSyncRestartDelay).then<string>(() => {
return setupUpdateScenario(projectManager, targetPlatform, UpdateSync, "Update 1 (good update)");
})
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UPDATE_INSTALLED])]);
})
.then<void>(() => {
const noUpdateResponse = ServerUtil.createDefaultResponse();
noUpdateResponse.is_available = false;
noUpdateResponse.target_binary_range = "0.0.1";
ServerUtil.updateResponse = { update_info: noUpdateResponse };
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE,
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UP_TO_DATE])]);
})
.done(() => { done(); }, (e) => { done(e); });
});
});
TestBuilder.describe("#window.codePush.sync mandatory install mode tests",
() => {
TestBuilder.it("defaults to IMMEDIATE", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(true, targetPlatform) };
setupTestRunScenario(projectManager, targetPlatform, ScenarioSyncMandatoryDefault).then<string>(() => {
return setupUpdateScenario(projectManager, targetPlatform, UpdateDeviceReady, "Update 1 (good update)");
})
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("works correctly when update is mandatory and mandatory install mode is Resume", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(true, targetPlatform) };
setupTestRunScenario(projectManager, targetPlatform, ScenarioSyncMandatoryResume).then<string>(() => {
return setupUpdateScenario(projectManager, targetPlatform, UpdateDeviceReady, "Update 1 (good update)");
})
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UPDATE_INSTALLED])]);
})
.then<void>(() => {
const noUpdateResponse = ServerUtil.createDefaultResponse();
noUpdateResponse.is_available = false;
noUpdateResponse.target_binary_range = "0.0.1";
ServerUtil.updateResponse = { update_info: noUpdateResponse };
targetPlatform.getEmulatorManager().resumeApplication(TestConfig.TestNamespace, 5 * 1000);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("works correctly when update is mandatory and mandatory install mode is Suspend", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(true, targetPlatform) };
setupTestRunScenario(projectManager, targetPlatform, ScenarioSyncMandatorySuspend).then<string>(() => {
return setupUpdateScenario(projectManager, targetPlatform, UpdateDeviceReady, "Update 1 (good update)");
})
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
new ServerUtil.AppMessage(ServerUtil.TestMessage.SYNC_STATUS, [ServerUtil.TestMessage.SYNC_UPDATE_INSTALLED])]);
})
.then<void>(() => {
const noUpdateResponse = ServerUtil.createDefaultResponse();
noUpdateResponse.is_available = false;
noUpdateResponse.target_binary_range = "0.0.1";
ServerUtil.updateResponse = { update_info: noUpdateResponse };
targetPlatform.getEmulatorManager().resumeApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("has no effect on updates that are not mandatory", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
setupTestRunScenario(projectManager, targetPlatform, ScenarioSyncMandatoryRestart).then<string>(() => {
return setupUpdateScenario(projectManager, targetPlatform, UpdateDeviceReady, "Update 1 (good update)");
})
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.done(() => { done(); }, (e) => { done(e); });
});
});
TestBuilder.describe("#codePush.disallowRestart",
() => {
TestBuilder.it("disallowRestart with IMMEDIATE install mode", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
setupTestRunScenario(projectManager, targetPlatform, ScenarioDisallowRestartImmediate)
.then(setupUpdateScenario.bind(this, projectManager, targetPlatform, UpdateNotifyApplicationReady, "Update 1"))
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.UPDATE_INSTALLED,
ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE
]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("disallowRestart with ON_NEXT_RESUME install mode", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
setupTestRunScenario(projectManager, targetPlatform, ScenarioDisallowRestartOnResume)
.then(setupUpdateScenario.bind(this, projectManager, targetPlatform, UpdateDeviceReady, "Update 1"))
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.UPDATE_INSTALLED
]);
})
.then<void>(() => {
/* resume the application */
return targetPlatform.getEmulatorManager().resumeApplication(TestConfig.TestNamespace);
})
.then<void>(() => {
/* restart the application */
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.done(() => { done(); }, (e) => { done(e); });
});
TestBuilder.it("disallowRestart with ON_NEXT_SUSPEND install mode", false,
(done: Mocha.Done) => {
ServerUtil.updateResponse = { update_info: ServerUtil.createUpdateResponse(false, targetPlatform) };
setupTestRunScenario(projectManager, targetPlatform, ScenarioDisallowRestartOnSuspend)
.then(setupUpdateScenario.bind(this, projectManager, targetPlatform, UpdateDeviceReady, "Update 1"))
.then<void>((updatePath: string) => {
ServerUtil.updatePackagePath = updatePath;
projectManager.runApplication(TestConfig.testRunDirectory, targetPlatform);
return ServerUtil.expectTestMessages([
ServerUtil.TestMessage.CHECK_UPDATE_AVAILABLE,
ServerUtil.TestMessage.DOWNLOAD_SUCCEEDED,
ServerUtil.TestMessage.UPDATE_INSTALLED
]);
})
.then<void>(() => {
/* resume the application */
return targetPlatform.getEmulatorManager().resumeApplication(TestConfig.TestNamespace);
})
.then<void>(() => {
/* restart the application */
targetPlatform.getEmulatorManager().restartApplication(TestConfig.TestNamespace);
return ServerUtil.expectTestMessages([ServerUtil.TestMessage.DEVICE_READY_AFTER_UPDATE]);
})
.done(() => { done(); }, (e) => { done(e); });
});
});
}); | the_stack |
import { deepStrictEqual, notStrictEqual, strictEqual } from 'assert';
import { createReadStream, mkdirSync, readdirSync, readFileSync, rmdirSync, unlinkSync } from 'fs';
import { join } from 'path';
// 3p
import {
Config, Context, createApp, createService, getApiRequestBody, HttpResponseOK, IApiRequestBody, Post
} from '@foal/core';
import * as request from 'supertest';
// FoalTS
import { Disk } from './disk.service';
import { File } from './file';
import { MultipartFormDataSchema, ValidateMultipartFormDataBody } from './validate-multipart-form-data-body.hook';
describe('ValidateMultipartFormDataBody', () => {
beforeEach(() => {
Config.set('settings.loggerFormat', 'none');
Config.set('settings.disk.driver', 'local');
});
afterEach(() => {
Config.remove('settings.loggerFormat');
Config.remove('settings.disk.driver');
});
// Note: Unfortunatly, in order to have a multipart request object,
// we need to create an Express server to test the hook.
function createAppWithHook(schema: MultipartFormDataSchema, actual: { body: any }): Promise<any> {
@ValidateMultipartFormDataBody(schema)
class AppController {
@Post('/')
index(ctx: Context) {
actual.body = ctx.request.body;
return new HttpResponseOK();
}
}
return createApp(AppController);
}
it('should return an HttpResponseBadRequest if the request is not of type multipart/form-data.', async () => {
const app = await createAppWithHook({
files: {}
}, { body: null });
await request(app)
.post('/')
.send({})
.expect(400)
.expect({
headers: {
error: 'INVALID_MULTIPART_FORM_DATA_REQUEST',
message: 'Unsupported content type: application/json'
}
});
});
describe('should set ctx.request.body.fields with the fields', () => {
it('when the fields are validated against the given schema.', async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
fields: {
name: { type: 'string' }
},
files: {}
}, actual);
await request(app)
.post('/')
.field('name', 'hello')
.field('unexpectedName', 'world')
.expect(200);
deepStrictEqual(actual.body.fields, {
name: 'hello'
});
});
it('when no schema is given in the hook.', async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {}
}, actual);
await request(app)
.post('/')
.field('name', 'hello')
.expect(200);
deepStrictEqual(actual.body.fields, {
name: 'hello'
});
});
});
describe('when the fields are not validated against the given schema', () => {
beforeEach(() => {
Config.set('settings.disk.local.directory', 'uploaded');
mkdirSync('uploaded');
mkdirSync('uploaded/images');
});
afterEach(() => {
Config.remove('settings.disk.local.directory');
const contents = readdirSync('uploaded/images');
for (const content of contents) {
unlinkSync(join('uploaded/images', content));
}
rmdirSync('uploaded/images');
rmdirSync('uploaded');
});
it('should return an HttpResponseBadRequest (invalid values).', async () => {
const app = await createAppWithHook({
fields: {
name: { type: 'boolean' }
},
files: {}
}, { body: null });
await request(app)
.post('/')
.field('name', 'hello')
.expect(400)
.expect({
body: [
{
dataPath: '.name',
keyword: 'type',
message: 'should be boolean',
params: {
type: 'boolean'
},
schemaPath: '#/properties/name/type',
}
]
});
});
it('should return an HttpResponseBadRequest (missing values).', async () => {
const app = await createAppWithHook({
fields: {
name: { type: 'string' },
name2: { type: 'string' }
},
files: {}
}, { body: null });
await request(app)
.post('/')
.field('name', 'hello')
.expect(400)
.expect({
body: [
{
dataPath: '',
keyword: 'required',
message: 'should have required property \'name2\'',
params: {
missingProperty: 'name2'
},
schemaPath: '#/required',
}
]
});
});
it('should not have uploaded the files.', async () => {
const app = await createAppWithHook({
fields: {
name: { type: 'boolean' }
},
files: {
foobar: { required: false, multiple: true, saveTo: 'images' },
foobar2: { required: false, multiple: false, saveTo: 'images' },
foobar3: { required: false, multiple: false, saveTo: 'images' },
foobar4: { required: false, multiple: false },
}
}, { body: null });
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'))
.attach('foobar', createReadStream('src/image.test2.png'))
.attach('foobar2', createReadStream('src/image.test2.png'))
.attach('foobar4', createReadStream('src/image.test2.png'))
.field('name', 'hello')
.expect(400); // Test that no error is rejected in the hook (error 500).
strictEqual(readdirSync('uploaded/images').length, 0);
});
});
describe('when the max file size has been reached', () => {
beforeEach(() => {
Config.set('settings.multipartRequests.fileSizeLimit', 200000);
Config.set('settings.disk.local.directory', 'uploaded');
mkdirSync('uploaded');
mkdirSync('uploaded/images');
});
afterEach(() => {
Config.remove('settings.multipartRequests.fileSizeLimit');
Config.remove('settings.disk.local.directory');
const contents = readdirSync('uploaded/images');
for (const content of contents) {
unlinkSync(join('uploaded/images', content));
}
rmdirSync('uploaded/images');
rmdirSync('uploaded');
});
it('should return an HttpResponseBadRequest.', async () => {
const app = await createAppWithHook({
files: {
foobar: { required: false },
foobar2: { required: false },
}
}, { body: null });
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'))
.attach('foobar2', createReadStream('src/image.test2.png'))
.expect(400)
.expect({
body: {
error: 'FILE_SIZE_LIMIT_REACHED',
message: 'The file "foobar2" is too large. The maximum file size is 200000 bytes.'
}
});
});
it('should not have uploaded the files.', async () => {
const app = await createAppWithHook({
files: {
foobar: { required: false, saveTo: 'images' },
foobar2: { required: false, saveTo: 'images' },
}
}, { body: null });
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'))
.attach('foobar2', createReadStream('src/image.test2.png'))
.expect(400); // Test that no error is rejected in the hook (error 500).
strictEqual(readdirSync('uploaded/images').length, 0);
});
});
describe('when the max number of files has been reached', () => {
beforeEach(() => {
Config.set('settings.multipartRequests.fileNumberLimit', 1);
Config.set('settings.disk.local.directory', 'uploaded');
mkdirSync('uploaded');
mkdirSync('uploaded/images');
});
afterEach(() => {
Config.remove('settings.multipartRequests.fileNumberLimit');
Config.remove('settings.disk.local.directory');
const contents = readdirSync('uploaded/images');
for (const content of contents) {
unlinkSync(join('uploaded/images', content));
}
rmdirSync('uploaded/images');
rmdirSync('uploaded');
});
it('should return an HttpResponseBadRequest.', async () => {
const app = await createAppWithHook({
files: {
foobar: { required: false, multiple: true },
}
}, { body: null });
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'))
.attach('foobar', createReadStream('src/image.test2.png'))
.expect(400)
.expect({
body: {
error: 'FILE_NUMBER_LIMIT_REACHED',
message: 'Too many files updated. The maximum number of files allowed is 1.'
}
});
});
it('should not have uploaded the files.', async () => {
const app = await createAppWithHook({
files: {
foobar: { required: false, multiple: true, saveTo: 'images' },
}
}, { body: null });
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'))
.attach('foobar', createReadStream('src/image.test2.png'))
.expect(400); // Test that no error is rejected in the hook (error 500).
strictEqual(readdirSync('uploaded/images').length, 0);
});
});
it('should ignore the upload of unexpected files.', async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {}
}, actual);
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'))
.expect(200);
deepStrictEqual(actual.body.files.foobar, undefined);
});
describe('when a file is not uploaded and it is not required', () => {
it('should set ctx.request.body.files with a "null" value if the option "multiple" is not defined.', async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {
foobar: { required: false }
}
}, actual);
await request(app)
.post('/')
.field('name', 'hello')
.expect(200);
deepStrictEqual(actual.body.files, {
foobar: null
});
});
it('should set ctx.request.body.files with a "null" value if the option "multiple" is "false".', async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {
foobar: { required: false, multiple: false }
}
}, actual);
await request(app)
.post('/')
.field('name', 'hello')
.expect(200);
deepStrictEqual(actual.body.files, {
foobar: null
});
});
it('should set ctx.request.body.files with an empty array if the option "multiple" is "true".', async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {
foobar: { required: false, multiple: true }
}
}, actual);
await request(app)
.post('/')
.field('name', 'hello')
.expect(200);
deepStrictEqual(actual.body.files, {
foobar: []
});
});
});
describe('when a file is not uploaded but it is required', () => {
beforeEach(() => {
Config.set('settings.disk.local.directory', 'uploaded');
mkdirSync('uploaded');
mkdirSync('uploaded/images');
});
afterEach(() => {
Config.remove('settings.disk.local.directory');
const contents = readdirSync('uploaded/images');
for (const content of contents) {
unlinkSync(join('uploaded/images', content));
}
rmdirSync('uploaded/images');
rmdirSync('uploaded');
});
it('should return an HttpResponseBadRequest (multiple === undefined).', async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {
foobar: { required: true }
}
}, actual);
return request(app)
.post('/')
.field('name', 'hello')
.expect(400)
.expect({
body: {
error: 'MISSING_FILE',
message: 'The file "foobar" is required.'
}
});
});
it('should return an HttpResponseBadRequest (multiple === false).', async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {
foobar: { required: true, multiple: false }
}
}, actual);
return request(app)
.post('/')
.field('name', 'hello')
.expect(400)
.expect({
body: {
error: 'MISSING_FILE',
message: 'The file "foobar" is required.'
}
});
});
it('should return an HttpResponseBadRequest (multiple === true).', async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {
foobar: { required: true, multiple: true }
}
}, actual);
return request(app)
.post('/')
.field('name', 'hello')
.expect(400)
.expect({
body: {
error: 'MISSING_FILE',
message: 'The file "foobar" is required.'
}
});
});
it('should not have uploaded the other files.', async () => {
const app = await createAppWithHook({
files: {
foobar: { required: false, multiple: true, saveTo: 'images' },
foobar2: { required: false, multiple: false, saveTo: 'images' },
foobar3: { required: false, multiple: false, saveTo: 'images' },
foobar4: { required: false, multiple: false },
requiredFoobar: { required: true },
}
}, { body: null });
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'))
.attach('foobar', createReadStream('src/image.test2.png'))
.attach('foobar2', createReadStream('src/image.test2.png'))
.attach('foobar4', createReadStream('src/image.test2.png'))
.field('name', 'hello')
.expect(400); // Test that no error is rejected in the hook (error 500).
strictEqual(readdirSync('uploaded/images').length, 0);
});
});
describe('when a file is uploaded and saveTo is undefined', () => {
it('should set ctx.request.files with the buffered file if the option "multiple" is not defined.', async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {
foobar: { required: true }
}
}, actual);
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'))
.expect(200);
deepStrictEqual(actual.body.files.foobar, new File({
buffer: readFileSync('src/image.test.png'),
encoding: '7bit',
filename: 'image.test.png',
mimeType: 'image/png',
}));
});
it('should set ctx.request.files with the buffered file if the option "multiple" is "false".', async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {
foobar: { required: true, multiple: false }
}
}, actual);
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'))
.expect(200);
deepStrictEqual(actual.body.files.foobar, new File({
buffer: readFileSync('src/image.test.png'),
encoding: '7bit',
filename: 'image.test.png',
mimeType: 'image/png',
}));
});
it('should set ctx.request.files with an array of the buffered fileS if the option "multiple" is "true".',
async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {
foobar: { required: true, multiple: true }
}
}, actual);
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'))
.attach('foobar', createReadStream('src/image.test2.png'))
.expect(200);
deepStrictEqual(actual.body.files.foobar, [
new File({
buffer: readFileSync('src/image.test.png'),
encoding: '7bit',
filename: 'image.test.png',
mimeType: 'image/png',
}),
new File({
buffer: readFileSync('src/image.test2.png'),
encoding: '7bit',
filename: 'image.test2.png',
mimeType: 'image/png',
}),
]);
});
});
describe('when a file is uploaded and saveTo is defined', () => {
let disk: Disk;
beforeEach(() => {
Config.set('settings.disk.local.directory', 'uploaded');
Config.set('settings.logErrors', false);
mkdirSync('uploaded');
mkdirSync('uploaded/images');
disk = createService(Disk);
});
afterEach(() => {
Config.remove('settings.disk.local.directory');
Config.remove('settings.logErrors');
const contents = readdirSync('uploaded/images');
for (const content of contents) {
unlinkSync(join('uploaded/images', content));
}
rmdirSync('uploaded/images');
rmdirSync('uploaded');
});
it('should not kill the process if Disk.write throws an error.', async () => {
Config.set('settings.disk.driver', '@foal/internal-test');
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {
foobar: { required: false, saveTo: 'images' },
foobar2: { required: false },
}
}, actual);
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'))
.expect(500);
});
it('should not kill the process if Disk.write rejects an error.', async () => {
Config.remove('settings.disk.local.directory');
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {
foobar: { required: false, saveTo: 'images' },
foobar2: { required: false }
}
}, actual);
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'))
.expect(500);
});
it('should save the file to the disk and set ctx.request.files with its path'
+ ' if the option "multiple" is not defined.', async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {
foobar: { required: false, saveTo: 'images' }
}
}, actual);
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'))
.expect(200);
const foobar = actual.body.files.foobar;
strictEqual(typeof foobar, 'object');
notStrictEqual(foobar, null);
const path = foobar.path;
strictEqual(typeof path, 'string');
deepStrictEqual(
readFileSync('src/image.test.png'),
(await disk.read(path, 'buffer')).file
);
strictEqual(foobar.encoding, '7bit');
strictEqual(foobar.mimeType, 'image/png');
strictEqual(foobar.filename, 'image.test.png');
}
);
it('should save the file to the disk and set ctx.request.files with its path'
+ ' if the option "multiple" is "false".', async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {
foobar: { required: false, multiple: false, saveTo: 'images' }
}
}, actual);
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'))
.expect(200);
const foobar = actual.body.files.foobar;
strictEqual(typeof foobar, 'object');
notStrictEqual(foobar, null);
const path = foobar.path;
strictEqual(typeof path, 'string');
deepStrictEqual(
readFileSync('src/image.test.png'),
(await disk.read(path, 'buffer')).file
);
strictEqual(foobar.encoding, '7bit');
strictEqual(foobar.mimeType, 'image/png');
strictEqual(foobar.filename, 'image.test.png');
}
);
it('should save the file to the disk and set ctx.request.files with an array'
+ ' of the pathS if the option "multiple" is "true".', async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {
foobar: { required: false, multiple: true, saveTo: 'images' }
}
}, actual);
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'))
.attach('foobar', createReadStream('src/image.test2.png'))
.expect(200);
const foobar = actual.body.files.foobar;
strictEqual(typeof foobar, 'object');
notStrictEqual(foobar, null);
if (!Array.isArray(foobar)) {
throw new Error('"files.foobar" should an array.');
}
const path = foobar[0].path;
strictEqual(typeof path, 'string');
deepStrictEqual(
readFileSync('src/image.test.png'),
(await disk.read(path, 'buffer')).file
);
strictEqual(foobar[0].encoding, '7bit');
strictEqual(foobar[0].mimeType, 'image/png');
strictEqual(foobar[0].filename, 'image.test.png');
const path2 = foobar[1].path;
strictEqual(typeof path2, 'string');
deepStrictEqual(
readFileSync('src/image.test2.png'),
(await disk.read(path2, 'buffer')).file
);
strictEqual(foobar[1].encoding, '7bit');
strictEqual(foobar[1].mimeType, 'image/png');
strictEqual(foobar[1].filename, 'image.test2.png');
}
);
it('should keep the extension of the file if it has one.', async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {
foobar: { required: false, saveTo: 'images' }
}
}, actual);
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'))
.expect(200);
strictEqual(typeof actual.body.files.foobar, 'object');
notStrictEqual(actual.body.files.foobar, null);
const path: string = actual.body.files.foobar.path;
strictEqual(typeof path, 'string');
const fragments = path.split('.');
strictEqual(fragments.length, 2);
strictEqual(fragments[1], 'png');
});
it('should not keep the extension of the file if it has none.', async () => {
const actual: { body: any } = { body: null };
const app = await createAppWithHook({
files: {
foobar: { required: false, saveTo: 'images' }
}
}, actual);
await request(app)
.post('/')
.attach('foobar', createReadStream('src/image.test.png'), { filename: 'my_image' })
.expect(200);
strictEqual(typeof actual.body.files.foobar, 'object');
notStrictEqual(actual.body.files.foobar, null);
const path: string = actual.body.files.foobar.path;
strictEqual(typeof path, 'string');
const fragments = path.split('.');
strictEqual(fragments.length, 1);
});
});
describe('should define an API specification', () => {
const schema: MultipartFormDataSchema = {
fields: {
bar: { type: 'integer' },
foo: { type: 'integer' },
},
files: {
album: { required: false, multiple: true },
profile: { required: true }
}
};
const expectedRequestBody: IApiRequestBody = {
content: {
'multipart/form-data': {
schema: {
properties: {
album: {
items: {
format: 'binary',
type: 'string',
},
type: 'array',
},
bar: {
type: 'integer'
},
foo: {
type: 'integer'
},
profile: {
format: 'binary',
type: 'string',
},
},
required: [ 'bar', 'foo', 'profile' ],
type: 'object',
}
}
}
};
it('unless options.openapi is false.', () => {
@ValidateMultipartFormDataBody(schema, { openapi: false })
class Foobar {}
deepStrictEqual(getApiRequestBody(Foobar), undefined);
});
it('with the proper request body.', () => {
@ValidateMultipartFormDataBody(schema)
class Foobar {}
const actualRequestBody = getApiRequestBody(Foobar);
deepStrictEqual(actualRequestBody, expectedRequestBody);
});
});
}); | the_stack |
import * as vscode from "vscode";
import type { Argument, InputOr } from ".";
import { closestSurroundedBy, Context, Direction, keypress, Lines, moveTo, moveWhile, Pair, pair, Positions, prompt, Range, search, SelectionBehavior, Selections, Shift, surroundedBy, wordBoundary } from "../api";
import { CharSet } from "../utils/charset";
import { ArgumentError, assert } from "../utils/errors";
import { execRange } from "../utils/regexp";
/**
* Update selections based on the text surrounding them.
*/
declare module "./seek";
/**
* Select to character (excluded).
*
* @keys `t` (normal)
*
* #### Variants
*
* | Title | Identifier | Keybinding | Command |
* | ---------------------------------------- | -------------------------- | ---------------- | -------------------------------------------------------------- |
* | Extend to character (excluded) | `extend` | `s-t` (normal) | `[".seek", { shift: "extend" }]` |
* | Select to character (excluded, backward) | `backward` | `a-t` (normal) | `[".seek", { direction: -1 }]` |
* | Extend to character (excluded, backward) | `extend.backward` | `s-a-t` (normal) | `[".seek", { shift: "extend", direction: -1 }]` |
* | Select to character (included) | `included` | `f` (normal) | `[".seek", { include: true }]` |
* | Extend to character (included) | `included.extend` | `s-f` (normal) | `[".seek", { include: true, shift: "extend" }]` |
* | Select to character (included, backward) | `included.backward` | `a-f` (normal) | `[".seek", { include: true, direction: -1 }]` |
* | Extend to character (included, backward) | `included.extend.backward` | `s-a-f` (normal) | `[".seek", { include: true, shift: "extend", direction: -1 }]` |
*/
export async function seek(
_: Context,
inputOr: InputOr<string>,
repetitions: number,
direction = Direction.Forward,
shift = Shift.Select,
include: Argument<boolean> = false,
) {
const input = await inputOr(() => keypress(_));
Selections.update.byIndex((_, selection, document) => {
let position: vscode.Position | undefined = Selections.seekFrom(selection, -direction);
for (let i = 0; i < repetitions; i++) {
position = Positions.offset(position, direction, document);
if (position === undefined) {
return undefined;
}
position = moveTo.excluded(direction, input, position, document);
if (position === undefined) {
return undefined;
}
}
if (include && !(shift === Shift.Extend && direction === Direction.Backward && position.isAfter(selection.anchor))) {
position = Positions.offset(position, input.length * direction);
if (position === undefined) {
return undefined;
}
}
return Selections.shift(selection, position, shift);
});
}
const defaultEnclosingPatterns = [
"\\[", "\\]",
"\\(", "\\)",
"\\{", "\\}",
"/\\*", "\\*/",
"\\bbegin\\b", "\\bend\\b",
];
/**
* Select to next enclosing character.
*
* @keys `m` (normal)
*
* #### Variants
*
* | Title | Identifier | Keybinding | Command |
* | -------------------------------------- | --------------------------- | ---------------- | --------------------------------------------------------- |
* | Extend to next enclosing character | `enclosing.extend` | `s-m` (normal) | `[".seek.enclosing", { shift: "extend" }]` |
* | Select to previous enclosing character | `enclosing.backward` | `a-m` (normal) | `[".seek.enclosing", { direction: -1 }]` |
* | Extend to previous enclosing character | `enclosing.extend.backward` | `s-a-m` (normal) | `[".seek.enclosing", { shift: "extend", direction: -1 }]` |
*/
export function enclosing(
_: Context,
direction = Direction.Forward,
shift = Shift.Select,
open: Argument<boolean> = true,
pairs: Argument<readonly string[]> = defaultEnclosingPatterns,
) {
ArgumentError.validate(
"pairs",
(pairs.length & 1) === 0,
"an even number of pairs must be given",
);
const selectionBehavior = _.selectionBehavior,
compiledPairs = [] as Pair[];
for (let i = 0; i < pairs.length; i += 2) {
compiledPairs.push(pair(new RegExp(pairs[i], "mu"), new RegExp(pairs[i + 1], "mu")));
}
// This command intentionally ignores repetitions to be consistent with
// Kakoune.
// It only finds one next enclosing character and drags only once to its
// matching counterpart. Repetitions > 1 does exactly the same with rep=1,
// even though executing the command again will jump back and forth.
Selections.update.byIndex((_, selection, document) => {
// First, find an enclosing char (which may be the current character).
let currentCharacter = selection.active;
if (selectionBehavior === SelectionBehavior.Caret) {
if (direction === Direction.Backward && selection.isReversed) {
// When moving backwards, the first character to consider is the
// character to the left, not the right. However, we hackily special
// case `|[foo]>` (> is anchor, | is active) to jump to the end in the
// current group.
currentCharacter = Positions.previous(currentCharacter, document) ?? currentCharacter;
} else if (direction === Direction.Forward && !selection.isReversed && !selection.isEmpty) {
// Similarly, we special case `<[foo]|` to jump back in the current
// group.
currentCharacter = Positions.previous(currentCharacter, document) ?? currentCharacter;
}
}
if (selectionBehavior === SelectionBehavior.Caret && direction === Direction.Backward) {
// When moving backwards, the first character to consider is the
// character to the left, not the right.
currentCharacter = Positions.previous(currentCharacter, document) ?? currentCharacter;
}
const enclosedRange = closestSurroundedBy(compiledPairs, direction, currentCharacter, open, document);
if (enclosedRange === undefined) {
return undefined;
}
if (shift === Shift.Extend) {
return new vscode.Selection(selection.anchor, enclosedRange.active);
}
return enclosedRange;
});
}
/**
* Select to next word start.
*
* Select the word and following whitespaces on the right of the end of each selection.
*
* @keys `w` (normal)
*
* #### Variants
*
* | Title | Identifier | Keybinding | Command |
* | -------------------------------------------- | ------------------------- | ---------------- | -------------------------------------------------------------------------------- |
* | Extend to next word start | `word.extend` | `s-w` (normal) | `[".seek.word", { shift: "extend" }]` |
* | Select to previous word start | `word.backward` | `b` (normal) | `[".seek.word", { direction: -1 }]` |
* | Extend to previous word start | `word.extend.backward` | `s-b` (normal) | `[".seek.word", { shift: "extend", direction: -1 }]` |
* | Select to next non-whitespace word start | `word.ws` | `a-w` (normal) | `[".seek.word", { ws: true }]` |
* | Extend to next non-whitespace word start | `word.ws.extend` | `s-a-w` (normal) | `[".seek.word", { ws: true, shift: "extend" }]` |
* | Select to previous non-whitespace word start | `word.ws.backward` | `a-b` (normal) | `[".seek.word", { ws: true, direction: -1 }]` |
* | Extend to previous non-whitespace word start | `word.ws.extend.backward` | `s-a-b` (normal) | `[".seek.word", { ws: true, shift: "extend", direction: -1 }]` |
* | Select to next word end | `wordEnd` | `e` (normal) | `[".seek.word", { stopAtEnd: true }]` |
* | Extend to next word end | `wordEnd.extend` | `s-e` (normal) | `[".seek.word", { stopAtEnd: true , shift: "extend" }]` |
* | Select to next non-whitespace word end | `wordEnd.ws` | `a-e` (normal) | `[".seek.word", { stopAtEnd: true , ws: true }]` |
* | Extend to next non-whitespace word end | `wordEnd.ws.extend` | `s-a-e` (normal) | `[".seek.word", { stopAtEnd: true , ws: true, shift: "extend" }]` |
*/
export function word(
_: Context,
repetitions: number,
stopAtEnd: Argument<boolean> = false,
ws: Argument<boolean> = false,
direction = Direction.Forward,
shift = Shift.Select,
) {
const charset = ws ? CharSet.NonBlank : CharSet.Word;
Selections.update.withFallback.byIndex((_i, selection) => {
const anchor = Selections.seekFrom(selection, direction, selection.anchor, _);
let active = Selections.seekFrom(selection, direction, selection.active, _);
for (let i = 0; i < repetitions; i++) {
const mapped = wordBoundary(direction, active, stopAtEnd, charset, _);
if (mapped === undefined) {
if (direction === Direction.Backward && active.line > 0) {
// This is a special case in Kakoune and we try to mimic it
// here.
// Instead of overflowing, put anchor at document start and
// active always on the first character on the second line.
const end = _.selectionBehavior === SelectionBehavior.Caret
? Positions.lineStart(1)
: (Lines.isEmpty(1) ? Positions.lineStart(2) : Positions.at(1, 1));
return new vscode.Selection(Positions.lineStart(0), end);
}
if (shift === Shift.Extend) {
return [new vscode.Selection(anchor, selection.active)];
}
return [selection];
}
selection = mapped;
active = selection.active;
}
if (shift === Shift.Extend) {
return new vscode.Selection(anchor, selection.active);
}
return selection;
});
}
let lastObjectInput: string | undefined;
/**
* Select object.
*
* @param input The pattern of object to select; see
* [object patterns](#object-patterns) below for more information.
* @param inner If `true`, only the "inner" part of the object will be selected.
* The definition of the "inner" part depends on the object.
* @param where What end of the object should be sought. If `undefined`, the
* object will be selected from start to end regardless of the `shift`.
*
* #### Object patterns
* - Pairs: `<regexp>(?#inner)<regexp>`.
* - Character sets: `[<characters>]+`.
* - Can be preceded by `(?<before>[<characters>]+)` and followed by
* `(?<after>[<character>]+)` for whole objects.
* - Matches that may only span a single line: `(?#singleline)<regexp>`.
* - Predefined: `(?#predefined=<argument | paragraph | sentence>)`.
*
* #### Variants
*
* | Title | Identifier | Keybinding | Command |
* | ---------------------------- | ------------------------------ | ------------------------------ | ---------------------------------------------------------------------------------------------- |
* | Select whole object | `askObject` | `a-a` (normal), `a-a` (insert) | `[".openMenu", { input: "object" }]` |
* | Select inner object | `askObject.inner` | `a-i` (normal), `a-i` (insert) | `[".openMenu", { input: "object", pass: [{ inner: true }] }]` |
* | Select to whole object start | `askObject.start` | `[` (normal) | `[".openMenu", { input: "object", pass: [{ where: "start" }] }]` |
* | Extend to whole object start | `askObject.start.extend` | `{` (normal) | `[".openMenu", { input: "object", pass: [{ where: "start", shift: "extend" }] }]` |
* | Select to inner object start | `askObject.inner.start` | `a-[` (normal) | `[".openMenu", { input: "object", pass: [{ inner: true, where: "start" }] }]` |
* | Extend to inner object start | `askObject.inner.start.extend` | `a-{` (normal) | `[".openMenu", { input: "object", pass: [{ inner: true, where: "start", shift: "extend" }] }]` |
* | Select to whole object end | `askObject.end` | `]` (normal) | `[".openMenu", { input: "object", pass: [{ where: "end" }] }]` |
* | Extend to whole object end | `askObject.end.extend` | `}` (normal) | `[".openMenu", { input: "object", pass: [{ where: "end" , shift: "extend" }] }]` |
* | Select to inner object end | `askObject.inner.end` | `a-]` (normal) | `[".openMenu", { input: "object", pass: [{ inner: true, where: "end" }] }]` |
* | Extend to inner object end | `askObject.inner.end.extend` | `a-}` (normal) | `[".openMenu", { input: "object", pass: [{ inner: true, where: "end" , shift: "extend" }] }]` |
*/
export async function object(
_: Context,
inputOr: InputOr<string>,
inner: Argument<boolean> = false,
where?: Argument<"start" | "end">,
shift = Shift.Select,
) {
const input = await inputOr(() => prompt({
prompt: "Object description",
value: lastObjectInput,
}));
let match: RegExpExecArray | null;
if (match = /^(.+)\(\?#inner\)(.+)$/s.exec(input)) {
const openRe = new RegExp(preprocessRegExp(match[1]), "u"),
closeRe = new RegExp(preprocessRegExp(match[2]), "u"),
p = pair(openRe, closeRe);
if (where === "start") {
return Selections.update.byIndex((_i, selection) => {
const startResult = p.searchOpening(Selections.activeStart(selection, _));
if (startResult === undefined) {
return;
}
const start = inner
? Positions.offset(startResult[0], startResult[1][0].length, _.document) ?? startResult[0]
: startResult[0];
return Selections.shift(selection, start, shift, _);
});
}
if (where === "end") {
return Selections.update.byIndex((_i, selection) => {
const endResult = p.searchClosing(Selections.activeEnd(selection, _));
if (endResult === undefined) {
return;
}
const end = inner
? endResult[0]
: Positions.offset(endResult[0], endResult[1][0].length, _.document) ?? endResult[0];
return Selections.shift(selection, end, shift, _);
});
}
if (_.selectionBehavior === SelectionBehavior.Character) {
const startRe = new RegExp("^" + openRe.source, openRe.flags);
return Selections.update.byIndex((_i, selection) => {
// If the selection behavior is character and the current character
// corresponds to the start of a pair, we select from here.
const searchStart = Selections.activeStart(selection, _),
searchStartResult = search(Direction.Forward, startRe, searchStart);
if (searchStartResult?.[1][0].length === 1) {
const start = searchStartResult[0],
innerStart = Positions.offset(start, searchStartResult[1][0].length, _.document)!,
endResult = p.searchClosing(innerStart);
if (endResult === undefined) {
return undefined;
}
if (inner) {
return new vscode.Selection(innerStart, endResult[0]);
}
return new vscode.Selection(
start,
Positions.offset(endResult[0], endResult[1][0].length, _.document)!,
);
}
// Otherwise, we select from the end of the current selection.
return surroundedBy([p], Selections.activeStart(selection, _), !inner, _.document);
});
}
return Selections.update.byIndex(
(_i, selection) => surroundedBy([p], Selections.activeStart(selection, _), !inner, _.document),
);
}
if (match =
/^(?:\(\?<before>(\[.+?\])\+\))?(\[.+\])\+(?:\(\?<after>(\[.+?\])\+\))?$/.exec(input)) {
const re = new RegExp(match[2], "u"),
beforeRe = inner || match[1] === undefined ? undefined : new RegExp(match[1], "u"),
afterRe = inner || match[3] === undefined ? undefined : new RegExp(match[3], "u");
return shiftWhere(
_,
(selection, _) => {
let start = moveWhile.backward((c) => re.test(c), selection.active, _.document),
end = moveWhile.forward((c) => re.test(c), selection.active, _.document);
if (beforeRe !== undefined) {
start = moveWhile.backward((c) => beforeRe.test(c), start, _.document);
}
if (afterRe !== undefined) {
end = moveWhile.forward((c) => afterRe.test(c), end, _.document);
}
return new vscode.Selection(start, end);
},
shift,
where,
);
}
if (match = /^\(\?#singleline\)(.+)$/.exec(input)) {
const re = new RegExp(preprocessRegExp(match[1]), "u");
return shiftWhere(
_,
(selection, _) => {
const line = Selections.activeLine(selection),
lineText = _.document.lineAt(line).text,
matches = execRange(lineText, re);
// Find match at text position.
const character = Selections.activeCharacter(selection, _.document);
for (const m of matches) {
let [start, end] = m;
if (start <= character && character <= end) {
if (inner && m[2].groups !== undefined) {
const match = m[2];
if ("before" in match.groups!) {
start += match.groups.before.length;
}
if ("after" in match.groups!) {
end -= match.groups.after.length;
}
}
return new vscode.Selection(
new vscode.Position(line, start),
new vscode.Position(line, end),
);
}
}
return undefined;
},
shift,
where,
);
}
if (match = /^\(\?#predefined=(argument|indent|paragraph|sentence)\)$/.exec(input)) {
let f: Range.Seek;
switch (match[1]) {
case "argument":
case "indent":
case "paragraph":
case "sentence":
f = Range[match[1]];
break;
default:
assert(false);
}
let newSelections: vscode.Selection[];
if (where === "start") {
newSelections = Selections.map.byIndex((_i, selection, document) => {
const activePosition = Selections.activePosition(selection, _.document);
let shiftTo = f.start(activePosition, inner, document);
if (shiftTo.isEqual(activePosition)) {
const activePositionBefore = Positions.previous(activePosition, document);
if (activePositionBefore !== undefined) {
shiftTo = f.start(activePositionBefore, inner, document);
}
}
return Selections.shift(selection, shiftTo, shift, _);
});
} else if (where === "end") {
newSelections = Selections.map.byIndex((_i, selection, document) =>
Selections.shift(
selection,
f.end(selection.active, inner, document),
shift,
_,
),
);
} else {
newSelections = Selections.map.byIndex((_, selection, document) =>
f(selection.active, inner, document),
);
}
if (_.selectionBehavior === SelectionBehavior.Character) {
Selections.shiftEmptyLeft(newSelections, _.document);
}
return _.selections = newSelections;
}
throw new Error("unknown object " + JSON.stringify(input));
}
function preprocessRegExp(re: string) {
return re.replace(/\(\?#noescape\)/g, "(?<=(?<!\\\\)(?:\\\\{2})*)");
}
function shiftWhere(
context: Context,
f: (selection: vscode.Selection, context: Context) => vscode.Selection | undefined,
shift: Shift,
where: "start" | "end" | undefined,
) {
Selections.update.byIndex((_, selection) => {
const result = f(selection, context);
if (result === undefined) {
return undefined;
}
if (where === undefined) {
return result;
}
return Selections.shift(selection, result[where], shift, context);
});
} | the_stack |
import { FetchResult } from '@apollo/client'
import classNames from 'classnames'
import { isEqual } from 'lodash'
import React, { useCallback, useEffect, useState, FunctionComponent, Dispatch, SetStateAction } from 'react'
import { TelemetryProps } from '@sourcegraph/shared/src/telemetry/telemetryService'
import { ErrorLike } from '@sourcegraph/shared/src/util/errors'
import { Container, PageSelector } from '@sourcegraph/wildcard'
import { RepoSelectionMode } from '../../../auth/PostSignUpPage'
import { useSteps } from '../../../auth/Steps'
import { useAffiliatedRepos } from '../../../auth/useAffiliatedRepos'
import { useExternalServices } from '../../../auth/useExternalServices'
import { useSelectedRepos, selectedReposVar, MinSelectedRepo } from '../../../auth/useSelectedRepos'
import { AwayPrompt } from '../../../components/AwayPrompt'
import {
ExternalServiceKind,
Maybe,
SiteAdminRepositoryFields,
SetExternalServiceReposResult,
} from '../../../graphql-operations'
import { CheckboxRepositoryNode } from './RepositoryNode'
export interface AffiliatedReposReference {
submit: () => Promise<FetchResult<SetExternalServiceReposResult>[] | void>
}
interface authenticatedUser {
id: string
siteAdmin: boolean
tags: string[]
}
interface Props extends TelemetryProps {
authenticatedUser: authenticatedUser
onRepoSelectionModeChange: Dispatch<SetStateAction<RepoSelectionMode>>
repoSelectionMode: RepoSelectionMode
onError: (error: ErrorLike) => void
}
export interface Repo {
name: string
codeHost: Maybe<{ kind: ExternalServiceKind; id: string; displayName: string }>
private: boolean
mirrorInfo?: SiteAdminRepositoryFields['mirrorInfo']
}
interface GitHubConfig {
repos?: string[]
repositoryQuery?: string[]
token: 'REDACTED'
url: string
}
interface GitLabConfig {
projectQuery?: string[]
projects?: { name: string }[]
token: 'REDACTED'
url: string
}
const PER_PAGE = 20
// project queries that are used when user syncs all repos from a code host
const GITLAB_SYNC_ALL_PROJECT_QUERY = 'projects?membership=true&archived=no'
const GITHUB_SYNC_ALL_PROJECT_QUERY = 'affiliated'
// initial state constants
const emptyRepos: Repo[] = []
const initialRepoState = {
repos: emptyRepos,
loading: false,
loaded: false,
}
const initialSelectionState = {
repos: new Map<string, Repo>(),
loaded: false,
radio: '',
}
/**
* A page to manage the repositories a user syncs from their connected code hosts.
*/
export const SelectAffiliatedRepos: FunctionComponent<Props> = ({
authenticatedUser,
onRepoSelectionModeChange,
repoSelectionMode,
telemetryService,
onError,
}) => {
useEffect(() => {
telemetryService.logViewEvent('UserSettingsRepositories')
}, [telemetryService])
const { setComplete, resetToTheRight, currentIndex } = useSteps()
const { externalServices, errorServices } = useExternalServices(authenticatedUser.id)
const { affiliatedRepos, errorAffiliatedRepos } = useAffiliatedRepos(authenticatedUser.id)
const { selectedRepos, errorSelectedRepos } = useSelectedRepos(authenticatedUser.id)
const fetchingError = errorServices || errorAffiliatedRepos || errorSelectedRepos
useEffect(() => {
if (fetchingError) {
onError(fetchingError)
}
}, [fetchingError, onError])
// set up state hooks
const [currentPage, setPage] = useState(1)
const [repoState, setRepoState] = useState(initialRepoState)
const [onloadSelectedRepos, setOnloadSelectedRepos] = useState<string[]>([])
const [selectionState, setSelectionState] = useState(initialSelectionState)
const [didSelectionChange, setDidSelectionChange] = useState(false)
const [query, setQuery] = useState('')
const [codeHostFilter, setCodeHostFilter] = useState('')
const [filteredRepos, setFilteredRepos] = useState<Repo[]>([])
const getRepoServiceAndName = (repo: Repo): string => `${repo.codeHost?.kind || 'unknown'}/${repo.name}`
useEffect(() => {
if (externalServices && affiliatedRepos) {
const codeHostsHaveSyncAllQuery = []
for (const host of externalServices) {
if (host.lastSyncError || host.warning) {
continue
}
const cfg = JSON.parse(host.config) as GitHubConfig | GitLabConfig
switch (host.kind) {
case ExternalServiceKind.GITLAB: {
const gitLabCfg = cfg as GitLabConfig
if (Array.isArray(gitLabCfg.projectQuery)) {
codeHostsHaveSyncAllQuery.push(
gitLabCfg.projectQuery.includes(GITLAB_SYNC_ALL_PROJECT_QUERY)
)
}
break
}
case ExternalServiceKind.GITHUB: {
const gitHubCfg = cfg as GitHubConfig
if (Array.isArray(gitHubCfg.repositoryQuery)) {
codeHostsHaveSyncAllQuery.push(
gitHubCfg.repositoryQuery.includes(GITHUB_SYNC_ALL_PROJECT_QUERY)
)
}
break
}
}
}
const selectedAffiliatedRepos = new Map<string, Repo>()
const cachedSelectedRepos = selectedReposVar()
const userSelectedRepos = repoSelectionMode === 'all' ? [] : cachedSelectedRepos || selectedRepos || []
const affiliatedReposWithMirrorInfo = affiliatedRepos.map(affiliatedRepo => {
let foundInSelected: SiteAdminRepositoryFields | MinSelectedRepo | null = null
for (const selectedRepo of userSelectedRepos) {
const {
name,
externalRepository: { serviceType: selectedRepoServiceType },
} = selectedRepo
const selectedRepoName = name.slice(name.indexOf('/') + 1)
if (
selectedRepoName === affiliatedRepo.name &&
selectedRepoServiceType === affiliatedRepo.codeHost?.kind.toLocaleLowerCase()
) {
foundInSelected = selectedRepo
break
}
}
if (foundInSelected) {
// save off only selected repos
selectedAffiliatedRepos.set(getRepoServiceAndName(affiliatedRepo), affiliatedRepo)
}
return affiliatedRepo
})
// sort affiliated repos with already selected repos at the top
affiliatedReposWithMirrorInfo.sort((repoA, repoB): number => {
const isRepoASelected = selectedAffiliatedRepos.has(getRepoServiceAndName(repoA))
const isRepoBSelected = selectedAffiliatedRepos.has(getRepoServiceAndName(repoB))
if (!isRepoASelected && isRepoBSelected) {
return 1
}
if (isRepoASelected && !isRepoBSelected) {
return -1
}
return 0
})
// safe off initial selection state
setOnloadSelectedRepos(previousValue => [...previousValue, ...selectedAffiliatedRepos.keys()])
/**
* 1. if every code host has a project query to sync all repos or the
* number of affiliated repos equals to the number of selected repos -
* set radio to 'all'
* 2. if only some repos were selected - set radio to 'selected'
* 3. if no repos selected - empty state
*/
const radioSelectOption =
repoSelectionMode ||
(externalServices.length === codeHostsHaveSyncAllQuery.length &&
codeHostsHaveSyncAllQuery.every(Boolean)
? 'all'
: selectedAffiliatedRepos.size > 0
? 'selected'
: '')
onRepoSelectionModeChange(radioSelectOption as RepoSelectionMode)
// set sorted repos and mark as loaded
setRepoState(previousRepoState => ({
...previousRepoState,
repos: affiliatedReposWithMirrorInfo,
loaded: true,
}))
setSelectionState({
repos: selectedAffiliatedRepos,
radio: radioSelectOption,
loaded: true,
})
}
}, [
externalServices,
affiliatedRepos,
selectedRepos,
onRepoSelectionModeChange,
setComplete,
currentIndex,
repoSelectionMode,
])
// select repos by code host and query
useEffect(() => {
// filter our set of repos based on query & code host selection
const filtered: Repo[] = []
for (const repo of repoState.repos) {
// filtering by code hosts
if (codeHostFilter !== '' && repo.codeHost?.id !== codeHostFilter) {
continue
}
const queryLoweCase = query.toLowerCase()
const nameLowerCase = repo.name.toLowerCase()
if (!nameLowerCase.includes(queryLoweCase)) {
continue
}
filtered.push(repo)
}
// set new filtered pages and reset the pagination
setFilteredRepos(filtered)
setPage(1)
}, [repoState.repos, codeHostFilter, query])
const handleRadioSelect = (changeEvent: React.ChangeEvent<HTMLInputElement>): void => {
setSelectionState({
repos: selectionState.repos,
radio: changeEvent.currentTarget.value,
loaded: selectionState.loaded,
})
onRepoSelectionModeChange(changeEvent.currentTarget.value as RepoSelectionMode)
}
// calculate if the current step is completed based on repo selection when
// we toggle between "Sync all" and individual repo selection checkboxes
useEffect(() => {
if (selectionState.radio) {
if (selectionState.radio === 'all') {
setComplete(currentIndex, true)
} else {
const hasSelectedRepos = selectionState.repos.size !== 0
if (hasSelectedRepos) {
setComplete(currentIndex, true)
} else {
setComplete(currentIndex, false)
resetToTheRight(currentIndex)
}
}
}
}, [currentIndex, resetToTheRight, selectionState.radio, selectionState.repos.size, setComplete])
const hasCodeHosts = Array.isArray(externalServices) && externalServices.length > 0
const modeSelect: JSX.Element = (
<>
<label className="d-flex flex-row align-items-baseline">
<input type="radio" value="all" checked={selectionState.radio === 'all'} onChange={handleRadioSelect} />
<div className="d-flex flex-column ml-2">
<p className="mb-0">Sync all repositories</p>
<p className="user-settings-repos__text-light text-muted">
Will sync all current and future public and private repositories
</p>
</div>
</label>
<label className="d-flex flex-row align-items-baseline mb-0">
<input
type="radio"
value="selected"
checked={selectionState.radio === 'selected'}
onChange={handleRadioSelect}
/>
<div className="d-flex flex-column ml-2">
<p className="mb-0">Sync selected repositories</p>
</div>
</label>
</>
)
const filterControls: JSX.Element = (
<div className="w-100 d-inline-flex justify-content-between flex-row mt-3">
<div className="d-inline-flex flex-row mr-3 align-items-baseline">
<p className="text-xl-center text-nowrap mr-2">Code Host:</p>
<select
className="form-control"
name="code-host"
aria-label="select code host type"
onChange={event => setCodeHostFilter(event.target.value)}
>
<option key="any" value="" label="Any" />
{externalServices?.map(value => (
<option key={value.id} value={value.id} label={value.displayName} />
))}
</select>
</div>
<input
className="form-control user-settings-repos__filter-input"
type="search"
placeholder="Filter..."
name="query"
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"
spellCheck={false}
onChange={event => {
setQuery(event.target.value)
}}
/>
</div>
)
const saveRepoSelection = (repos: Repo[]): void => {
// save off last selected repos
const selection = repos.reduce((accumulator, repo) => {
const serviceType = repo.codeHost?.kind.toLowerCase()
const serviceName = serviceType ? `${serviceType}.com` : 'unknown'
accumulator.push({
name: `${serviceName}/${repo.name}`,
externalRepository: { serviceType: serviceType || 'unknown', id: repo.codeHost?.id },
})
return accumulator
}, [] as MinSelectedRepo[])
// safe off repo selection to apollo
selectedReposVar(selection)
}
const onRepoClicked = useCallback(
(repo: Repo) => (): void => {
const clickedRepo = getRepoServiceAndName(repo)
const newSelection = new Map(selectionState.repos)
if (newSelection.has(clickedRepo)) {
newSelection.delete(clickedRepo)
} else {
newSelection.set(clickedRepo, repo)
}
const currentlySelectedRepos = [...newSelection.keys()]
const didChange = !isEqual(currentlySelectedRepos.sort(), onloadSelectedRepos.sort())
// set current step as complete if user had already selected repos or made changes
if (didChange || onloadSelectedRepos.length !== 0) {
setComplete(currentIndex, true)
setDidSelectionChange(true)
} else {
setComplete(currentIndex, false)
resetToTheRight(currentIndex)
}
saveRepoSelection([...newSelection.values()])
// set new selection state
setSelectionState({
repos: newSelection,
radio: selectionState.radio,
loaded: selectionState.loaded,
})
},
[
currentIndex,
onloadSelectedRepos,
resetToTheRight,
selectionState.loaded,
selectionState.radio,
selectionState.repos,
setComplete,
]
)
const getSelectedReposByCodeHost = (codeHostId: string = ''): Repo[] => {
const selectedRepos = [...selectionState.repos.values()]
// if no specific code host selected, return all selected repos
return codeHostId ? selectedRepos.filter(({ codeHost }) => codeHost?.id === codeHostId) : selectedRepos
}
const areAllReposSelected = (): boolean => {
if (selectionState.repos.size === 0) {
return false
}
const selectedRepos = getSelectedReposByCodeHost(codeHostFilter)
return selectedRepos.length === filteredRepos.length
}
const selectAll = (): void => {
const newSelection = new Map<string, Repo>()
// if not all repos are selected, we should select all, otherwise empty the selection
if (selectionState.repos.size !== filteredRepos.length) {
for (const repo of filteredRepos) {
newSelection.set(getRepoServiceAndName(repo), repo)
}
}
saveRepoSelection([...newSelection.values()])
setSelectionState({
repos: newSelection,
loaded: selectionState.loaded,
radio: selectionState.radio,
})
}
const rows: JSX.Element = (
<tbody>
<tr className="align-items-baseline d-flex" key="header">
<td className="user-settings-repos__repositorynode p-2 w-100 d-flex align-items-center border-top-0 border-bottom">
<input
id="select-all-repos"
className="mr-3"
type="checkbox"
checked={areAllReposSelected()}
onChange={selectAll}
/>
<label
htmlFor="select-all-repos"
className={classNames({
'text-muted': selectionState.repos.size === 0,
'text-body': selectionState.repos.size !== 0,
'mb-0': true,
})}
>
{(selectionState.repos.size > 0 && (
<small>{`${selectionState.repos.size} ${
selectionState.repos.size === 1 ? 'repository' : 'repositories'
} selected`}</small>
)) || <small>Select all</small>}
</label>
</td>
</tr>
{filteredRepos.map((repo, index) => {
if (index < (currentPage - 1) * PER_PAGE || index >= currentPage * PER_PAGE) {
return
}
const serviceAndRepoName = getRepoServiceAndName(repo)
return (
<CheckboxRepositoryNode
name={repo.name}
key={serviceAndRepoName}
onClick={onRepoClicked(repo)}
checked={selectionState.repos.has(serviceAndRepoName)}
serviceType={repo.codeHost?.kind || 'unknown'}
isPrivate={repo.private}
/>
)
})}
</tbody>
)
const modeSelectShimmer: JSX.Element = (
<div className="container">
<div className="mt-2 row">
<div className="user-settings-repos__shimmer-circle mr-2" />
<div className="user-settings-repos__shimmer mb-1 p-2 border-top-0 col-sm-2" />
</div>
<div className="mt-1 ml-2 row">
<div className="user-settings-repos__shimmer mb-3 p-2 ml-1 border-top-0 col-sm-6" />
</div>
<div className="mt-2 row">
<div className="user-settings-repos__shimmer-circle mr-2" />
<div className="user-settings-repos__shimmer p-2 mb-1 border-top-0 col-sm-3" />
</div>
</div>
)
return (
<div className="user-settings-repos mb-0">
<Container>
<ul className="list-group">
<li className="list-group-item user-settings-repos__container" key="from-code-hosts">
<div>
{/* display type of repo sync radio buttons or shimmer when appropriate */}
{hasCodeHosts && selectionState.loaded ? modeSelect : modeSelectShimmer}
{hasCodeHosts && selectionState.radio === 'selected' && (
<div className="ml-4">
{filterControls}
<table role="grid" className="table">
{
// if the repos are loaded display the rows of repos
repoState.loaded && rows
}
</table>
{filteredRepos.length > 0 && (
<PageSelector
currentPage={currentPage}
onPageChange={setPage}
totalPages={Math.ceil(filteredRepos.length / PER_PAGE)}
className="pt-4"
/>
)}
</div>
)}
</div>
</li>
</ul>
</Container>
<AwayPrompt
header="Discard unsaved changes?"
message="Currently synced repositories will be unchanged"
button_ok_text="Discard"
when={didSelectionChange}
/>
</div>
)
} | the_stack |
import { async, ComponentFixture, TestBed, fakeAsync, tick, flush } from '@angular/core/testing';
import { AlertDetailsComponent, AlertCommentWrapper } from './alert-details.component';
import { SharedModule } from 'app/shared/shared.module';
import { AlertDetailsKeysPipe } from './alert-details-keys.pipe';
import { AuthenticationService } from 'app/service/authentication.service';
import { AlertsService } from 'app/service/alerts.service';
import { UpdateService } from 'app/service/update.service';
import { RouterTestingModule } from '@angular/router/testing';
import { SearchService } from 'app/service/search.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { AppConfigService } from 'app/service/app-config.service';
import { GlobalConfigService } from 'app/service/global-config.service';
import { DataSource } from 'app/service/data-source';
import { ElasticSearchLocalstorageImpl } from 'app/service/elasticsearch-localstorage-impl';
import { DialogService } from 'app/service/dialog.service';
import { By } from '@angular/platform-browser';
import { AlertComment } from './alert-comment';
import { Subject } from 'rxjs';
import { ConfirmationType } from 'app/model/confirmation-type';
import { CommentAddRemoveRequest } from '../../model/comment-add-remove-request';
import { AlertSource } from '../../model/alert-source';
import { of } from 'rxjs/index';
import { Router } from '@angular/router';
const alertDetail = {
'enrichments:geo:ip_dst_addr:locID': '5308655',
'bro_timestamp': '1554222181.202211',
'status_code': 404,
'enrichments:geo:ip_dst_addr:location_point': '33.4589,-112.0709',
'ip_dst_port': 80,
'enrichments:geo:ip_dst_addr:dmaCode': '753',
'adapter:geoadapter:begin:ts': '1554727717061',
'enrichments:geo:ip_dst_addr:latitude': '33.4589',
'parallelenricher:enrich:end:ts': '1554727717078',
'uid': 'CBt5FP2TVetZJjaZbi',
'resp_mime_types': ['text/html'],
'trans_depth': 1,
'protocol': 'http',
'source:type': 'bro',
'adapter:threatinteladapter:end:ts': '1554727717076',
'original_string': 'HTTP | id.orig_p:49199',
'ip_dst_addr': '204.152.254.221',
'adapter:hostfromjsonlistadapter:end:ts': '1554727717069',
'host': 'runlove.us',
'adapter:geoadapter:end:ts': '1554727717069',
'ip_src_addr': '192.168.138.158',
'enrichments:geo:ip_dst_addr:longitude': '-112.0709',
'user_agent': '',
'resp_fuids': ['FeDAUx1IIW621Aw6Y8'],
'timestamp': 1554222181202,
'method': 'POST',
'parallelenricher:enrich:begin:ts': '1554727717075',
'request_body_len': 96,
'enrichments:geo:ip_dst_addr:city': 'Phoenix',
'enrichments:geo:ip_dst_addr:postalCode': '85004',
'adapter:hostfromjsonlistadapter:begin:ts': '1554727717061',
'orig_mime_types': ['text/plain'],
'uri': '/wp-content/themes/twentyfifteen/img5.php?l=8r1gf1b2t1kuq42',
'tags': [],
'parallelenricher:splitter:begin:ts': '1554727717075',
'alert_status': 'RESOLVE',
'orig_fuids': ['FTTvSE5Asee5tJr99'],
'ip_src_port': 49199,
'parallelenricher:splitter:end:ts': '1554727717075',
'adapter:threatinteladapter:begin:ts': '1554727717075',
'status_msg': 'Not Found',
'guid': 'fe9e058e-6d5a-4ba5-8b79-d8e6a2792931',
'enrichments:geo:ip_dst_addr:country': 'US',
'response_body_len': 357
};
describe('AlertDetailsComponent', () => {
let component: AlertDetailsComponent;
let fixture: ComponentFixture<AlertDetailsComponent>;
let updateService: UpdateService;
let router: Router;
let alertsService: AlertsService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
SharedModule,
HttpClientTestingModule,
RouterTestingModule.withRoutes([])
],
declarations: [ AlertDetailsComponent, AlertDetailsKeysPipe ],
providers: [
SearchService,
AuthenticationService,
UpdateService,
{ provide: GlobalConfigService, useValue: {
get: () => { return of({})}
}},
{
provide: DialogService,
useValue: {
launchDialog: () => {
const confirmed = new Subject<ConfirmationType>();
setTimeout(() => {
confirmed.next(ConfirmationType.Confirmed);
});
return confirmed;
}
}
},
{
provide: AppConfigService, useValue: {
appConfigStatic: {},
getApiRoot: () => {},
} },
{
provide: DataSource,
useClass: ElasticSearchLocalstorageImpl
},
{ provide: AlertsService,
useValue: {
escalate: () => {}
}
},
],
})
.compileComponents();
alertsService = TestBed.get(AlertsService);
}));
beforeEach(() => {
fixture = TestBed.createComponent(AlertDetailsComponent);
component = fixture.componentInstance;
updateService = fixture.debugElement.injector.get(UpdateService);
router = TestBed.get(Router)
fixture.detectChanges();
});
it('should be in a loading state if no alertSources loaded', () => {
component.alertSources = [];
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('[data-qe-id="preloader"]'))).toBeTruthy();
});
it('should show details if alertSources loaded', () => {
component.alertSources = [alertDetail];
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('[data-qe-id="preloader"]'))).toBeFalsy();
});
it('should delete a comment.', fakeAsync(() => {
const responseMock = new AlertSource();
responseMock.guid = 'guid';
const removeCommentSpy = spyOn(updateService, 'removeComment').and.returnValue(
of(responseMock)
);
const setAlertSpy = spyOn(component, 'setAlert');
expect(component).toBeTruthy();
component.alertSource = new AlertSource();
component.alertSource.guid = 'guid';
component.alertSourceType = 'sourceType';
const now = Date.now();
component.alertSources = [alertDetail];
fixture.detectChanges();
component.alertCommentsWrapper = [
new AlertCommentWrapper(
new AlertComment('lorem ipsum', 'user', now),
(new Date()).toString()
)
];
const element = fixture.debugElement.query(By.css('[data-qe-id="comments"]'));
element.nativeElement.click();
fixture.detectChanges();
const deleteComment = fixture.debugElement.query(By.css('[data-qe-id="delete-comment"]'));
deleteComment.nativeElement.click();
tick(500);
fixture.detectChanges();
const expectedCommentRequest = new CommentAddRemoveRequest();
expectedCommentRequest.guid = 'guid';
expectedCommentRequest.comment = 'lorem ipsum';
expectedCommentRequest.username = 'user';
expectedCommentRequest.sensorType = 'sourceType';
expectedCommentRequest.timestamp = now;
const expectedAlertSource = new AlertSource();
expectedAlertSource.guid = 'guid';
expect(removeCommentSpy).toHaveBeenCalledWith(expectedCommentRequest);
expect(removeCommentSpy).toHaveBeenCalledTimes(1);
expect(setAlertSpy).toHaveBeenCalledWith(expectedAlertSource);
expect(setAlertSpy).toHaveBeenCalledTimes(1);
}));
it('should return to alert list page when goBack() is called', () => {
let navigateSpy = spyOn(router, 'navigateByUrl');
component.goBack();
expect(navigateSpy).toHaveBeenCalledWith('/alerts-list');
});
it('should set alert source with setAlert', () => {
const alertSource = {
name: 'test',
comments: ['test comment 1', 'test comment 2'],
metron_alert: ''
};
component.setAlert(alertSource);
expect(component.alertName).toBe('test');
expect(component.alertSource).toBe(alertSource);
alertSource.metron_alert = 'test alert';
component.setAlert(alertSource);
expect(component.alertSources).toBe(alertSource.metron_alert);
});
it('should return the correct alert state with getAlertState', () => {
expect(component.getAlertState('OPEN')).toBe(component.alertState.OPEN);
expect(component.getAlertState('ESCALATE')).toBe(
component.alertState.ESCALATE
);
expect(component.getAlertState('DISMISS')).toBe(
component.alertState.DISMISS
);
expect(component.getAlertState('RESOLVE')).toBe(
component.alertState.RESOLVE
);
expect(component.getAlertState('NEW')).toBe(component.alertState.NEW);
});
it('should update alert state', () => {
spyOn(alertsService, 'escalate').and.returnValue(of({}));
spyOn(component, 'updateAlertState').and.callThrough();
component.alertSource = new AlertSource();
component.processEscalate();
expect(component.updateAlertState).toHaveBeenCalledWith('ESCALATE');
component.processOpen();
expect(component.updateAlertState).toHaveBeenCalledWith('OPEN');
component.processNew();
expect(component.updateAlertState).toHaveBeenCalledWith('NEW');
component.processDismiss();
expect(component.updateAlertState).toHaveBeenCalledWith('DISMISS');
component.processResolve();
expect(component.updateAlertState).toHaveBeenCalledWith('RESOLVE');
});
it('should toggle editor with toggleNameEditor', fakeAsync(() => {
expect(component.showEditor).toBe(false);
component.alertSources = ['test1', 'test2'];
component.toggleNameEditor();
fixture.detectChanges();
const focus = spyOn(component.metaAlertNameInput.nativeElement, 'focus');
expect(component.showEditor).toBe(true);
tick(500);
fixture.detectChanges();
expect(focus).toHaveBeenCalled();
component.alertSources = [];
component.toggleNameEditor();
fixture.detectChanges();
expect(component.showEditor).toBe(true);
flush();
}));
it('should send a request to update an alert name with saveName', () => {
const responseMock = new AlertSource();
const patchSpy = spyOn(updateService, 'patch').and.returnValue(
of(responseMock)
);
component.alertName = 'test name';
component.alertId = '123';
fixture.detectChanges();
component.saveName();
expect(patchSpy).toHaveBeenCalled();
});
it('should send a request to add a comment with onAddComment', () => {
const addCommentSpy = spyOn(updateService, 'addComment').and.returnValue(
of()
);
component.alertSources = ['test'];
component.activeTab = component.tabs.COMMENTS;
component.alertCommentStr = 'abcd';
fixture.detectChanges();
const addCommentBtn = fixture.debugElement.query(
By.css('[data-qe-id="add-comment-button"]')
);
addCommentBtn.nativeElement.click();
expect(addCommentSpy).toHaveBeenCalled();
});
it('should update a meta alert name or escape the input based on certain keyup events', () => {
component.alertSources = ['test1', 'test2'];
component.toggleNameEditor();
component.alertSource.name = 'test';
fixture.detectChanges();
const saveNameSpy = spyOn(component, 'saveName');
const toggleSpy = spyOn(component, 'toggleNameEditor');
const metaAlertNameInput = fixture.debugElement.query(
By.css('[data-qe-id="meta-alert-name-input"')
);
const enterEvent = new KeyboardEvent('keyup', {
code: 'Enter'
});
const escEvent = new KeyboardEvent('keyup', {
code: 'Escape'
});
metaAlertNameInput.nativeElement.value = 'test';
metaAlertNameInput.nativeElement.dispatchEvent(enterEvent);
expect(saveNameSpy).toHaveBeenCalled();
metaAlertNameInput.nativeElement.value = 'test';
metaAlertNameInput.nativeElement.dispatchEvent(escEvent);
expect(component.alertName).toBe(component.alertSource.name);
expect(toggleSpy).toHaveBeenCalled();
});
it('should restore the alert name if cancel is clicked', () => {
component.alertSources = ['test1', 'test2'];
component.toggleNameEditor();
component.alertSource.name = 'test';
fixture.detectChanges();
const toggleSpy = spyOn(component, 'toggleNameEditor');
const cancelInputBtn = fixture.debugElement.query(
By.css('[data-qe-id="cancel-name-input"]')
);
cancelInputBtn.nativeElement.click();
expect(component.alertName).toBe(component.alertSource.name);
expect(toggleSpy).toHaveBeenCalled();
});
}); | the_stack |
import React from 'react';
import { DeepRequired } from 'ts-essentials';
import { DataSourcesAPI } from '../..';
import { QualifiedTable } from '../../../metadata/types';
import {
TableColumn,
Table,
BaseTableColumn,
SupportedFeaturesType,
FrequentlyUsedColumn,
ViolationActions,
} from '../../types';
import {
generateTableRowRequest,
operators,
generateRowsCountRequest,
} from './utils';
const permissionColumnDataTypes = {
character: [
'char',
'varchar',
'text',
'nchar',
'nvarchar',
'binary',
'vbinary',
'image',
],
numeric: [
'bit',
'tinyint',
'smallint',
'int',
'bigint',
'decimal',
'numeric',
'smallmoney',
'money',
'float',
'real',
],
dateTime: [
'datetime',
'smalldatetime',
'date',
'time',
'datetimeoffset',
'timestamp',
],
user_defined: [],
};
const supportedColumnOperators = [
'_is_null',
'_eq',
'_neq',
'_gt',
'_lt',
'_gte',
'_lte',
];
const isTable = (table: Table) => {
if (!table.table_type) return true; // todo
return table.table_type === 'TABLE' || table.table_type === 'BASE TABLE';
};
export const isColTypeString = (colType: string) =>
['text', 'varchar', 'char', 'bpchar', 'name'].includes(colType);
const columnDataTypes = {
INTEGER: 'integer',
BIGINT: 'bigint',
GUID: 'guid',
JSONDTYPE: 'nvarchar',
DATETIMEOFFSET: 'timestamp with time zone',
NUMERIC: 'numeric',
DATE: 'date',
TIME: 'time',
TEXT: 'text',
};
// eslint-disable-next-line no-useless-escape
const createSQLRegex = /create\s*(?:|or\s*replace)\s*(?<type>view|table|function)\s*(?:\s*if*\s*not\s*exists\s*)?((?<schema>\"?\w+\"?)\.(?<nameWithSchema>\"?\w+\"?)|(?<name>\"?\w+\"?))\s*(?<partition>partition\s*of)?/gim;
export const displayTableName = (table: Table) => {
const tableName = table.table_name;
return isTable(table) ? <span>{tableName}</span> : <i>{tableName}</i>;
};
const violationActions: ViolationActions[] = [
'no action',
'cascade',
'set null',
'set default',
];
export const supportedFeatures: DeepRequired<SupportedFeaturesType> = {
driver: {
name: 'mssql',
fetchVersion: {
enabled: false,
},
},
schemas: {
create: {
enabled: true,
},
delete: {
enabled: true,
},
},
tables: {
create: {
enabled: true,
frequentlyUsedColumns: false,
columnTypeSelector: false,
},
browse: {
enabled: true,
customPagination: true,
aggregation: true,
},
insert: {
enabled: false,
},
modify: {
editableTableName: false,
enabled: true,
columns: {
view: true,
edit: true,
graphqlFieldName: false,
frequentlyUsedColumns: false,
},
readOnly: false,
computedFields: false,
primaryKeys: {
view: true,
edit: true,
},
foreignKeys: {
view: true,
edit: true,
},
uniqueKeys: {
view: true,
edit: true,
},
triggers: false,
checkConstraints: {
view: true,
edit: false,
},
indexes: {
view: false,
edit: false,
},
customGqlRoot: true,
setAsEnum: false,
untrack: true,
delete: true,
comments: {
view: true,
edit: false,
},
},
relationships: {
enabled: true,
track: true,
remoteRelationships: false,
},
permissions: {
enabled: true,
aggregation: false,
},
track: {
enabled: false,
},
},
functions: {
enabled: true,
track: {
enabled: false,
},
nonTrackableFunctions: {
enabled: false,
},
},
events: {
triggers: {
enabled: true,
add: false,
},
},
actions: {
enabled: true,
relationships: false,
},
rawSQL: {
enabled: true,
statementTimeout: false,
tracking: true,
},
connectDbForm: {
enabled: true,
connectionParameters: false,
databaseURL: true,
environmentVariable: true,
read_replicas: false,
prepared_statements: false,
isolation_level: false,
connectionSettings: true,
retries: false,
pool_timeout: false,
connection_lifetime: false,
ssl_certificates: false,
},
};
export const isJsonColumn = (column: BaseTableColumn): boolean => {
return column.data_type_name === 'json' || column.data_type_name === 'jsonb';
};
const defaultRedirectSchema = 'dbo';
export const mssql: DataSourcesAPI = {
isTable,
isJsonColumn,
displayTableName,
operators,
generateTableRowRequest,
getFunctionSchema: () => {
return '';
},
getFunctionDefinition: () => {
return '';
},
getSchemaFunctions: () => {
return [];
},
findFunction: () => {
return undefined;
},
getGroupedTableComputedFields: () => {
return { scalar: [], table: [] };
},
isColumnAutoIncrement: () => {
return false;
},
getTableSupportedQueries: () => {
// since only subscriptions and queries are supported on MSSQL atm.
return ['select'];
},
getColumnType: (col: TableColumn) => col.data_type_name ?? col.data_type,
arrayToPostgresArray: () => {
return '';
},
schemaListSql: () => `
SELECT
s.name AS schema_name
FROM
sys.schemas s
WHERE
s.name NOT IN (
'guest', 'INFORMATION_SCHEMA', 'sys',
'db_owner', 'db_securityadmin', 'db_accessadmin',
'db_backupoperator', 'db_ddladmin', 'db_datawriter',
'db_datareader', 'db_denydatawriter', 'db_denydatareader'
)
ORDER BY
s.name
`,
parseColumnsInfoResult: () => {
return {};
},
columnDataTypes,
getFetchTablesListQuery: ({ schemas, tables }) => {
let whereClause = '';
if (schemas) {
whereClause = `AND sch.name IN (${schemas.map(s => `'${s}'`).join(',')})`;
} else if (tables) {
whereClause = `AND obj.name IN (${tables
.map(t => `'${t.table_name}'`)
.join(',')})`;
}
// ## Note on fetching MSSQL table comments
// LEFT JOIN (select * from sys.extended_properties where "minor_id"= 0) AS e ON e.major_id = obj.object_id
// this would filter out column comments, but if there are multiple extended properties with same major id and minor_id=0;
// ie, multiple properties on the table name (as shown below) can cause confusion and then it would pick only the first result.
// * case 1
// EXEC sys.sp_addextendedproperty
// @name=N'TableDescription',
// @value=N'Album Table is used for listing albums' ,
// @level0type=N'SCHEMA', @level0name=N'dbo',
// @level1type=N'TABLE', @level1name=N'Album';
// * case 2
// EXEC sys.sp_addextendedproperty
// @name=N'TableDescription2', -- ==> this is possible with mssql
// @value=N'some other property description' ,
// @level0type=N'SCHEMA', @level0name=N'dbo',
// @level1type=N'TABLE', @level1name=N'Album';
return `
SELECT sch.name as table_schema,
obj.name as table_name,
case
when obj.type = 'AF' then 'Aggregate function (CLR)'
when obj.type = 'C' then 'CHECK constraint'
when obj.type = 'D' then 'DEFAULT (constraint or stand-alone)'
when obj.type = 'F' then 'FOREIGN KEY constraint'
when obj.type = 'FN' then 'SQL scalar function'
when obj.type = 'FS' then 'Assembly (CLR) scalar-function'
when obj.type = 'FT' then 'Assembly (CLR) table-valued function'
when obj.type = 'IF' then 'SQL inline table-valued function'
when obj.type = 'IT' then 'Internal table'
when obj.type = 'P' then 'SQL Stored Procedure'
when obj.type = 'PC' then 'Assembly (CLR) stored-procedure'
when obj.type = 'PG' then 'Plan guide'
when obj.type = 'PK' then 'PRIMARY KEY constraint'
when obj.type = 'R' then 'Rule (old-style, stand-alone)'
when obj.type = 'RF' then 'Replication-filter-procedure'
when obj.type = 'S' then 'System base table'
when obj.type = 'SN' then 'Synonym'
when obj.type = 'SO' then 'Sequence object'
when obj.type = 'U' then 'TABLE'
when obj.type = 'EC' then 'Edge constraint'
when obj.type = 'V' then 'VIEW'
end as table_type,
(SELECT e.[value] AS comment for json path),
JSON_QUERY([isc].json) AS columns
FROM sys.objects as obj
INNER JOIN sys.schemas as sch ON obj.schema_id = sch.schema_id
LEFT JOIN (select * from sys.extended_properties where minor_id = 0) AS e ON e.major_id = obj.object_id
OUTER APPLY (
SELECT
a.name AS column_name,
a.column_id AS ordinal_position,
ad.definition AS column_default,
a.collation_name AS collation_name,
CASE
WHEN a.is_nullable = 0
OR t.is_nullable = 0
THEN 'NO'
ELSE 'YES'
END AS is_nullable,
CASE
WHEN t.is_table_type = 1 THEN 'TABLE'
WHEN t.is_assembly_type = 1 THEN 'ASSEMBLY'
WHEN t.is_user_defined = 1 THEN 'USER-DEFINED'
ELSE 'OTHER'
END AS data_type,
t.name AS data_type_name,
sch.name AS table_schema,
obj.name AS table_name,
ep.value AS comment,
ep.name AS extended_property_name_comment
FROM
sys.columns a
LEFT JOIN sys.default_constraints ad ON (a.column_id = ad.parent_column_id AND a.object_id = ad.parent_object_id)
JOIN sys.types t ON a.user_type_id = t.user_type_id
LEFT JOIN sys.extended_properties ep ON (ep.major_id = a.object_id AND ep.minor_id = a.column_id)
WHERE a.column_id > 0 and a.object_id = obj.object_id
FOR JSON path
) AS [isc](json) where obj.type_desc in ('USER_TABLE', 'VIEW') ${whereClause};`;
},
commonDataTypes: [],
fetchColumnTypesQuery: '',
fetchColumnDefaultFunctions: () => {
return '';
},
isSQLFunction: () => {
return false;
},
getEstimateCountQuery: () => {
return '';
},
isColTypeString: () => {
return false;
},
cascadeSqlQuery: () => {
return '';
},
dependencyErrorCode: '',
getCreateTableQueries: (
currentSchema: string,
tableName: string,
columns: any[],
primaryKeys: (number | string)[],
foreignKeys: any[],
uniqueKeys: any[],
checkConstraints: any[],
tableComment?: string | undefined
) => {
const currentCols = columns.filter(c => c.name !== '');
const flatUniqueKeys = uniqueKeys.reduce((acc, val) => acc.concat(val), []);
const pKeys = primaryKeys
.filter(p => p !== '')
.map(p => currentCols[p as number].name);
let tableDefSql = '';
for (let i = 0; i < currentCols.length; i++) {
tableDefSql += `${currentCols[i].name} ${currentCols[i].type}`;
// check if column is nullable
if (!currentCols[i].nullable) {
tableDefSql += ' NOT NULL';
}
// check if the column is unique
if (uniqueKeys.length && flatUniqueKeys.includes(i)) {
tableDefSql += ' UNIQUE';
}
// check if column has a default value
if (
currentCols[i].default !== undefined &&
currentCols[i].default?.value !== ''
) {
if (isColTypeString(currentCols[i].type)) {
// if a column type is text and if it has a non-func default value, add a single quote
tableDefSql += ` DEFAULT '${currentCols[i]?.default?.value}'`;
} else {
tableDefSql += ` DEFAULT ${currentCols[i]?.default?.value}`;
}
}
tableDefSql += i === currentCols.length - 1 ? '' : ', ';
}
// add primary key
if (pKeys.length > 0) {
tableDefSql += ', PRIMARY KEY (';
tableDefSql += pKeys.map(col => `${col}`).join(',');
tableDefSql += ') ';
}
const numFks = foreignKeys.length;
let fkDupColumn = null;
if (numFks > 1) {
foreignKeys.forEach((fk, _i) => {
if (_i === numFks - 1) {
return;
}
const { colMappings, refTableName, onUpdate, onDelete } = fk;
const mappingObj: Record<string, string> = {};
const rCols: string[] = [];
const lCols: string[] = [];
colMappings
.slice(0, -1)
.forEach((cm: { column: string | number; refColumn: string }) => {
if (mappingObj[cm.column] !== undefined) {
fkDupColumn = columns[cm.column as number].name;
}
mappingObj[cm.column] = cm.refColumn;
lCols.push(`"${columns[cm.column as number].name}"`);
rCols.push(`"${cm.refColumn}"`);
});
if (lCols.length === 0) {
return;
}
tableDefSql += `, FOREIGN KEY (${lCols.join(', ')}) REFERENCES "${
fk.refSchemaName
}"."${refTableName}"(${rCols.join(
', '
)}) ON UPDATE ${onUpdate} ON DELETE ${onDelete}`;
});
}
if (fkDupColumn) {
return {
error: `The column "${fkDupColumn}" seems to be referencing multiple foreign columns`,
};
}
// add check constraints
if (checkConstraints.length > 0) {
checkConstraints.forEach(constraint => {
if (!constraint.name || !constraint.check) {
return;
}
tableDefSql += `, CONSTRAINT "${constraint.name}" CHECK(${constraint.check})`;
});
}
let sqlCreateTable = `CREATE TABLE "${currentSchema}"."${tableName}" (${tableDefSql});`;
// add comment to the table using MS_Description property
if (tableComment && tableComment !== '') {
const commentSQL = `EXEC sys.sp_addextendedproperty
@name = N'MS_Description',
@value = N'${tableComment}',
@level0type = N'SCHEMA', @level0name = '${currentSchema}',
@level1type = N'TABLE', @level1name = '${tableName}';`;
sqlCreateTable += `${commentSQL}`;
}
return [sqlCreateTable];
},
getDropTableSql: (schema: string, table: string) => {
return `DROP TABLE "${schema}"."${table}"`;
},
createSQLRegex,
getDropSchemaSql: (schema: string) => {
return `drop schema ${schema};`;
},
getCreateSchemaSql: (schema: string) => {
return `create schema ${schema};`;
},
isTimeoutError: () => {
return false;
},
getAlterForeignKeySql: (
from: {
tableName: string;
schemaName: string;
columns: string[];
},
to: {
tableName: string;
schemaName: string;
columns: string[];
},
dropConstraint: string,
newConstraint: string,
onUpdate: string,
onDelete: string
) => {
return `
BEGIN transaction;
ALTER TABLE "${from.schemaName}"."${from.tableName}"
DROP CONSTRAINT IF EXISTS "${dropConstraint}";
ALTER TABLE "${from.schemaName}"."${from.tableName}"
ADD CONSTRAINT "${newConstraint}"
FOREIGN KEY (${from.columns.join(', ')})
REFERENCES "${to.schemaName}"."${to.tableName}" (${to.columns.join(', ')})
ON UPDATE ${onUpdate} ON DELETE ${onDelete};
COMMIT transaction;
`;
},
getCreateFKeySql: (
from: {
tableName: string;
schemaName: string;
columns: string[];
},
to: {
tableName: string;
schemaName: string;
columns: string[];
},
newConstraint: string,
onUpdate: string,
onDelete: string
) => {
return `
ALTER TABLE "${from.schemaName}"."${from.tableName}"
ADD CONSTRAINT "${newConstraint}"
FOREIGN KEY (${from.columns.join(', ')})
REFERENCES "${to.schemaName}"."${to.tableName}" (${to.columns.join(', ')})
ON UPDATE ${onUpdate} ON DELETE ${onDelete}`;
},
getDropConstraintSql: (
tableName: string,
schemaName: string,
constraintName: string
) => {
return `ALTER TABLE "${schemaName}"."${tableName}" DROP CONSTRAINT "${constraintName}"`;
},
getRenameTableSql: () => {
return '';
},
getDropTriggerSql: () => {
return '';
},
getCreateTriggerSql: () => {
return '';
},
getDropSql: (tableName: string, schemaName: string, property = 'table') => {
return `DROP ${property} "${schemaName}"."${tableName}";`;
},
getViewDefinitionSql: () => {
return '';
},
getDropColumnSql: (
tableName: string,
schemaName: string,
columnName: string
) => {
return `ALTER TABLE "${schemaName}"."${tableName}"
DROP COLUMN "${columnName}"`;
},
getAddColumnSql: (
tableName: string,
schemaName: string,
columnName: string,
columnType: string,
options?: {
nullable: boolean;
unique: boolean;
default: any;
sqlGenerator?: FrequentlyUsedColumn['dependentSQLGenerator'];
},
constraintName?: string
) => {
let sql = `ALTER TABLE "${schemaName}"."${tableName}" ADD "${columnName}" ${columnType}`;
if (!options) {
return sql;
}
if (options.nullable) {
sql += ` NULL`;
} else {
sql += ` NOT NULL`;
}
if (options.unique) {
sql += ` UNIQUE`;
}
if (options.default) {
sql += ` CONSTRAINT "${constraintName}" DEFAULT '${options.default}' WITH VALUES`;
}
return sql;
},
getAddUniqueConstraintSql: (
tableName: string,
schemaName: string,
constraintName: string,
columns: string[]
) => {
return `ALTER TABLE "${schemaName}"."${tableName}"
ADD CONSTRAINT "${constraintName}"
UNIQUE (${columns.join(',')})`;
},
getDropNotNullSql: (
tableName: string,
schemaName: string,
columnName: string,
columnType?: string
) => {
return `ALTER TABLE "${schemaName}"."${tableName}" ALTER COLUMN "${columnName}" ${columnType} NULL`;
},
getSetCommentSql: (
on: 'column' | 'table' | string,
tableName: string,
schemaName: string,
comment: string | null,
columnName?: string
) => {
const dropCommonCommentStatement = `IF EXISTS (SELECT NULL FROM SYS.EXTENDED_PROPERTIES WHERE [major_id] = OBJECT_ID('${tableName}') AND [name] = N'${on}_comment_${schemaName}_${tableName}_${columnName}' AND [minor_id] = (SELECT [column_id] FROM SYS.COLUMNS WHERE [name] = '${columnName}' AND [object_id] = OBJECT_ID('${tableName}')))
EXECUTE sp_dropextendedproperty
@name = N'${on}_comment_${schemaName}_${tableName}_${columnName}',
@level0type = N'SCHEMA', @level0name = '${schemaName}'
`;
const commonCommentStatement = `
exec sys.sp_addextendedproperty
@name = N'${on}_comment_${schemaName}_${tableName}_${columnName}',
@value = N'${comment}',
@level0type = N'SCHEMA', @level0name = '${schemaName}'
`;
if (on === 'column') {
return `${dropCommonCommentStatement},@level1type = N'TABLE', @level1name = '${tableName}',@level2type = N'COLUMN', @level2name = '${columnName}';
${commonCommentStatement},@level1type = N'TABLE', @level1name = '${tableName}',@level2type = N'COLUMN', @level2name = '${columnName}'`;
}
// FIXME: Comment on mssql table and function is not implemented yet.
return '';
},
getSetColumnDefaultSql: (
tableName: string,
schemaName: string,
columnName: string,
defaultValue: any,
constraintName: string
) => {
return `ALTER TABLE "${schemaName}"."${tableName}" DROP CONSTRAINT IF EXISTS "${constraintName}";
ALTER TABLE "${schemaName}"."${tableName}" ADD CONSTRAINT "${constraintName}" DEFAULT ${defaultValue} FOR "${columnName}"`;
},
getSetNotNullSql: (
tableName: string,
schemaName: string,
columnName: string,
columnType: string
) => {
return `ALTER TABLE "${schemaName}"."${tableName}" ALTER COLUMN "${columnName}" ${columnType} NOT NULL`;
},
getAlterColumnTypeSql: (
tableName: string,
schemaName: string,
columnName: string,
columnType: string,
wasNullable?: boolean
) => {
return `ALTER TABLE "${schemaName}"."${tableName}" ALTER COLUMN "${columnName}" ${columnType} ${
!wasNullable ? `NOT NULL` : ``
}`;
},
getDropColumnDefaultSql: (
tableName: string,
schemaName: string,
columnName?: string,
constraintName?: string
) => {
return `ALTER TABLE "${schemaName}"."${tableName}" DROP CONSTRAINT "${constraintName}"`;
},
getRenameColumnQuery: (
tableName: string,
schemaName: string,
newName: string,
oldName: string
) => {
return `sp_rename '[${schemaName}].[${tableName}].[${oldName}]', '${newName}', 'COLUMN'`;
},
fetchColumnCastsQuery: '',
checkSchemaModification: () => {
return false;
},
getCreateCheckConstraintSql: () => {
return '';
},
getCreatePkSql: ({
schemaName,
tableName,
selectedPkColumns,
constraintName,
}: {
schemaName: string;
tableName: string;
selectedPkColumns: string[];
constraintName?: string;
}) => {
return `ALTER TABLE "${schemaName}"."${tableName}"
ADD CONSTRAINT "${constraintName}"
PRIMARY KEY (${selectedPkColumns.map(pkc => `"${pkc}"`).join(',')})`;
},
getAlterPkSql: ({
schemaName,
tableName,
selectedPkColumns,
constraintName,
}: {
schemaName: string;
tableName: string;
selectedPkColumns: string[];
constraintName: string; // compulsory for PG
}) => {
return `BEGIN TRANSACTION;
ALTER TABLE "${schemaName}"."${tableName}" DROP CONSTRAINT "${constraintName}";
ALTER TABLE "${schemaName}"."${tableName}"
ADD CONSTRAINT "${constraintName}" PRIMARY KEY (${selectedPkColumns
.map(pkc => `"${pkc}"`)
.join(', ')});
COMMIT TRANSACTION;`;
},
getFunctionDefinitionSql: null,
primaryKeysInfoSql: ({ schemas }) => {
let whereClause = '';
if (schemas) {
whereClause = `WHERE schema_name (schema_id) in (${schemas
.map(s => `'${s}'`)
.join(',')})`;
}
return `
SELECT
schema_name (tab.schema_id) AS table_schema,
tab.name AS table_name,
(
SELECT
col.name,
pk.name AS constraint_name
FROM
sys.indexes pk
INNER JOIN sys.index_columns ic ON ic.object_id = pk.object_id
AND ic.index_id = pk.index_id
INNER JOIN sys.columns col ON pk.object_id = col.object_id
AND col.column_id = ic.column_id
WHERE
tab.object_id = pk.object_id AND pk.is_primary_key = 1 FOR json path) AS constraints
FROM
sys.tables tab
INNER JOIN sys.indexes pk ON tab.object_id = pk.object_id
AND pk.is_primary_key = 1
${whereClause}
GROUP BY
tab.name,
tab.schema_id,
tab.object_id
FOR JSON PATH;
`;
},
checkConstraintsSql: ({ schemas }) => {
let whereClause = '';
if (schemas) {
whereClause = `WHERE schema_name (t.schema_id) in (${schemas
.map(s => `'${s}'`)
.join(',')})`;
}
return `
SELECT
con.name AS constraint_name,
schema_name (t.schema_id) AS table_schema,
t.name AS table_name,
col.name AS column_name,
con.definition AS check_definition
FROM
sys.check_constraints con
LEFT OUTER JOIN sys.objects t ON con.parent_object_id = t.object_id
LEFT OUTER JOIN sys.all_columns col ON con.parent_column_id = col.column_id
AND con.parent_object_id = col.object_id
${whereClause}
ORDER BY con.name
FOR JSON PATH;
`;
},
uniqueKeysSql: ({ schemas }) => {
let whereClause = '';
if (schemas) {
whereClause = `WHERE schema_name (schema_id) in (${schemas
.map(s => `'${s}'`)
.join(',')})`;
}
return `
SELECT
schema_name (tab.schema_id) AS table_schema,
tab.name AS table_name,
(
SELECT
col.name,
idx.name AS constraint_name
FROM
sys.indexes idx
INNER JOIN sys.index_columns ic ON ic.object_id = idx.object_id
AND ic.index_id = idx.index_id
INNER JOIN sys.columns col ON idx.object_id = col.object_id
AND col.column_id = ic.column_id
WHERE
tab.object_id = idx.object_id
AND idx.is_unique_constraint = 1 FOR json path) AS constraints
FROM
sys.tables tab
INNER JOIN sys.indexes idx ON tab.object_id = idx.object_id
AND idx.is_unique_constraint = 1
${whereClause}
GROUP BY
tab.name,
tab.schema_id,
tab.object_id
FOR JSON PATH;
`;
},
frequentlyUsedColumns: [],
getFKRelations: () => {
return `
SELECT
fk.name AS constraint_name,
sch1.name AS [table_schema],
tab1.name AS [table_name],
sch2.name AS [ref_table_schema],
tab2.name AS [ref_table],
(
SELECT
col1.name AS [column],
col2.name AS [referenced_column]
FROM sys.foreign_key_columns fkc
INNER JOIN sys.columns col1
ON col1.column_id = fkc.parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.columns col2
ON col2.column_id = fkc.referenced_column_id AND col2.object_id = tab2.object_id
WHERE fk.object_id = fkc.constraint_object_id
FOR JSON PATH
) AS column_mapping,
fk.delete_referential_action_desc AS [on_delete],
fk.update_referential_action_desc AS [on_update]
FROM sys.foreign_keys fk
INNER JOIN sys.objects obj
ON obj.object_id = fk.referenced_object_id
INNER JOIN sys.tables tab1
ON tab1.object_id = fk.parent_object_id
INNER JOIN sys.schemas sch1
ON tab1.schema_id = sch1.schema_id
INNER JOIN sys.tables tab2
ON tab2.object_id = fk.referenced_object_id
INNER JOIN sys.schemas sch2
ON tab2.schema_id = sch2.schema_id for json path;
`;
},
getReferenceOption: (opt: string) => {
return opt;
},
deleteFunctionSql: () => {
return '';
},
getEventInvocationInfoByIDSql: () => {
return '';
},
getDatabaseInfo: '',
getTableInfo: (tables: QualifiedTable[]) => `
SELECT
o.name AS table_name,
s.name AS table_schema,
table_type = CASE o.type
WHEN 'U' THEN
'table'
WHEN 'V' THEN
'view'
ELSE
'table'
END
FROM
sys.objects AS o
JOIN sys.schemas AS s ON (o.schema_id = s.schema_id)
WHERE
o.name in (${tables.map(t => `'${t.name}'`).join(',')}) for json path;
`,
getDatabaseVersionSql: 'SELECT @@VERSION;',
permissionColumnDataTypes,
viewsSupported: false,
supportedColumnOperators,
supportedFeatures,
violationActions,
defaultRedirectSchema,
generateRowsCountRequest,
}; | the_stack |
import { IMarkdownString } from 'vs/base/common/htmlContent';
import { MarshalledId } from 'vs/base/common/marshallingIds';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IPosition } from 'vs/editor/common/core/position';
import { IRange, Range } from 'vs/editor/common/core/range';
export const enum TestResultState {
Unset = 0,
Queued = 1,
Running = 2,
Passed = 3,
Failed = 4,
Skipped = 5,
Errored = 6
}
export const enum TestRunProfileBitset {
Run = 1 << 1,
Debug = 1 << 2,
Coverage = 1 << 3,
HasNonDefaultProfile = 1 << 4,
HasConfigurable = 1 << 5,
}
/**
* List of all test run profile bitset values.
*/
export const testRunProfileBitsetList = [
TestRunProfileBitset.Run,
TestRunProfileBitset.Debug,
TestRunProfileBitset.Coverage,
TestRunProfileBitset.HasNonDefaultProfile,
];
/**
* DTO for a controller's run profiles.
*/
export interface ITestRunProfile {
controllerId: string;
profileId: number;
label: string;
group: TestRunProfileBitset;
isDefault: boolean;
tag: string | null;
hasConfigurationHandler: boolean;
}
/**
* A fully-resolved request to run tests, passsed between the main thread
* and extension host.
*/
export interface ResolvedTestRunRequest {
targets: {
testIds: string[];
controllerId: string;
profileGroup: TestRunProfileBitset;
profileId: number;
}[];
exclude?: string[];
isAutoRun?: boolean;
/** Whether this was trigged by a user action in UI. Default=true */
isUiTriggered?: boolean;
}
/**
* Request to the main thread to run a set of tests.
*/
export interface ExtensionRunTestsRequest {
id: string;
include: string[];
exclude: string[];
controllerId: string;
profile?: { group: TestRunProfileBitset; id: number };
persist: boolean;
}
/**
* Request from the main thread to run tests for a single controller.
*/
export interface RunTestForControllerRequest {
runId: string;
controllerId: string;
profileId: number;
excludeExtIds: string[];
testIds: string[];
}
/**
* Location with a fully-instantiated Range and URI.
*/
export interface IRichLocation {
range: Range;
uri: URI;
}
export namespace IRichLocation {
export interface Serialize {
range: IRange;
uri: UriComponents;
}
export const serialize = (location: IRichLocation): Serialize => ({
range: location.range.toJSON(),
uri: location.uri.toJSON(),
});
export const deserialize = (location: Serialize): IRichLocation => ({
range: Range.lift(location.range),
uri: URI.revive(location.uri),
});
}
export const enum TestMessageType {
Error,
Output
}
export interface ITestErrorMessage {
message: string | IMarkdownString;
type: TestMessageType.Error;
expected: string | undefined;
actual: string | undefined;
location: IRichLocation | undefined;
}
export namespace ITestErrorMessage {
export interface Serialized {
message: string | IMarkdownString;
type: TestMessageType.Error;
expected: string | undefined;
actual: string | undefined;
location: IRichLocation.Serialize | undefined;
}
export const serialize = (message: ITestErrorMessage): Serialized => ({
message: message.message,
type: TestMessageType.Error,
expected: message.expected,
actual: message.actual,
location: message.location && IRichLocation.serialize(message.location),
});
export const deserialize = (message: Serialized): ITestErrorMessage => ({
message: message.message,
type: TestMessageType.Error,
expected: message.expected,
actual: message.actual,
location: message.location && IRichLocation.deserialize(message.location),
});
}
export interface ITestOutputMessage {
message: string;
type: TestMessageType.Output;
offset: number;
location: IRichLocation | undefined;
}
export namespace ITestOutputMessage {
export interface Serialized {
message: string;
offset: number;
type: TestMessageType.Output;
location: IRichLocation.Serialize | undefined;
}
export const serialize = (message: ITestOutputMessage): Serialized => ({
message: message.message,
type: TestMessageType.Output,
offset: message.offset,
location: message.location && IRichLocation.serialize(message.location),
});
export const deserialize = (message: Serialized): ITestOutputMessage => ({
message: message.message,
type: TestMessageType.Output,
offset: message.offset,
location: message.location && IRichLocation.deserialize(message.location),
});
}
export type ITestMessage = ITestErrorMessage | ITestOutputMessage;
export namespace ITestMessage {
export type Serialized = ITestErrorMessage.Serialized | ITestOutputMessage.Serialized;
export const serialize = (message: ITestMessage): Serialized =>
message.type === TestMessageType.Error ? ITestErrorMessage.serialize(message) : ITestOutputMessage.serialize(message);
export const deserialize = (message: Serialized): ITestMessage =>
message.type === TestMessageType.Error ? ITestErrorMessage.deserialize(message) : ITestOutputMessage.deserialize(message);
}
export interface ITestTaskState {
state: TestResultState;
duration: number | undefined;
messages: ITestMessage[];
}
export namespace ITestTaskState {
export interface Serialized {
state: TestResultState;
duration: number | undefined;
messages: ITestMessage.Serialized[];
}
export const serialize = (state: ITestTaskState): Serialized => ({
state: state.state,
duration: state.duration,
messages: state.messages.map(ITestMessage.serialize),
});
export const deserialize = (state: Serialized): ITestTaskState => ({
state: state.state,
duration: state.duration,
messages: state.messages.map(ITestMessage.deserialize),
});
}
export interface ITestRunTask {
id: string;
name: string | undefined;
running: boolean;
}
export interface ITestTag {
readonly id: string;
}
const testTagDelimiter = '\0';
export const namespaceTestTag =
(ctrlId: string, tagId: string) => ctrlId + testTagDelimiter + tagId;
export const denamespaceTestTag = (namespaced: string) => {
const index = namespaced.indexOf(testTagDelimiter);
return { ctrlId: namespaced.slice(0, index), tagId: namespaced.slice(index + 1) };
};
export interface ITestTagDisplayInfo {
id: string;
}
/**
* The TestItem from .d.ts, as a plain object without children.
*/
export interface ITestItem {
/** ID of the test given by the test controller */
extId: string;
label: string;
tags: string[];
busy: boolean;
children?: never;
uri: URI | undefined;
range: Range | null;
description: string | null;
error: string | IMarkdownString | null;
sortText: string | null;
}
export namespace ITestItem {
export interface Serialized {
extId: string;
label: string;
tags: string[];
busy: boolean;
children?: never;
uri: UriComponents | undefined;
range: IRange | null;
description: string | null;
error: string | IMarkdownString | null;
sortText: string | null;
}
export const serialize = (item: ITestItem): Serialized => ({
extId: item.extId,
label: item.label,
tags: item.tags,
busy: item.busy,
children: undefined,
uri: item.uri?.toJSON(),
range: item.range?.toJSON() || null,
description: item.description,
error: item.error,
sortText: item.sortText
});
export const deserialize = (serialized: Serialized): ITestItem => ({
extId: serialized.extId,
label: serialized.label,
tags: serialized.tags,
busy: serialized.busy,
children: undefined,
uri: serialized.uri ? URI.revive(serialized.uri) : undefined,
range: serialized.range ? Range.lift(serialized.range) : null,
description: serialized.description,
error: serialized.error,
sortText: serialized.sortText
});
}
export const enum TestItemExpandState {
NotExpandable,
Expandable,
BusyExpanding,
Expanded,
}
/**
* TestItem-like shape, butm with an ID and children as strings.
*/
export interface InternalTestItem {
/** Controller ID from whence this test came */
controllerId: string;
/** Expandability state */
expand: TestItemExpandState;
/** Parent ID, if any */
parent: string | null;
/** Raw test item properties */
item: ITestItem;
}
export namespace InternalTestItem {
export interface Serialized {
controllerId: string;
expand: TestItemExpandState;
parent: string | null;
item: ITestItem.Serialized;
}
export const serialize = (item: InternalTestItem): Serialized => ({
controllerId: item.controllerId,
expand: item.expand,
parent: item.parent,
item: ITestItem.serialize(item.item)
});
export const deserialize = (serialized: Serialized): InternalTestItem => ({
controllerId: serialized.controllerId,
expand: serialized.expand,
parent: serialized.parent,
item: ITestItem.deserialize(serialized.item)
});
}
/**
* A partial update made to an existing InternalTestItem.
*/
export interface ITestItemUpdate {
extId: string;
expand?: TestItemExpandState;
item?: Partial<ITestItem>;
}
export namespace ITestItemUpdate {
export interface Serialized {
extId: string;
expand?: TestItemExpandState;
item?: Partial<ITestItem.Serialized>;
}
export const serialize = (u: ITestItemUpdate): Serialized => {
let item: Partial<ITestItem.Serialized> | undefined;
if (u.item) {
item = {};
if (u.item.label !== undefined) { item.label = u.item.label; }
if (u.item.tags !== undefined) { item.tags = u.item.tags; }
if (u.item.busy !== undefined) { item.busy = u.item.busy; }
if (u.item.uri !== undefined) { item.uri = u.item.uri?.toJSON(); }
if (u.item.range !== undefined) { item.range = u.item.range?.toJSON(); }
if (u.item.description !== undefined) { item.description = u.item.description; }
if (u.item.error !== undefined) { item.error = u.item.error; }
if (u.item.sortText !== undefined) { item.sortText = u.item.sortText; }
}
return { extId: u.extId, expand: u.expand, item };
};
export const deserialize = (u: Serialized): ITestItemUpdate => {
let item: Partial<ITestItem> | undefined;
if (u.item) {
item = {};
if (u.item.label !== undefined) { item.label = u.item.label; }
if (u.item.tags !== undefined) { item.tags = u.item.tags; }
if (u.item.busy !== undefined) { item.busy = u.item.busy; }
if (u.item.range !== undefined) { item.range = u.item.range ? Range.lift(u.item.range) : null; }
if (u.item.description !== undefined) { item.description = u.item.description; }
if (u.item.error !== undefined) { item.error = u.item.error; }
if (u.item.sortText !== undefined) { item.sortText = u.item.sortText; }
}
return { extId: u.extId, expand: u.expand, item };
};
}
export const applyTestItemUpdate = (internal: InternalTestItem | ITestItemUpdate, patch: ITestItemUpdate) => {
if (patch.expand !== undefined) {
internal.expand = patch.expand;
}
if (patch.item !== undefined) {
internal.item = internal.item ? Object.assign(internal.item, patch.item) : patch.item;
}
};
/**
* Test result item used in the main thread.
*/
export interface TestResultItem extends InternalTestItem {
/** State of this test in various tasks */
tasks: ITestTaskState[];
/** State of this test as a computation of its tasks */
ownComputedState: TestResultState;
/** Computed state based on children */
computedState: TestResultState;
/** Max duration of the item's tasks (if run directly) */
ownDuration?: number;
}
export namespace TestResultItem {
/** Serialized version of the TestResultItem */
export interface Serialized extends InternalTestItem.Serialized {
children: string[];
tasks: ITestTaskState.Serialized[];
ownComputedState: TestResultState;
computedState: TestResultState;
}
export const serialize = (original: TestResultItem, children: string[]): Serialized => ({
...InternalTestItem.serialize(original),
children,
ownComputedState: original.ownComputedState,
computedState: original.computedState,
tasks: original.tasks.map(ITestTaskState.serialize),
});
}
export interface ISerializedTestResults {
/** ID of these test results */
id: string;
/** Time the results were compelted */
completedAt: number;
/** Subset of test result items */
items: TestResultItem.Serialized[];
/** Tasks involved in the run. */
tasks: { id: string; name: string | undefined; messages: ITestOutputMessage.Serialized[] }[];
/** Human-readable name of the test run. */
name: string;
/** Test trigger informaton */
request: ResolvedTestRunRequest;
}
export interface ITestCoverage {
files: IFileCoverage[];
}
export interface ICoveredCount {
covered: number;
total: number;
}
export interface IFileCoverage {
uri: URI;
statement: ICoveredCount;
branch?: ICoveredCount;
function?: ICoveredCount;
details?: CoverageDetails[];
}
export const enum DetailType {
Function,
Statement,
}
export type CoverageDetails = IFunctionCoverage | IStatementCoverage;
export interface IBranchCoverage {
count: number;
location?: IRange | IPosition;
}
export interface IFunctionCoverage {
type: DetailType.Function;
count: number;
location?: IRange | IPosition;
}
export interface IStatementCoverage {
type: DetailType.Statement;
count: number;
location: IRange | IPosition;
branches?: IBranchCoverage[];
}
export const enum TestDiffOpType {
/** Adds a new test (with children) */
Add,
/** Shallow-updates an existing test */
Update,
/** Removes a test (and all its children) */
Remove,
/** Changes the number of controllers who are yet to publish their collection roots. */
IncrementPendingExtHosts,
/** Retires a test/result */
Retire,
/** Add a new test tag */
AddTag,
/** Remove a test tag */
RemoveTag,
}
export type TestsDiffOp =
| { op: TestDiffOpType.Add; item: InternalTestItem }
| { op: TestDiffOpType.Update; item: ITestItemUpdate }
| { op: TestDiffOpType.Remove; itemId: string }
| { op: TestDiffOpType.Retire; itemId: string }
| { op: TestDiffOpType.IncrementPendingExtHosts; amount: number }
| { op: TestDiffOpType.AddTag; tag: ITestTagDisplayInfo }
| { op: TestDiffOpType.RemoveTag; id: string };
export namespace TestsDiffOp {
export type Serialized =
| { op: TestDiffOpType.Add; item: InternalTestItem.Serialized }
| { op: TestDiffOpType.Update; item: ITestItemUpdate.Serialized }
| { op: TestDiffOpType.Remove; itemId: string }
| { op: TestDiffOpType.Retire; itemId: string }
| { op: TestDiffOpType.IncrementPendingExtHosts; amount: number }
| { op: TestDiffOpType.AddTag; tag: ITestTagDisplayInfo }
| { op: TestDiffOpType.RemoveTag; id: string };
export const deserialize = (u: Serialized): TestsDiffOp => {
if (u.op === TestDiffOpType.Add) {
return { op: u.op, item: InternalTestItem.deserialize(u.item) };
} else if (u.op === TestDiffOpType.Update) {
return { op: u.op, item: ITestItemUpdate.deserialize(u.item) };
} else {
return u;
}
};
export const serialize = (u: TestsDiffOp): Serialized => {
if (u.op === TestDiffOpType.Add) {
return { op: u.op, item: InternalTestItem.serialize(u.item) };
} else if (u.op === TestDiffOpType.Update) {
return { op: u.op, item: ITestItemUpdate.serialize(u.item) };
} else {
return u;
}
};
}
/**
* Context for actions taken in the test explorer view.
*/
export interface ITestItemContext {
/** Marshalling marker */
$mid: MarshalledId.TestItemContext;
/** Tests and parents from the root to the current items */
tests: InternalTestItem.Serialized[];
}
/**
* Request from the ext host or main thread to indicate that tests have
* changed. It's assumed that any item upserted *must* have its children
* previously also upserted, or upserted as part of the same operation.
* Children that no longer exist in an upserted item will be removed.
*/
export type TestsDiff = TestsDiffOp[];
/**
* @private
*/
export interface IncrementalTestCollectionItem extends InternalTestItem {
children: Set<string>;
}
/**
* The IncrementalChangeCollector is used in the IncrementalTestCollection
* and called with diff changes as they're applied. This is used in the
* ext host to create a cohesive change event from a diff.
*/
export class IncrementalChangeCollector<T> {
/**
* A node was added.
*/
public add(node: T): void { }
/**
* A node in the collection was updated.
*/
public update(node: T): void { }
/**
* A node was removed.
*/
public remove(node: T, isNestedOperation: boolean): void { }
/**
* Called when the diff has been applied.
*/
public complete(): void { }
}
/**
* Maintains tests in this extension host sent from the main thread.
*/
export abstract class AbstractIncrementalTestCollection<T extends IncrementalTestCollectionItem> {
private readonly _tags = new Map<string, ITestTagDisplayInfo>();
/**
* Map of item IDs to test item objects.
*/
protected readonly items = new Map<string, T>();
/**
* ID of test root items.
*/
protected readonly roots = new Set<T>();
/**
* Number of 'busy' controllers.
*/
protected busyControllerCount = 0;
/**
* Number of pending roots.
*/
protected pendingRootCount = 0;
/**
* Known test tags.
*/
public readonly tags: ReadonlyMap<string, ITestTagDisplayInfo> = this._tags;
/**
* Applies the diff to the collection.
*/
public apply(diff: TestsDiff) {
const changes = this.createChangeCollector();
for (const op of diff) {
switch (op.op) {
case TestDiffOpType.Add: {
const internalTest = InternalTestItem.deserialize(op.item);
if (!internalTest.parent) {
const created = this.createItem(internalTest);
this.roots.add(created);
this.items.set(internalTest.item.extId, created);
changes.add(created);
} else if (this.items.has(internalTest.parent)) {
const parent = this.items.get(internalTest.parent)!;
parent.children.add(internalTest.item.extId);
const created = this.createItem(internalTest, parent);
this.items.set(internalTest.item.extId, created);
changes.add(created);
}
if (internalTest.expand === TestItemExpandState.BusyExpanding) {
this.busyControllerCount++;
}
break;
}
case TestDiffOpType.Update: {
const patch = ITestItemUpdate.deserialize(op.item);
const existing = this.items.get(patch.extId);
if (!existing) {
break;
}
if (patch.expand !== undefined) {
if (existing.expand === TestItemExpandState.BusyExpanding) {
this.busyControllerCount--;
}
if (patch.expand === TestItemExpandState.BusyExpanding) {
this.busyControllerCount++;
}
}
applyTestItemUpdate(existing, patch);
changes.update(existing);
break;
}
case TestDiffOpType.Remove: {
const toRemove = this.items.get(op.itemId);
if (!toRemove) {
break;
}
if (toRemove.parent) {
const parent = this.items.get(toRemove.parent)!;
parent.children.delete(toRemove.item.extId);
} else {
this.roots.delete(toRemove);
}
const queue: Iterable<string>[] = [[op.itemId]];
while (queue.length) {
for (const itemId of queue.pop()!) {
const existing = this.items.get(itemId);
if (existing) {
queue.push(existing.children);
this.items.delete(itemId);
changes.remove(existing, existing !== toRemove);
if (existing.expand === TestItemExpandState.BusyExpanding) {
this.busyControllerCount--;
}
}
}
}
break;
}
case TestDiffOpType.Retire:
this.retireTest(op.itemId);
break;
case TestDiffOpType.IncrementPendingExtHosts:
this.updatePendingRoots(op.amount);
break;
case TestDiffOpType.AddTag:
this._tags.set(op.tag.id, op.tag);
break;
case TestDiffOpType.RemoveTag:
this._tags.delete(op.id);
break;
}
}
changes.complete();
}
/**
* Called when the extension signals a test result should be retired.
*/
protected retireTest(testId: string) {
// no-op
}
/**
* Updates the number of test root sources who are yet to report. When
* the total pending test roots reaches 0, the roots for all controllers
* will exist in the collection.
*/
public updatePendingRoots(delta: number) {
this.pendingRootCount += delta;
}
/**
* Called before a diff is applied to create a new change collector.
*/
protected createChangeCollector() {
return new IncrementalChangeCollector<T>();
}
/**
* Creates a new item for the collection from the internal test item.
*/
protected abstract createItem(internal: InternalTestItem, parent?: T): T;
} | the_stack |
const slashCode = '/'.charCodeAt(0);
const dotCode = '.'.charCodeAt(0);
/**
* @param {ExportsField} exportsField the exports field
* @returns {FieldProcessor} process callback
*/
export default function processExportsField(exportsField) {
return createFieldProcessor(buildExportsFieldPathTree(exportsField), assertExportsFieldRequest, assertExportTarget);
}
/**
* @param {PathTreeNode} treeRoot root
* @param {(s: string) => string} assertRequest assertRequest
* @param {(s: string, f: boolean) => void} assertTarget assertTarget
* @returns {FieldProcessor} field processor
*/
function createFieldProcessor(treeRoot, assertRequest, assertTarget) {
return function fieldProcessor(request, conditionNames) {
request = assertRequest(request);
const match = findMatch(request, treeRoot);
if (match === null) return [];
const [mapping, remainRequestIndex] = match;
/** @type {DirectMapping|null} */
let direct = null;
if (isConditionalMapping(mapping)) {
direct = conditionalMapping(/** @type {ConditionalMapping} */ mapping, conditionNames);
// matching not found
if (direct === null) return [];
} else {
direct = /** @type {DirectMapping} */ mapping;
}
let remainingRequest;
if (remainRequestIndex !== request.length + 1) {
remainingRequest =
remainRequestIndex < 0 ? request.slice(-remainRequestIndex - 1) : request.slice(remainRequestIndex);
}
return directMapping(remainingRequest, remainRequestIndex < 0, direct, conditionNames, assertTarget);
};
}
/**
* @param {string} request request
* @returns {string} updated request
*/
function assertExportsFieldRequest(request) {
if (request.charCodeAt(0) !== dotCode) {
throw new Error('Request should be relative path and start with "."');
}
if (request.length === 1) return '';
if (request.charCodeAt(1) !== slashCode) {
throw new Error('Request should be relative path and start with "./"');
}
if (request.charCodeAt(request.length - 1) === slashCode) {
throw new Error('Only requesting file allowed');
}
return request.slice(2);
}
/**
* @param {string} exp export target
* @param {boolean} expectFolder is folder expected
*/
function assertExportTarget(exp, expectFolder) {
if (exp.charCodeAt(0) === slashCode || (exp.charCodeAt(0) === dotCode && exp.charCodeAt(1) !== slashCode)) {
throw new Error(`Export should be relative path and start with "./", got ${JSON.stringify(exp)}.`);
}
const isFolder = exp.charCodeAt(exp.length - 1) === slashCode;
if (isFolder !== expectFolder) {
throw new Error(
expectFolder
? `Expecting folder to folder mapping. ${JSON.stringify(exp)} should end with "/"`
: `Expecting file to file mapping. ${JSON.stringify(exp)} should not end with "/"`,
);
}
}
/**
* Trying to match request to field
* @param {string} request request
* @param {PathTreeNode} treeRoot path tree root
* @returns {[MappingValue, number]|null} match or null, number is negative and one less when it's a folder mapping, number is request.length + 1 for direct mappings
*/
function findMatch(request, treeRoot) {
if (request.length === 0) {
const value = treeRoot.files.get('');
return value ? [value, 1] : null;
}
if (treeRoot.children === null && treeRoot.folder === null && treeRoot.wildcards === null) {
const value = treeRoot.files.get(request);
return value ? [value, request.length + 1] : null;
}
let node = treeRoot;
let lastNonSlashIndex = 0;
let slashIndex = request.indexOf('/', 0);
/** @type {[MappingValue, number]|null} */
let lastFolderMatch = null;
const applyFolderMapping = () => {
const folderMapping = node.folder;
if (folderMapping) {
if (lastFolderMatch) {
lastFolderMatch[0] = folderMapping;
lastFolderMatch[1] = -lastNonSlashIndex - 1;
} else {
lastFolderMatch = [folderMapping, -lastNonSlashIndex - 1];
}
}
};
const applyWildcardMappings = (wildcardMappings, remainingRequest) => {
if (wildcardMappings) {
for (const [key, target] of wildcardMappings) {
if (remainingRequest.startsWith(key)) {
if (!lastFolderMatch) {
lastFolderMatch = [target, lastNonSlashIndex + key.length];
} else if (lastFolderMatch[1] < lastNonSlashIndex + key.length) {
lastFolderMatch[0] = target;
lastFolderMatch[1] = lastNonSlashIndex + key.length;
}
}
}
}
};
while (slashIndex !== -1) {
applyFolderMapping();
const wildcardMappings = node.wildcards;
if (!wildcardMappings && node.children === null) return lastFolderMatch;
const folder = request.slice(lastNonSlashIndex, slashIndex);
applyWildcardMappings(wildcardMappings, folder);
if (node.children === null) return lastFolderMatch;
const newNode = node.children.get(folder);
if (!newNode) {
return lastFolderMatch;
}
node = newNode;
lastNonSlashIndex = slashIndex + 1;
slashIndex = request.indexOf('/', lastNonSlashIndex);
}
const remainingRequest = lastNonSlashIndex > 0 ? request.slice(lastNonSlashIndex) : request;
const value = node.files.get(remainingRequest);
if (value) {
return [value, request.length + 1];
}
applyFolderMapping();
applyWildcardMappings(node.wildcards, remainingRequest);
return lastFolderMatch;
}
/**
* @param {ConditionalMapping|DirectMapping|null} mapping mapping
* @returns {boolean} is conditional mapping
*/
function isConditionalMapping(mapping) {
return mapping !== null && typeof mapping === 'object' && !Array.isArray(mapping);
}
/**
* @param {string|undefined} remainingRequest remaining request when folder mapping, undefined for file mappings
* @param {boolean} subpathMapping true, for subpath mappings
* @param {DirectMapping|null} mappingTarget direct export
* @param {Set<string>} conditionNames condition names
* @param {(d: string, f: boolean) => void} assert asserting direct value
* @returns {string[]} mapping result
*/
function directMapping(remainingRequest, subpathMapping, mappingTarget, conditionNames, assert) {
if (mappingTarget === null) return [];
if (typeof mappingTarget === 'string') {
return [targetMapping(remainingRequest, subpathMapping, mappingTarget, assert)];
}
const targets = [];
for (const exp of mappingTarget) {
if (typeof exp === 'string') {
targets.push(targetMapping(remainingRequest, subpathMapping, exp, assert));
continue;
}
const mapping = conditionalMapping(exp, conditionNames);
if (!mapping) continue;
const innerExports = directMapping(remainingRequest, subpathMapping, mapping, conditionNames, assert);
for (const innerExport of innerExports) {
targets.push(innerExport);
}
}
return targets;
}
/**
* @param {string|undefined} remainingRequest remaining request when folder mapping, undefined for file mappings
* @param {boolean} subpathMapping true, for subpath mappings
* @param {string} mappingTarget direct export
* @param {(d: string, f: boolean) => void} assert asserting direct value
* @returns {string} mapping result
*/
function targetMapping(remainingRequest, subpathMapping, mappingTarget, assert) {
if (remainingRequest === undefined) {
assert(mappingTarget, false);
return mappingTarget;
}
if (subpathMapping) {
assert(mappingTarget, true);
return mappingTarget + remainingRequest;
}
assert(mappingTarget, false);
return mappingTarget.replace(/\*/g, remainingRequest.replace(/\$/g, '$$'));
}
/**
* @param {ConditionalMapping} conditionalMapping_ conditional mapping
* @param {Set<string>} conditionNames condition names
* @returns {DirectMapping|null} direct mapping if found
*/
function conditionalMapping(conditionalMapping_, conditionNames) {
/** @type {[ConditionalMapping, string[], number][]} */
const lookup = [[conditionalMapping_, Object.keys(conditionalMapping_), 0]];
// eslint-disable-next-line
loop: while (lookup.length > 0) {
const [mapping, conditions, j] = lookup[lookup.length - 1];
const last = conditions.length - 1;
for (let i = j; i < conditions.length; i++) {
const condition = conditions[i];
// assert default. Could be last only
if (i !== last) {
if (condition === 'default') {
throw new Error('Default condition should be last one');
}
} else if (condition === 'default') {
const innerMapping = mapping[condition];
// is nested
if (isConditionalMapping(innerMapping)) {
lookup[lookup.length - 1][2] = i + 1;
lookup.push([innerMapping, Object.keys(innerMapping), 0]);
// eslint-disable-next-line
continue loop;
}
return /** @type {DirectMapping} */ innerMapping;
}
if (conditionNames.has(condition)) {
const innerMapping = mapping[condition];
// is nested
if (isConditionalMapping(innerMapping)) {
lookup[lookup.length - 1][2] = i + 1;
lookup.push([innerMapping, Object.keys(innerMapping), 0]);
// eslint-disable-next-line
continue loop;
}
return /** @type {DirectMapping} */ innerMapping;
}
}
lookup.pop();
}
return null;
}
/**
* Internal helper to create path tree node
* to ensure that each node gets the same hidden class
* @returns {PathTreeNode} node
*/
function createNode() {
return {
children: null,
folder: null,
wildcards: null,
files: new Map(),
};
}
/**
* Internal helper for building path tree
* @param {PathTreeNode} root root
* @param {string} path path
* @param {MappingValue} target target
*/
function walkPath(root, path, target) {
if (path.length === 0) {
root.folder = target;
return;
}
let node = root;
// Typical path tree can looks like
// root
// - files: ["a.js", "b.js"]
// - children:
// node1:
// - files: ["a.js", "b.js"]
let lastNonSlashIndex = 0;
let slashIndex = path.indexOf('/', 0);
while (slashIndex !== -1) {
const folder = path.slice(lastNonSlashIndex, slashIndex);
let newNode;
if (node.children === null) {
newNode = createNode();
node.children = new Map();
node.children.set(folder, newNode);
} else {
newNode = node.children.get(folder);
if (!newNode) {
newNode = createNode();
node.children.set(folder, newNode);
}
}
node = newNode;
lastNonSlashIndex = slashIndex + 1;
slashIndex = path.indexOf('/', lastNonSlashIndex);
}
if (lastNonSlashIndex >= path.length) {
node.folder = target;
} else {
const file = lastNonSlashIndex > 0 ? path.slice(lastNonSlashIndex) : path;
if (file.endsWith('*')) {
if (node.wildcards === null) node.wildcards = new Map();
node.wildcards.set(file.slice(0, -1), target);
} else {
node.files.set(file, target);
}
}
}
/**
* @param {ExportsField} field exports field
* @returns {PathTreeNode} tree root
*/
function buildExportsFieldPathTree(field) {
const root = createNode();
// handle syntax sugar, if exports field is direct mapping for "."
if (typeof field === 'string') {
root.files.set('', field);
return root;
} else if (Array.isArray(field)) {
root.files.set('', field.slice());
return root;
}
const keys = Object.keys(field);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key.charCodeAt(0) !== dotCode) {
// handle syntax sugar, if exports field is conditional mapping for "."
if (i === 0) {
while (i < keys.length) {
const charCode = keys[i].charCodeAt(0);
if (charCode === dotCode || charCode === slashCode) {
throw new Error(
`Exports field key should be relative path and start with "." (key: ${JSON.stringify(key)})`,
);
}
i++;
}
root.files.set('', field);
return root;
}
throw new Error(`Exports field key should be relative path and start with "." (key: ${JSON.stringify(key)})`);
}
if (key.length === 1) {
root.files.set('', field[key]);
continue;
}
if (key.charCodeAt(1) !== slashCode) {
throw new Error(`Exports field key should be relative path and start with "./" (key: ${JSON.stringify(key)})`);
}
walkPath(root, key.slice(2), field[key]);
}
return root;
} | the_stack |
import { test } from '@jest/globals';
import { AbstractClassType, arrayRemoveItem, ClassType, CompilerContext, CustomError, getClassName, isClass, isFunction, urlJoin } from '@deepkit/core';
import { isExtendable } from '../src/reflection/extends';
import { ReceiveType, reflect, resolveReceiveType } from '../src/reflection/reflection';
import { isType, metaAnnotation, ReflectionKind, Type } from '../src/reflection/type';
import { IncomingMessage, ServerResponse } from 'http';
import { Writable } from 'stream';
import querystring from 'querystring';
import { entity } from '../src/decorator';
import { SerializationOptions, Serializer } from '../src/serializer';
export interface ProviderBase {
/**
* Per default all instances are singleton (scoped to its scope). Enabling transient makes the
* Injector create always a new instance for every consumer.
*/
transient?: true;
}
export type Token<T = any> = symbol | number | bigint | RegExp | boolean | string | InjectorToken<T> | AbstractClassType<T> | Type;
export function provide<T>(provider: Omit<ProviderProvide, 'provide'> | ClassType, type?: ReceiveType<T>): Provider {
if (isClass(provider)) return { provide: resolveReceiveType(type), useClass: provider };
return { ...provider, provide: resolveReceiveType(type) };
}
export interface ValueProvider<T> extends ProviderBase {
/**
* An injection token.
*/
provide: Token<T>;
/**
* The value to inject.
*/
useValue: T;
}
export interface ClassProvider<T> extends ProviderBase {
/**
* An injection token.
*/
provide: Token<T>;
/**
* Class to instantiate for the `token`.
*/
useClass?: ClassType<T>;
}
export interface ExistingProvider<T> extends ProviderBase {
/**
* An injection token.
*/
provide: Token<T>;
/**
* Existing `token` to return. (equivalent to `injector.get(useExisting)`)
*/
useExisting: ClassType<T>;
}
export interface FactoryProvider<T> extends ProviderBase {
/**
* An injection token.
*/
provide: Token<T>;
/**
* A function to invoke to create a value for this `token`. The function is invoked with
* resolved values of `token`s in the `deps` field.
*/
useFactory: (...args: any[]) => T;
/**
* A list of `token`s which need to be resolved by the injector. The list of values is then
* used as arguments to the `useFactory` function.
*
* @deprecated not necessary anymore
*/
deps?: any[];
}
export type Provider<T = any> = ClassType | ValueProvider<T> | ClassProvider<T> | ExistingProvider<T> | FactoryProvider<T> | TagProvider<T>;
export type ProviderProvide<T = any> = ValueProvider<T> | ClassProvider<T> | ExistingProvider<T> | FactoryProvider<T>;
interface TagRegistryEntry<T> {
tagProvider: TagProvider<T>;
module: InjectorModule;
}
export class TagRegistry {
constructor(
public tags: TagRegistryEntry<any>[] = []
) {
}
register(tagProvider: TagProvider<any>, module: InjectorModule) {
return this.tags.push({ tagProvider, module });
}
resolve<T extends ClassType<Tag<any>>>(tag: T): TagRegistryEntry<InstanceType<T>>[] {
return this.tags.filter(v => v.tagProvider.tag instanceof tag);
}
}
export class TagProvider<T> {
constructor(
public provider: NormalizedProvider<T>,
public tag: Tag<T>,
) {
}
}
export class Tag<T, TP extends TagProvider<T> = TagProvider<T>> {
_!: () => T;
_2!: () => TP;
constructor(
public readonly services: T[] = []
) {
}
protected createTagProvider(provider: NormalizedProvider<any>): TP {
return new TagProvider(provider, this) as TP;
}
static provide<P extends ClassType<T> | ValueProvider<T> | ClassProvider<T> | ExistingProvider<T> | FactoryProvider<T>,
T extends ReturnType<InstanceType<B>['_']>,
TP extends ReturnType<InstanceType<B>['_2']>,
B extends ClassType<Tag<any>>>(this: B, provider: P): TP {
const t = new this;
if (isClass(provider)) {
return t.createTagProvider({ provide: provider }) as TP;
}
return t.createTagProvider(provider as NormalizedProvider<T>) as TP;
}
}
export interface ProviderScope {
scope?: 'module' | 'rpc' | 'http' | 'cli' | string;
}
export type NormalizedProvider<T = any> = ProviderProvide<T> & ProviderScope;
export type ProviderWithScope<T = any> = ClassType | (ProviderProvide<T> & ProviderScope) | TagProvider<any>;
export function isScopedProvider(obj: any): obj is ProviderProvide & ProviderScope {
return obj.provide && obj.hasOwnProperty('scope');
}
export function isValueProvider(obj: any): obj is ValueProvider<any> {
return obj.provide && obj.hasOwnProperty('useValue');
}
export function isClassProvider(obj: any): obj is ClassProvider<any> {
return obj.provide && !isValueProvider(obj) && !isExistingProvider(obj) && !isFactoryProvider(obj);
}
export function isExistingProvider(obj: any): obj is ExistingProvider<any> {
return obj.provide && obj.hasOwnProperty('useExisting');
}
export function isFactoryProvider(obj: any): obj is FactoryProvider<any> {
return obj.provide && obj.hasOwnProperty('useFactory');
}
export function isInjectionProvider(obj: any): obj is Provider<any> {
return isValueProvider(obj) || isClassProvider(obj) || isExistingProvider(obj) || isFactoryProvider(obj);
}
export function isTransient(provider: ProviderWithScope): boolean {
if (isClass(provider)) return false;
if (provider instanceof TagProvider) return false;
return provider.transient === true;
}
export function getProviders(
providers: ProviderWithScope[],
requestScope: 'module' | 'session' | 'request' | string,
) {
const result: Provider<any>[] = [];
function normalize(provider: ProviderWithScope<any>): Provider<any> {
if (isClass(provider)) {
return provider;
}
return provider;
}
for (const provider of providers) {
if (isClass(provider)) {
if (requestScope === 'module') result.push(provider);
continue;
}
if (isClass(provider)) {
if (requestScope === 'module') result.push(provider);
continue;
}
const scope = isScopedProvider(provider) ? provider.scope : 'module';
if (scope === requestScope) {
result.push(normalize(provider));
}
}
return result;
}
export type ConfigureProvider<T> = { [name in keyof T]: T[name] extends (...args: infer A) => any ? (...args: A) => ConfigureProvider<T> : T[name] };
/**
* Returns a configuration object that reflects the API of the given ClassType or token. Each call
* is scheduled and executed once the provider has been created by the dependency injection container.
*/
export function setupProvider<T extends ClassType<T> | any>(classTypeOrToken: Token<T>, registry: SetupProviderRegistry, order: number): ConfigureProvider<T extends ClassType<infer C> ? C : T> {
const proxy = new Proxy({}, {
get(target, prop) {
return (...args: any[]) => {
registry.add(classTypeOrToken, { type: 'call', methodName: prop, args: args, order });
return proxy;
};
},
set(target, prop, value) {
registry.add(classTypeOrToken, { type: 'property', property: prop, value: value, order });
return true;
}
});
return proxy as any;
}
let moduleIds: number = 0;
export interface PreparedProvider {
/**
* The modules from which dependencies can be resolved. The first item is always the module from which this provider was declared.
*
* This is per default the module in which the provider was declared,
* but if the provider was moved (by exporting), then if
* a) the parent had this provider already, then this array has additionally the one from which the provider was exported.
* b) the parent had no provider of that token, then this array is just the module from which the provider was exported.
*
* This is important otherwise exported provider won't have access in their dependencies to their original (encapsulated) injector.
*/
modules: InjectorModule[];
/**
* A token can have multiple providers, for each scope its own entry.
* Each scoped provider can only exist once.
*/
providers: NormalizedProvider[];
/**
* When this provider was exported to another module and thus is actually instantiated in another module, then this is set.
* This is necessary to tell the module who declared this provider to not instantiate it, but redirects resolve requests
* to `resolveFrom` instead.
*/
resolveFrom?: InjectorModule;
}
function registerPreparedProvider(map: Map<Token<any>, PreparedProvider>, modules: InjectorModule[], providers: NormalizedProvider[], replaceExistingScope: boolean = true) {
const token = providers[0].provide;
const preparedProvider = map.get(token);
if (preparedProvider) {
for (const m of modules) {
if (preparedProvider.modules.includes(m)) continue;
preparedProvider.modules.push(m);
}
for (const provider of providers) {
const scope = getScope(provider);
//check if given provider has a unknown scope, if so set it.
//if the scope is known, overwrite it (we want always the last known provider to be valid)
const knownProvider = preparedProvider.providers.findIndex(v => getScope(v) === scope);
if (knownProvider === -1) {
//scope not known, add it
preparedProvider.providers.push(provider);
} else if (replaceExistingScope) {
//scope already known, replace it
preparedProvider.providers.splice(knownProvider, 1, provider);
}
}
} else {
//just add it
map.set(token, { modules, providers: providers.slice(0) });
}
}
export function findModuleForConfig(config: ClassType, modules: InjectorModule[]): InjectorModule | undefined {
for (const m of modules) {
if (m.configDefinition === config) return m;
}
return undefined;
}
export type ExportType = Token | InjectorModule;
export function isProvided(providers: ProviderWithScope[], token: any): boolean {
return providers.find(v => !(v instanceof TagProvider) ? token === (isClass(v) ? v : v.provide) : false) !== undefined;
}
export function getScope(provider: ProviderWithScope): string {
return (isClass(provider) ? '' : provider instanceof TagProvider ? provider.provider.scope : provider.scope) || '';
}
export class InjectorModule<C extends { [name: string]: any } = any, IMPORT = InjectorModule<any, any>> {
public id: number = moduleIds++;
/**
* Whether this module is for the root module. All its providers are automatically exported and moved to the root level.
*/
public root: boolean = false;
/**
* The built injector. This is set once an Injector for this module has been created.
*/
injector?: Injector;
public setupProviderRegistry: SetupProviderRegistry = new SetupProviderRegistry;
public globalSetupProviderRegistry: SetupProviderRegistry = new SetupProviderRegistry;
imports: InjectorModule[] = [];
/**
* The first stage of building the injector is to resolve all providers and exports.
* Then the actual injector functions can be built.
*/
protected processed: boolean = false;
protected exportsDisabled: boolean = false;
public configDefinition?: ClassType;
constructor(
public providers: ProviderWithScope[] = [],
public parent?: InjectorModule,
public config: C = {} as C,
public exports: ExportType[] = []
) {
if (this.parent) this.parent.registerAsChildren(this);
}
registerAsChildren(child: InjectorModule): void {
if (this.imports.includes(child)) return;
this.imports.push(child);
}
/**
* When the module exports providers the importer don't want to have then `disableExports` disable all exports.
*/
disableExports(): this {
this.exportsDisabled = true;
return this;
}
/**
* Makes all the providers, controllers, etc available at the root module, basically exporting everything.
*/
forRoot(): this {
this.root = true;
return this;
}
/**
* Reverts the root default setting to false.
*/
notForRoot(): this {
this.root = false;
return this;
}
unregisterAsChildren(child: InjectorModule): void {
if (!this.imports.includes(child)) return;
child.parent = undefined;
arrayRemoveItem(this.imports, child);
}
getChildren(): InjectorModule[] {
return this.imports;
}
setConfigDefinition(config: ClassType): this {
this.configDefinition = config;
const configDefaults = new config;
this.config = Object.assign(configDefaults, this.config);
return this;
}
setParent(parent: InjectorModule): this {
if (this.parent === parent) return this;
this.assertInjectorNotBuilt();
if (this.parent) this.parent.unregisterAsChildren(this);
this.parent = parent;
this.parent.registerAsChildren(this);
return this;
}
getParent(): InjectorModule | undefined {
return this.parent;
}
protected assertInjectorNotBuilt(): void {
if (!this.injector) return;
throw new Error(`Injector already built for ${getClassName(this)}. Can not modify its provider or tree structure.`);
}
addExport(...controller: ClassType[]): this {
this.assertInjectorNotBuilt();
this.exports.push(...controller);
return this;
}
isExported(token: Token): boolean {
return this.exports.includes(token);
}
isProvided(classType: ClassType): boolean {
return isProvided(this.getProviders(), classType);
}
addProvider(...provider: ProviderWithScope[]): this {
this.assertInjectorNotBuilt();
this.providers.push(...provider);
return this;
}
getProviders(): ProviderWithScope[] {
return this.providers;
}
getConfig(): C {
return this.config;
}
configure(config: Partial<C>): this {
Object.assign(this.config, config);
return this;
}
getImports(): InjectorModule[] {
return this.imports;
}
getImportedModulesByClass<T extends InjectorModule>(classType: ClassType<T>): T[] {
return this.getImports().filter(v => v instanceof classType) as T[];
}
getImportedModuleByClass<T extends InjectorModule>(classType: ClassType<T>): T {
const v = this.getImports().find(v => v instanceof classType);
if (!v) {
throw new Error(`No module ${getClassName(classType)} in ${getClassName(this)}#${this.id} imported.`);
}
return v as T;
}
getImportedModule<T extends InjectorModule>(module: T): T {
const v = this.getImports().find(v => v.id === module.id);
if (!v) {
throw new Error(`No module ${getClassName(module)}#${module.id} in ${getClassName(this)}#${this.id} imported.`);
}
return v as T;
}
getExports() {
return this.exports;
}
hasImport<T extends InjectorModule>(moduleClass: ClassType<T>): boolean {
for (const importModule of this.getImports()) {
if (importModule instanceof moduleClass) return true;
}
return false;
}
/**
* Adds a new import at the end.
*/
addImport(...modules: InjectorModule<any>[]): this {
this.assertInjectorNotBuilt();
for (const module of modules) {
module.setParent(this);
}
return this;
}
/**
* Adds a new import at the beginning. Since import order matters, it might be useful to import a module first
* so its exported providers can be overwritten by imports following this module.
*/
addImportAtBeginning(...modules: InjectorModule<any>[]): this {
this.assertInjectorNotBuilt();
for (const module of modules) {
module.parent = this;
this.imports.unshift(module);
}
return this;
}
/**
* Allows to register additional setup calls for a provider in this module.
* The injector token needs to be available in the local module providers.
* Use setupGlobalProvider to register globally setup calls (not limited to this module only).
*
* Returns a object that reflects the API of the given ClassType or token. Each call
* is scheduled and executed once the provider is created by the dependency injection container.
*/
setupProvider<T extends ClassType<T> | any>(classTypeOrToken: Token<T>, order: number = 0): ConfigureProvider<T extends ClassType<infer C> ? C : T> {
return setupProvider(classTypeOrToken, this.setupProviderRegistry, order);
}
/**
* Allows to register additional setup calls for a provider in the whole module tree.
* The injector token needs to be available in the local module providers.
*
* Returns a object that reflects the API of the given ClassType or token. Each call
* is scheduled and executed once the provider is created by the dependency injection container.
*/
setupGlobalProvider<T extends ClassType<T> | any>(classTypeOrToken: Token<T>, order: number = 0): ConfigureProvider<T extends ClassType<infer C> ? C : T> {
return setupProvider(classTypeOrToken, this.globalSetupProviderRegistry, order);
}
getOrCreateInjector(buildContext: BuildContext): Injector {
if (this.injector) return this.injector;
//notify everyone we know to prepare providers
if (this.parent) this.parent.getPreparedProviders(buildContext);
this.getPreparedProviders(buildContext);
//handle exports, from bottom to up
if (this.parent) this.parent.handleExports(buildContext);
this.handleExports(buildContext);
//build the injector context
if (this.parent) this.parent.getOrCreateInjector(buildContext);
this.injector = new Injector(this, buildContext);
for (const child of this.imports) child.getOrCreateInjector(buildContext);
return this.injector;
}
protected preparedProviders?: Map<Token, PreparedProvider>;
getPreparedProvider(token: Token): { token: Token, provider: PreparedProvider } | undefined {
if (!this.preparedProviders) return;
if (isType(token)) {
let last = undefined as { token: Token, provider: PreparedProvider } | undefined;
for (const [key, value] of this.preparedProviders.entries()) {
if (isType(key) && isExtendable(key, token)) last = { token: key, provider: value };
}
if (last) return last;
}
const provider = this.preparedProviders.get(token);
if (provider) return { token, provider };
return;
}
resolveToken(token: Token): InjectorModule | undefined {
const found = this.getPreparedProvider(token);
if (found) return this;
if (this.parent) return this.parent.resolveToken(token);
return;
}
getBuiltPreparedProviders(): Map<any, PreparedProvider> | undefined {
return this.preparedProviders;
}
/**
* Prepared the module for a injector tree build.
*
* - Index providers by token so that last known provider is picked (so they can be overwritten).
* - Register TagProvider in TagRegistry
* - Put TagProvider in providers if not already made.
* - Put exports to parent's module with the reference to this, so the dependencies are fetched from the correct module.
*/
getPreparedProviders(buildContext: BuildContext): Map<any, PreparedProvider> {
if (this.preparedProviders) return this.preparedProviders;
for (const m of this.imports) {
m.getPreparedProviders(buildContext);
}
this.preparedProviders = new Map<any, PreparedProvider>();
this.globalSetupProviderRegistry.mergeInto(buildContext.globalSetupProviderRegistry);
//make sure that providers that declare the same provider token will be filtered out so that the last will be used.
for (const provider of this.providers) {
if (provider instanceof TagProvider) {
buildContext.tagRegistry.register(provider, this);
if (!this.preparedProviders.has(provider.provider.provide)) {
//we dont want to overwrite that provider with a tag
registerPreparedProvider(this.preparedProviders, [this], [provider.provider]);
}
} else if (isClass(provider)) {
registerPreparedProvider(this.preparedProviders, [this], [{ provide: provider }]);
} else {
registerPreparedProvider(this.preparedProviders, [this], [provider]);
}
}
return this.preparedProviders;
}
protected exported: boolean = false;
protected handleExports(buildContext: BuildContext) {
}
findRoot(): InjectorModule {
if (this.parent) return this.parent.findRoot();
return this;
}
}
export class CircularDependencyError extends CustomError {
}
export class TokenNotFoundError extends CustomError {
}
export class DependenciesUnmetError extends CustomError {
}
export class InjectorReference {
constructor(public readonly to: any, public module?: InjectorModule) {
}
}
export function injectorReference<T>(classTypeOrToken: T, module?: InjectorModule): any {
return new InjectorReference(classTypeOrToken, module);
}
/**
* An injector token for tokens that have no unique class or interface.
*
* ```typescript
* export interface ServiceInterface {
* doIt(): void;
* }
* export const Service = new InjectorToken<ServiceInterface>('service');
*
* {
* providers: [
* {provide: Service, useFactory() => ... },
* ]
* }
*
* //user side
* const service = injector.get(Service);
* service.doIt();
* ```
*/
export class InjectorToken<T> {
type!: T;
constructor(public readonly name: string) {
}
toString() {
return 'InjectToken=' + this.name;
}
}
export function tokenLabel(token: any): string {
if (token === null) return 'null';
if (token === undefined) return 'undefined';
if (token instanceof TagProvider) return 'Tag(' + getClassName(token.provider.provide) + ')';
if (isClass(token)) return getClassName(token);
if (isFunction(token.toString)) return token.name;
return token + '';
}
function constructorParameterNotFound(ofName: string, name: string, position: number, token: any) {
const argsCheck: string[] = [];
for (let i = 0; i < position; i++) argsCheck.push('✓');
argsCheck.push('?');
throw new DependenciesUnmetError(
`Unknown constructor argument '${name}: ${tokenLabel(token)}' of ${ofName}(${argsCheck.join(', ')}). Make sure '${tokenLabel(token)}' is provided.`
);
}
function tokenNotfoundError(token: any, moduleName: string) {
throw new TokenNotFoundError(
`Token '${tokenLabel(token)}' in ${moduleName} not found. Make sure '${tokenLabel(token)}' is provided.`
);
}
function factoryDependencyNotFound(ofName: string, name: string, position: number, token: any) {
const argsCheck: string[] = [];
for (let i = 0; i < position; i++) argsCheck.push('✓');
argsCheck.push('?');
for (const reset of CircularDetectorResets) reset();
throw new DependenciesUnmetError(
`Unknown factory dependency argument '${tokenLabel(token)}' of ${ofName}(${argsCheck.join(', ')}). Make sure '${tokenLabel(token)}' is provided.`
);
}
function propertyParameterNotFound(ofName: string, name: string, position: number, token: any) {
for (const reset of CircularDetectorResets) reset();
throw new DependenciesUnmetError(
`Unknown property parameter ${name} of ${ofName}. Make sure '${tokenLabel(token)}' is provided.`
);
}
let CircularDetector: any[] = [];
let CircularDetectorResets: (() => void)[] = [];
function throwCircularDependency() {
const path = CircularDetector.map(tokenLabel).join(' -> ');
CircularDetector.length = 0;
for (const reset of CircularDetectorResets) reset();
throw new CircularDependencyError(`Circular dependency found ${path}`);
}
export type SetupProviderCalls = {
type: 'call', methodName: string | symbol | number, args: any[], order: number
}
| { type: 'property', property: string | symbol | number, value: any, order: number }
| { type: 'stop', order: number }
;
export class SetupProviderRegistry {
public calls = new Map<Token, SetupProviderCalls[]>();
public add(token: any, ...newCalls: SetupProviderCalls[]) {
this.get(token).push(...newCalls);
}
mergeInto(registry: SetupProviderRegistry): void {
for (const [token, calls] of this.calls) {
registry.add(token, ...calls);
}
}
public get(token: Token): SetupProviderCalls[] {
let calls = this.calls.get(token);
if (!calls) {
calls = [];
this.calls.set(token, calls);
}
return calls;
}
}
interface Scope {
name: string;
instances: { [name: string]: any };
}
export type ResolveToken<T> = T extends ClassType<infer R> ? R : T extends InjectorToken<infer R> ? R : T;
export function resolveToken(provider: ProviderWithScope): Token {
if (isClass(provider)) return provider;
if (provider instanceof TagProvider) return resolveToken(provider.provider);
return provider.provide;
}
export interface InjectorInterface {
get<T>(token: T, scope?: Scope): ResolveToken<T>;
}
/**
* Returns the injector token type if the given type was decorated with `Inject<T>`.
*/
function getInjectOptions(type: Type): Type | undefined {
const annotations = metaAnnotation.getAnnotations(type);
for (const annotation of annotations) {
if (annotation.name === 'inject') {
const t = annotation.options[0] as Type;
return t.kind !== ReflectionKind.never ? t : type;
}
}
return;
}
/**
* This is the actual dependency injection container.
* Every module has its own injector.
*/
export class Injector implements InjectorInterface {
private resolver?: (token: any, scope?: Scope) => any;
private setter?: (token: any, value: any, scope?: Scope) => any;
private instantiations?: (token: any, scope?: string) => number;
/**
* All unscoped provider instances. Scoped instances are attached to `Scope`.
*/
private instances: { [name: string]: any } = {};
private instantiated: { [name: string]: number } = {};
constructor(
public readonly module: InjectorModule,
private buildContext: BuildContext,
) {
module.injector = this;
this.build(buildContext);
}
static from(providers: ProviderWithScope[], parent?: Injector): Injector {
return new Injector(new InjectorModule(providers, parent?.module), new BuildContext);
}
static fromModule(module: InjectorModule, parent?: Injector): Injector {
return new Injector(module, new BuildContext);
}
get<T>(token: T, scope?: Scope): ResolveToken<T> {
if (!this.resolver) throw new Error('Injector was not built');
return this.resolver(token, scope);
}
set<T>(token: T, value: any, scope?: Scope): void {
if (!this.setter) throw new Error('Injector was not built');
this.setter(token, value, scope);
}
instantiationCount<T>(token: any, scope?: string): number {
if (!this.instantiations) throw new Error('Injector was not built');
return this.instantiations(token, scope);
}
clear() {
this.instances = {};
}
protected build(buildContext: BuildContext): void {
}
protected buildProvider(
buildContext: BuildContext,
compiler: CompilerContext,
name: string,
accessor: string,
scope: string,
provider: NormalizedProvider,
resolveDependenciesFrom: InjectorModule[],
) {
return ``;
}
protected createFactory(
provider: NormalizedProvider,
resolvedName: string,
compiler: CompilerContext,
classType: ClassType,
resolveDependenciesFrom: InjectorModule[]
): { code: string, dependencies: number } {
return {
code: ``,
dependencies: 0
};
}
protected createFactoryProperty(
options: { name: string, type: Type, optional: boolean },
fromProvider: NormalizedProvider,
compiler: CompilerContext,
resolveDependenciesFrom: InjectorModule[],
ofName: string,
argPosition: number,
notFoundFunction: string
): string {
return '';
}
}
class BuildProviderIndex {
protected offset: number = 0;
reserve(): number {
return this.offset++;
}
}
export class BuildContext {
static ids: number = 0;
public id: number = BuildContext.ids++;
tagRegistry: TagRegistry = new TagRegistry;
providerIndex: BuildProviderIndex = new BuildProviderIndex;
/**
* In the process of preparing providers, each module redirects their
* global setup calls in this registry.
*/
globalSetupProviderRegistry: SetupProviderRegistry = new SetupProviderRegistry;
}
/**
* A InjectorContext is responsible for taking a root InjectorModule and build all Injectors.
*
* It also can create scopes aka a sub InjectorContext with providers from a particular scope.
*/
export class InjectorContext {
constructor(
public rootModule: InjectorModule,
public readonly scope?: Scope,
protected buildContext: BuildContext = new BuildContext,
) {
}
get<T>(token: T | Token, module?: InjectorModule): ResolveToken<T> {
return this.getInjector(module || this.rootModule).get(token, this.scope) as ResolveToken<T>;
}
instantiationCount(token: Token, module?: InjectorModule, scope?: string): number {
return this.getInjector(module || this.rootModule).instantiationCount(token, this.scope ? this.scope.name : scope);
}
set<T>(token: T, value: any, module?: InjectorModule): void {
return this.getInjector(module || this.rootModule).set(token, value, this.scope);
}
static forProviders(providers: ProviderWithScope[]) {
return new InjectorContext(new InjectorModule(providers));
}
/**
* Returns the unscoped injector. Use `.get(T, Scope)` for resolving scoped token.
*/
getInjector(module: InjectorModule): Injector {
return module.getOrCreateInjector(this.buildContext);
}
getRootInjector(): Injector {
return this.getInjector(this.rootModule);
}
public createChildScope(scope: string): InjectorContext {
return new InjectorContext(this.rootModule, { name: scope, instances: {} }, this.buildContext);
}
}
@entity.name('@deepkit/UploadedFile')
export class UploadedFile {
/**
* The size of the uploaded file in bytes.
*/
size!: number;
/**
* The path this file is being written to.
*/
path!: string;
/**
* The name this file had according to the uploading client.
*/
name!: string | null;
/**
* The mime type of this file, according to the uploading client.
*/
type!: string | null;
/**
* A Date object (or `null`) containing the time this file was last written to.
* Mostly here for compatibility with the [W3C File API Draft](http://dev.w3.org/2006/webapi/FileAPI/).
*/
lastModifiedDate!: Date | null;
// /**
// * If `options.hash` calculation was set, you can read the hex digest out of this var.
// */
// hash!: string | 'sha1' | 'md5' | 'sha256' | null;
}
export class HttpResponse extends ServerResponse {
status(code: number) {
this.writeHead(code);
this.end();
}
}
export type HttpRequestQuery = { [name: string]: string };
export type HttpRequestResolvedParameters = { [name: string]: any };
export type HttpBody<T> = T & { __meta?: ['httpBody'] };
export type HttpQuery<T, Options extends {name?: string} = {}> = T & { __meta?: ['httpQuery', Options] };
export type HttpQueries<T, Options extends {name?: string} = {}> = T & { __meta?: ['httpQueries', Options] };
export class RequestBuilder {
protected contentBuffer: Buffer = Buffer.alloc(0);
protected _headers: { [name: string]: string } = {};
protected queryPath?: string;
constructor(
protected path: string,
protected method: string = 'GET',
) {
}
getUrl() {
if (this.queryPath) {
return this.path + '?' + this.queryPath;
}
return this.path;
}
build(): HttpRequest {
const headers = this._headers;
const method = this.method;
const url = this.getUrl();
const bodyContent = this.contentBuffer;
const writable = new Writable({
write(chunk, encoding, callback) {
-
callback();
},
writev(chunks, callback) {
callback();
}
});
const request = new (class extends HttpRequest {
url = url;
method = method;
position = 0;
headers = headers;
done = false;
_read(size: number) {
if (!this.done) {
this.push(bodyContent);
process.nextTick(() => {
this.emit('end');
});
this.done = true;
}
}
})(writable as any);
return request;
}
headers(headers: { [name: string]: string }): this {
this._headers = headers;
return this;
}
header(name: string, value: string | number): this {
this._headers[name] = String(value);
return this;
}
json(body: object): this {
this.contentBuffer = Buffer.from(JSON.stringify(body), 'utf8');
this._headers['content-type'] = 'application/json; charset=utf-8';
this._headers['content-length'] = String(this.contentBuffer.byteLength);
return this;
}
body(body: string | Buffer): this {
if ('string' === typeof body) {
this.contentBuffer = Buffer.from(body, 'utf8');
} else {
this.contentBuffer = body;
}
this._headers['content-length'] = String(this.contentBuffer.byteLength);
return this;
}
query(query: any): this {
this.queryPath = querystring.stringify(query);
return this;
}
}
export class HttpRequest extends IncomingMessage {
/**
* A store that can be used to transport data from guards/listeners to ParameterResolvers/controllers.
*/
public store: { [name: string]: any } = {};
public uploadedFiles: { [name: string]: UploadedFile } = {};
static GET(path: string): RequestBuilder {
return new RequestBuilder(path);
}
static POST(path: string): RequestBuilder {
return new RequestBuilder(path, 'POST');
}
static OPTIONS(path: string): RequestBuilder {
return new RequestBuilder(path, 'OPTIONS');
}
static TRACE(path: string): RequestBuilder {
return new RequestBuilder(path, 'TRACE');
}
static HEAD(path: string): RequestBuilder {
return new RequestBuilder(path, 'HEAD');
}
static PATCH(path: string): RequestBuilder {
return new RequestBuilder(path, 'PATCH');
}
static PUT(path: string): RequestBuilder {
return new RequestBuilder(path, 'PUT');
}
static DELETE(path: string): RequestBuilder {
return new RequestBuilder(path, 'DELETE');
}
getUrl(): string {
return this.url || '/';
}
getMethod(): string {
return this.method || 'GET';
}
getRemoteAddress(): string {
return this.socket.remoteAddress || '';
}
}
export type RouteParameterResolverForInjector = ((injector: InjectorContext) => any[] | Promise<any[]>);
export interface RouteControllerAction {
//if not set, the root module is used
module?: InjectorModule<any>;
controller: ClassType;
methodName: string;
}
export type HttpMiddlewareFn = (req: HttpRequest, res: HttpResponse, next: (err?: any) => void) => void | Promise<void>;
export interface HttpMiddleware {
execute: HttpMiddlewareFn;
}
export interface HttpMiddlewareRoute {
path?: string;
pathRegExp?: RegExp;
httpMethod?: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'PUT' | 'DELETE' | 'OPTIONS' | 'TRACE';
category?: string;
excludeCategory?: string;
group?: string;
excludeGroup?: string;
}
export class HttpMiddlewareConfig {
name?: string;
middlewares: (HttpMiddlewareFn | ClassType<HttpMiddleware>)[] = [];
routes: HttpMiddlewareRoute[] = [];
excludeRoutes: HttpMiddlewareRoute[] = [];
order: number = 0;
controllers: ClassType[] = [];
excludeControllers: ClassType[] = [];
routeNames: string[] = [];
excludeRouteNames: string[] = [];
timeout: number = 4_000;
modules: InjectorModule<any>[] = [];
selfModule: boolean = false;
getClassTypes(): ClassType[] {
const classTypes: ClassType[] = [];
for (const middleware of this.middlewares) {
if (isClass(middleware)) classTypes.push(middleware);
}
return classTypes;
}
}
export interface RouteParameterConfig {
type?: 'body' | 'query' | 'queries';
/**
* undefined = propertyName, '' === root, else given path
*/
typePath?: string;
optional: boolean;
name: string;
}
export class RouteConfig {
public baseUrl: string = '';
public parameterRegularExpressions: { [name: string]: any } = {};
public responses: { statusCode: number, description: string, type?: Type }[] = [];
public description: string = '';
public groups: string[] = [];
public category: string = '';
/**
* This is set when the route action has a manual return type defined using @t.
*/
public returnType?: Type;
public serializationOptions?: SerializationOptions;
public serializer?: Serializer;
/**
* When assigned defines where this route came from.
*/
public module?: InjectorModule<any>;
resolverForToken: Map<any, ClassType> = new Map();
middlewares: { config: HttpMiddlewareConfig, module: InjectorModule<any> }[] = [];
resolverForParameterName: Map<string, ClassType> = new Map();
/**
* An arbitrary data container the user can use to store app specific settings/values.
*/
data = new Map<any, any>();
public parameters: {
[name: string]: RouteParameterConfig
} = {};
constructor(
public readonly name: string,
public readonly httpMethods: string[],
public readonly path: string,
public readonly action: RouteControllerAction,
public internal: boolean = false,
) {
}
getSchemaForResponse(statusCode: number): Type | undefined {
if (!this.responses.length) return;
for (const response of this.responses) {
if (response.statusCode === statusCode) return response.type;
}
return;
}
getFullPath(): string {
let path = this.baseUrl ? urlJoin(this.baseUrl, this.path) : this.path;
if (!path.startsWith('/')) path = '/' + path;
return path;
}
}
interface ResolvedController {
parameters: RouteParameterResolverForInjector;
routeConfig: RouteConfig;
uploadedFiles: { [name: string]: UploadedFile };
middlewares?: (injector: InjectorContext) => { fn: HttpMiddlewareFn, timeout: number }[];
}
export class HttpControllers {
constructor(public readonly controllers: {controller: ClassType, module: InjectorModule<any>}[] = []) {
}
public add(controller: ClassType, module: InjectorModule<any>) {
this.controllers.push({controller, module});
}
}
export interface MiddlewareConfig {
getClassTypes(): ClassType[];
}
export type MiddlewareRegistryEntry = { config: MiddlewareConfig, module: InjectorModule<any> };
export class MiddlewareRegistry {
public readonly configs: MiddlewareRegistryEntry[] = [];
}
export class Router {
protected fn?: (request: HttpRequest) => ResolvedController | undefined;
protected resolveFn?: (name: string, parameters: { [name: string]: any }) => string;
protected routes: RouteConfig[] = [];
constructor(
controllers: HttpControllers,
// private logger: Logger,
tagRegistry: TagRegistry,
private middlewareRegistry: MiddlewareRegistry = new MiddlewareRegistry,
) {
}
getRoutes(): RouteConfig[] {
return this.routes;
}
protected getRouteCode(compiler: CompilerContext, routeConfig: RouteConfig): string {
return '';
}
protected getRouteUrlResolveCode(compiler: CompilerContext, routeConfig: RouteConfig): string {
return '';
}
public addRoute(routeConfig: RouteConfig) {
}
public addRouteForController(controller: ClassType, module: InjectorModule<any>) {
}
protected buildUrlResolver(): any {
}
public resolveUrl(routeName: string, parameters: { [name: string]: any } = {}): string {
return '';
}
public resolveRequest(request: HttpRequest): ResolvedController | undefined {
return;
}
public resolve(method: string, url: string): ResolvedController | undefined {
method = method.toUpperCase();
return this.resolveRequest({ url, method } as any);
}
}
//
// test('TagRegistry', () => {
// const start = Date.now();
// const type = reflect(TagRegistry);
// console.log('TagRegistry took', Date.now() - start);
// });
//
// test('InjectorModule', () => {
// const start = Date.now();
// const type = reflect(InjectorModule);
// console.log('InjectorModule took', Date.now() - start);
// });
test('Router', () => {
const start = Date.now();
const type = reflect(Router);
console.log('Router took', Date.now() - start);
});
// test('Injector', () => {
// const start = Date.now();
// const type = reflect(Injector);
// console.log('Injector took', Date.now() - start);
// }); | the_stack |
import * as vscode from "vscode";
enum TokenType {
Invalid
, Word
, Assignment // = += -= *= /=
, Arrow // =>
, Block // {} [] ()
, PartialBlock // { [ (
, EndOfBlock // } ] )
, String
, PartialString
, Comment
, Whitespace
, Colon
, Comma
, CommaAsWord
, Insertion
}
interface Token {
type : TokenType;
text : string;
}
interface LineInfo {
line : vscode.TextLine;
sgfntTokenType : TokenType;
sgfntTokens : TokenType[];
tokens : Token[];
}
interface LineRange {
anchor : number;
infos : LineInfo[];
}
const REG_WS = /\s/;
const BRACKET_PAIR = {
"{" : "}"
, "[" : "]"
, "(" : ")"
};
function whitespace( count ) {
return new Array(count+1).join(" ");
}
export default class Formatter {
/* Align:
* operators = += -= *= /= :
* trailling comment
* preceding comma
* Ignore anything inside a quote, comment, or block
*/
public process( editor:vscode.TextEditor ):void {
this.editor = editor;
var ranges : LineRange[] = [];
editor.selections.forEach( (sel)=> {
const indentBase = this.getConfig().get("indentBase", "firstline") as string;
const importantIndent:boolean = indentBase == "dontchange";
let res:LineRange;
if ( sel.isSingleLine ) {
// If this selection is single line. Look up and down to search for the similar neighbour
ranges.push( this.narrow(0, editor.document.lineCount-1, sel.active.line, importantIndent) );
} else {
// Otherwise, narrow down the range where to align
let start = sel.start.line;
let end = sel.end.line;
while ( true ) {
res = this.narrow(start, end, start, importantIndent);
let lastLine = res.infos[res.infos.length - 1];
if ( lastLine.line.lineNumber > end ) {
break;
}
if ( res.infos[0] && res.infos[0].sgfntTokenType != TokenType.Invalid ) {
ranges.push( res );
}
if ( lastLine.line.lineNumber == end ) {
break;
}
start = lastLine.line.lineNumber + 1;
}
}
});
// Format
let formatted:string[][] = [];
for ( let range of ranges ) {
/*
console.log( `\n===============` );
for ( let info of range.infos ) {
console.log( `+++ [${info.line.lineNumber}]: ${TokenType[info.sgfntTokenType]} +++` );
console.log( info.line, info.tokens );
}
// */
formatted.push( this.format( range ) );
}
// Apply
editor.edit(( editBuilder )=>{
for ( let i = 0; i < ranges.length; ++i ) {
var infos = ranges[i].infos;
var lastline = infos[infos.length-1].line;
var location = new vscode.Range( infos[0].line.lineNumber,
0,
lastline.lineNumber,
lastline.text.length );
editBuilder.replace(location, formatted[i].join("\n"));
}
});
}
protected editor:vscode.TextEditor;
protected getConfig() {
let defaultConfig = vscode.workspace.getConfiguration("alignment");
let langConfig:Object = null;
try {
langConfig = vscode.workspace.getConfiguration().get(`[${this.editor.document.languageId}]`) as any;
} catch (e) {}
return {
get : function( key:any, defaultValue?:any ):any {
if ( langConfig ) {
var key1 = "alignment." + key;
if ( langConfig.hasOwnProperty(key1) ) {
return langConfig[key1];
}
}
return defaultConfig.get( key, defaultValue );
}
};
}
protected tokenize( line:number ):LineInfo {
let textline = this.editor.document.lineAt( line );
let text = textline.text;
let pos = 0;
let lt:LineInfo = {
line : textline
, sgfntTokenType : TokenType.Invalid
, sgfntTokens : []
, tokens : []
};
let lastTokenType = TokenType.Invalid;
let tokenStartPos = -1;
while ( pos < text.length ) {
let char = text.charAt(pos);
let next = text.charAt(pos+1);
let currTokenType:TokenType;
let nextSeek = 1;
// Tokens order are important
if ( char.match( REG_WS ) ) {
currTokenType = TokenType.Whitespace;
} else if ( char == "\"" || char == "'" || char == "`" ) {
currTokenType = TokenType.String;
} else if ( char == "{" || char == "(" || char == "[" ) {
currTokenType = TokenType.Block;
} else if ( char == "}" || char == ")" || char == "]" ) {
currTokenType = TokenType.EndOfBlock;
} else if ( char == "/" && (
(next == "/" && (pos > 0 ? text.charAt(pos-1) : "") != ":") // only `//` but not `://`
|| next == "*"
) ) {
currTokenType = TokenType.Comment;
} else if ( char == ":" && next != ":" ) {
currTokenType = TokenType.Colon;
} else if ( char == "," ) {
if ( lt.tokens.length == 0 || (lt.tokens.length == 1 && lt.tokens[0].type == TokenType.Whitespace) ) {
currTokenType = TokenType.CommaAsWord; // Comma-first style
} else {
currTokenType = TokenType.Comma;
}
} else if ( char == "=" && next == ">" ) {
currTokenType = TokenType.Arrow;
nextSeek = 2;
} else if ( char == "=" && next == "=" ) {
currTokenType = TokenType.Word;
nextSeek = 2;
} else if (( char == "+" || char == "-" || char == "*" || char == "/" ) && next == "=" ) {
currTokenType = TokenType.Assignment;
nextSeek = 2;
} else if ( char == "=" && next != "=" ) {
currTokenType = TokenType.Assignment;
} else {
currTokenType = TokenType.Word;
}
if ( currTokenType != lastTokenType ) {
if ( tokenStartPos != -1 ) {
lt.tokens.push({
type : lastTokenType
, text : textline.text.substr(tokenStartPos, pos - tokenStartPos)
});
}
lastTokenType = currTokenType;
tokenStartPos = pos;
if ( lastTokenType == TokenType.Assignment
|| lastTokenType == TokenType.Colon
|| lastTokenType == TokenType.Arrow )
{
if ( lt.sgfntTokens.indexOf(lastTokenType) === -1 ) {
lt.sgfntTokens.push( lastTokenType );
}
}
}
// Skip to end of string
if ( currTokenType == TokenType.String ) {
++pos;
while ( pos < text.length ) {
let quote = text.charAt(pos);
if ( quote == char && text.charAt(pos-1) != "\\" ) {
break;
}
++pos;
}
if ( pos >= text.length ) {
lastTokenType = TokenType.PartialString;
}
}
// Skip to end of block
if ( currTokenType == TokenType.Block ) {
++pos;
let bracketCount = 1;
while ( pos < text.length ) {
let bracket = text.charAt(pos);
if ( bracket == char ) {
++bracketCount;
} else if ( bracket == BRACKET_PAIR[char] && text.charAt(pos-1) != "\\" ) {
if ( bracketCount == 1 ) {
break;
} else {
--bracketCount;
}
}
++pos;
}
if ( pos >= text.length ) {
lastTokenType = TokenType.PartialBlock;
}
}
if ( char == "/" ) {
// Skip to end if we encounter single line comment
if ( next == "/" ) {
pos = text.length;
} else if ( next == "*" ) {
++pos;
while ( pos < text.length ) {
if ( text.charAt(pos) == "*" && text.charAt(pos+1) == "/" ) {
++pos;
currTokenType = TokenType.Word;
break;
}
++pos;
}
}
}
pos += nextSeek;
}
if ( tokenStartPos != -1 ) {
lt.tokens.push({
type : lastTokenType
, text : textline.text.substr(tokenStartPos, pos-tokenStartPos)
});
}
return lt;
}
protected hasPartialToken( info:LineInfo ):boolean {
for ( let j = info.tokens.length-1; j >= 0; --j ) {
let lastT = info.tokens[ j ];
if ( lastT.type == TokenType.PartialBlock
|| lastT.type == TokenType.EndOfBlock
|| lastT.type == TokenType.PartialString )
{
return true;
}
}
return false;
}
protected hasSameIndent( info1:LineInfo, info2:LineInfo ):boolean {
var t1 = info1.tokens[0];
var t2 = info2.tokens[0];
if ( t1.type == TokenType.Whitespace ) {
if ( t1.text == t2.text ) {
return true;
}
} else if ( t2.type != TokenType.Whitespace ) {
return true;
}
return false;
}
protected arrayAnd( array1:TokenType[], array2:TokenType[] ):TokenType[] {
var res:TokenType[] = []
var map = {}
for ( var i = 0; i < array1.length; ++i ) {
map[array1[i]] = true;
}
for ( var i = 0; i < array2.length; ++i ) {
if ( map[array2[i]] ) {
res.push( array2[i] );
}
}
return res;
}
/*
* Determine which blocks of code needs to be align.
* 1. Empty lines is the boundary of a block.
* 2. If user selects something, blocks are always within selection,
* but not necessarily is the selection.
* 3. Bracket / Brace usually means boundary.
* 4. Unsimilar line is boundary.
*/
protected narrow( start:number, end:number, anchor:number, importantIndent:boolean ):LineRange {
let anchorToken = this.tokenize( anchor );
let range = { anchor, infos:[ anchorToken ] };
let tokenTypes = anchorToken.sgfntTokens;
if ( anchorToken.sgfntTokens.length == 0 ) {
return range;
}
if ( this.hasPartialToken(anchorToken) ) {
return range;
}
let i = anchor - 1;
while ( i >= start ) {
let token = this.tokenize( i );
if ( this.hasPartialToken(token) ) {
break;
}
let tt = this.arrayAnd( tokenTypes, token.sgfntTokens );
if ( tt.length == 0 ) {
break;
}
tokenTypes = tt;
if ( importantIndent && !this.hasSameIndent(anchorToken, token) ) {
break;
}
range.infos.unshift( token );
--i;
}
i = anchor + 1;
while ( i <= end ) {
let token = this.tokenize(i);
let tt = this.arrayAnd( tokenTypes, token.sgfntTokens );
if ( tt.length == 0 ) {
break;
}
tokenTypes = tt;
if ( importantIndent && !this.hasSameIndent(anchorToken, token) ) {
break;
}
if ( this.hasPartialToken(token) ) {
range.infos.push( token );
break;
}
range.infos.push( token );
++i;
}
let sgt;
if ( tokenTypes.indexOf(TokenType.Assignment) >= 0 ) {
sgt = TokenType.Assignment;
} else {
sgt = tokenTypes[0];
}
for ( let info of range.infos ) {
info.sgfntTokenType = sgt;
}
return range;
}
protected format( range:LineRange ):string[] {
// 0. Remove indentatioin, and trailing whitespace
let indentation = null;
let anchorLine = range.infos[0];
const config = this.getConfig();
if (config.get("indentBase", "firstline") as string == "activeline") {
for ( let info of range.infos ) {
if ( info.line.lineNumber == range.anchor ) {
anchorLine = info;
break;
}
}
}
if ( anchorLine.tokens[0].type == TokenType.Whitespace ) {
indentation = anchorLine.tokens[0].text;
} else {
indentation = "";
}
for ( let info of range.infos ) {
if ( info.tokens[0].type == TokenType.Whitespace ) {
info.tokens.shift();
}
if ( info.tokens.length > 1 && info.tokens[ info.tokens.length - 1 ].type == TokenType.Whitespace ) {
info.tokens.pop();
}
}
// 1. Special treatment for Word-Word-Operator ( e.g. var abc = )
let firstWordLength = 0;
for ( let info of range.infos ) {
let count = 0;
for ( let token of info.tokens ) {
if ( token.type == info.sgfntTokenType ) {
count = -count;
break;
}
if ( token.type != TokenType.Whitespace ) {
++count;
}
}
if ( count < -1 ) {
firstWordLength = Math.max( firstWordLength, info.tokens[0].text.length );
}
}
if ( firstWordLength > 0 ) {
let wordSpace: Token = { type: TokenType.Insertion, text: whitespace( firstWordLength + 1 ) };
let oneSpace: Token = { type: TokenType.Insertion, text: " " };
for (let info of range.infos) {
let count = 0;
for (let token of info.tokens) {
if (token.type == info.sgfntTokenType) {
count = -count;
break;
}
if (token.type != TokenType.Whitespace) {
++count;
}
}
if (count == -1) {
info.tokens.unshift( wordSpace );
} else if (count < -1) {
if ( info.tokens[1].type == TokenType.Whitespace ) {
info.tokens[1] = oneSpace;
} else if ( info.tokens[0].type == TokenType.CommaAsWord ) {
info.tokens.splice(1, 0, oneSpace);
}
if ( info.tokens[0].text.length != firstWordLength ) {
let ws = { type: TokenType.Insertion, text: whitespace(firstWordLength-info.tokens[0].text.length) }
if ( info.tokens[0].type == TokenType.CommaAsWord ) {
info.tokens.unshift(ws);
} else {
info.tokens.splice(1,0,ws);
}
}
}
}
}
// 2. Remove whitespace surrounding operator ( comma in the middle of the line is also consider an operator ).
for ( let info of range.infos ) {
let i = 1;
while ( i < info.tokens.length ) {
if ( info.tokens[i].type == info.sgfntTokenType || info.tokens[i].type == TokenType.Comma ) {
if ( info.tokens[i-1].type == TokenType.Whitespace ) {
info.tokens.splice( i-1, 1 );
--i;
}
if ( info.tokens[i+1] && info.tokens[i+1].type == TokenType.Whitespace ) {
info.tokens.splice( i+1, 1 );
}
}
++i;
}
}
// 3. Align
const configOP = config.get("operatorPadding") as string;
const configWS = config.get("surroundSpace");
const stt = TokenType[range.infos[0].sgfntTokenType].toLowerCase();
const configDef = { "colon": [0, 1], "assignment": [1, 1], "comment": 2, "arrow" : [1, 1] };
const configSTT = configWS[stt] || configDef[stt];
const configComment = configWS["comment"] || configDef["comment"];
const rangeSize = range.infos.length;
let length = new Array<number>( rangeSize );
length.fill(0);
let column = new Array<number>( rangeSize );
column.fill(0);
let result = new Array<string>( rangeSize );
result.fill(indentation);
let exceed = 0; // Tracks how many line have reached to the end.
let hasTrallingComment = false;
let resultSize = 0;
while ( exceed < rangeSize ) {
let operatorSize = 0;
// First pass: for each line, scan until we reach to the next operator
for ( let l = 0; l < rangeSize; ++l ) {
let i = column[l];
let info = range.infos[l];
let tokenSize = info.tokens.length;
if ( i == -1 ) { continue; }
let end = tokenSize;
let res = result[l];
// Bail out if we reach to the trailing comment
if ( tokenSize > 1 && info.tokens[ tokenSize - 1 ].type == TokenType.Comment ) {
hasTrallingComment = true;
if ( tokenSize > 2 && info.tokens[ tokenSize - 2 ].type == TokenType.Whitespace ) {
end = tokenSize - 2;
} else {
end = tokenSize - 1;
}
}
for ( ; i < end; ++i ) {
let token = info.tokens[i];
// Vertical align will occur at significant operator or subsequent comma
if ( token.type == info.sgfntTokenType || (token.type == TokenType.Comma && i != 0) ) {
operatorSize = Math.max(operatorSize, token.text.length);
break;
} else {
res += token.text;
}
}
result[l] = res;
if ( i < end ) {
resultSize = Math.max(resultSize, res.length);
}
if ( i == end ) {
++exceed;
column[l] = -1;
info.tokens.splice( 0, end );
} else {
column[l] = i;
}
}
// Second pass: align
for ( let l = 0; l < rangeSize; ++l ) {
let i = column[l];
if ( i == -1 ) { continue; }
let info = range.infos[l];
let res = result[l];
let op = info.tokens[i].text;
if ( op.length < operatorSize ) {
if ( configOP == "right" ) {
op = whitespace( operatorSize - op.length ) + op;
} else {
op = op + whitespace( operatorSize - op.length );
}
}
let padding = "";
if ( resultSize > res.length ) {
padding = whitespace( resultSize - res.length );
}
if ( info.tokens[i].type == TokenType.Comma ) {
res += op;
if ( i < info.tokens.length - 1 ) {
res += padding + " "; // Ensure there's one space after comma.
}
} else {
if (configSTT[0] < 0) {
// operator will stick with the leftside word
if ( configSTT[1] < 0 ) {
// operator will be aligned, and the sibling token will be connected with the operator
let z = res.length - 1;
while ( z >= 0 ) {
let ch = res.charAt( z );
if ( ch.match(REG_WS) ) {
break;
}
--z;
}
res = res.substring(0, z+1) + padding + res.substring(z+1) + op;
} else {
res = res + op;
if ( i < info.tokens.length - 1 ) {
res += padding;
}
}
} else {
res = res + padding + whitespace(configSTT[0]) + op;
}
if (configSTT[1] > 0) {
res += whitespace(configSTT[1]);
}
}
result[l] = res;
column[l] = i+1;
}
}
// 4. Align trailing comment
if ( configComment < 0 ) {
// It means user don't want to align trailing comment.
for ( let l = 0; l < rangeSize; ++l ) {
let info = range.infos[l];
for ( let token of info.tokens ) {
result[l] += token.text;
}
}
} else {
resultSize = 0;
for ( let res of result ) {
resultSize = Math.max( res.length, resultSize );
}
for ( let l = 0; l < rangeSize; ++l ) {
let info = range.infos[l];
if ( info.tokens.length ) {
let res = result[l];
result[l] = res + whitespace(resultSize-res.length+configComment) + info.tokens.pop().text;
}
}
}
return result;
}
} | the_stack |
import { ExtensionTypes, IdentityTypes, RequestLogicTypes } from '@requestnetwork/types';
import Utils from '@requestnetwork/utils';
import { AbstractExtension } from '../abstract-extension';
const CURRENT_VERSION = '0.1.0';
/**
* Core of the declarative payment network
*/
export default class DeclarativePaymentNetwork<
TCreationParameters extends ExtensionTypes.PnAnyDeclarative.ICreationParameters = ExtensionTypes.PnAnyDeclarative.ICreationParameters,
> extends AbstractExtension<TCreationParameters> {
public constructor(
public extensionId: ExtensionTypes.ID = ExtensionTypes.ID.PAYMENT_NETWORK_ANY_DECLARATIVE,
public currentVersion: string = CURRENT_VERSION,
) {
super(ExtensionTypes.TYPE.PAYMENT_NETWORK, extensionId, currentVersion);
this.actions = {
...this.actions,
[ExtensionTypes.PnAnyDeclarative.ACTION.ADD_PAYMENT_INSTRUCTION]:
this.applyAddPaymentInstruction.bind(this),
[ExtensionTypes.PnAnyDeclarative.ACTION.ADD_REFUND_INSTRUCTION]:
this.applyAddRefundInstruction.bind(this),
[ExtensionTypes.PnAnyDeclarative.ACTION.DECLARE_SENT_PAYMENT]:
this.applyDeclareSentPayment.bind(this),
[ExtensionTypes.PnAnyDeclarative.ACTION.DECLARE_SENT_REFUND]:
this.applyDeclareSentRefund.bind(this),
[ExtensionTypes.PnAnyDeclarative.ACTION.DECLARE_RECEIVED_PAYMENT]:
this.applyDeclareReceivedPayment.bind(this),
[ExtensionTypes.PnAnyDeclarative.ACTION.DECLARE_RECEIVED_REFUND]:
this.applyDeclareReceivedRefund.bind(this),
[ExtensionTypes.PnAnyDeclarative.ACTION.ADD_DELEGATE]: this.applyAddDelegate.bind(this),
};
}
/**
* Creates the extensionsData to add a sent payment declaration
*
* @param parameters parameters to create sent payment declaration
*
* @returns IAction the extensionsData to be stored in the request
*/
public createDeclareSentPaymentAction(
parameters: ExtensionTypes.PnAnyDeclarative.ISentParameters,
): ExtensionTypes.IAction {
return {
action: ExtensionTypes.PnAnyDeclarative.ACTION.DECLARE_SENT_PAYMENT,
id: this.extensionId,
parameters: {
amount: parameters.amount.toString(),
note: parameters.note,
txHash: parameters.txHash,
network: parameters.network,
},
};
}
/**
* Creates the extensionsData to add a sent refund declaration
*
* @param parameters parameters to create sent refund declaration
*
* @returns IAction the extensionsData to be stored in the request
*/
public createDeclareSentRefundAction(
parameters: ExtensionTypes.PnAnyDeclarative.ISentParameters,
): ExtensionTypes.IAction {
return {
action: ExtensionTypes.PnAnyDeclarative.ACTION.DECLARE_SENT_REFUND,
id: this.extensionId,
parameters: {
amount: parameters.amount.toString(),
note: parameters.note,
txHash: parameters.txHash,
network: parameters.network,
},
};
}
/**
* Creates the extensionsData to add a received payment declaration
*
* @param parameters parameters to create received payment declaration
*
* @returns IAction the extensionsData to be stored in the request
*/
public createDeclareReceivedPaymentAction(
parameters: ExtensionTypes.PnAnyDeclarative.IReceivedParameters,
): ExtensionTypes.IAction {
return {
action: ExtensionTypes.PnAnyDeclarative.ACTION.DECLARE_RECEIVED_PAYMENT,
id: this.extensionId,
parameters: {
amount: parameters.amount.toString(),
note: parameters.note,
txHash: parameters.txHash,
network: parameters.network,
},
};
}
/**
* Creates the extensionsData to add a received refund declaration
*
* @param parameters parameters to create received refund declaration
*
* @returns IAction the extensionsData to be stored in the request
*/
public createDeclareReceivedRefundAction(
parameters: ExtensionTypes.PnAnyDeclarative.IReceivedParameters,
): ExtensionTypes.IAction {
return {
action: ExtensionTypes.PnAnyDeclarative.ACTION.DECLARE_RECEIVED_REFUND,
id: this.extensionId,
parameters: {
amount: parameters.amount.toString(),
note: parameters.note,
txHash: parameters.txHash,
network: parameters.network,
},
};
}
/**
* Creates the extensionsData to add payment instruction
*
* @param extensions extensions parameters to add payment instruction
*
* @returns IAction the extensionsData to be stored in the request
*/
public createAddPaymentInstructionAction(
parameters: ExtensionTypes.PnAnyDeclarative.IAddPaymentInstructionParameters,
): ExtensionTypes.IAction {
return {
action: ExtensionTypes.PnAnyDeclarative.ACTION.ADD_PAYMENT_INSTRUCTION,
id: this.extensionId,
parameters: {
paymentInfo: parameters.paymentInfo,
},
};
}
/**
* Creates the extensionsData to add refund instruction
*
* @param extensions extensions parameters to add refund instruction
*
* @returns IAction the extensionsData to be stored in the request
*/
public createAddRefundInstructionAction(
parameters: ExtensionTypes.PnAnyDeclarative.IAddRefundInstructionParameters,
): ExtensionTypes.IAction {
return {
action: ExtensionTypes.PnAnyDeclarative.ACTION.ADD_REFUND_INSTRUCTION,
id: this.extensionId,
parameters: {
refundInfo: parameters.refundInfo,
},
};
}
/**
* Creates the extensionsData to add delegate
*
* @param extensions extensions parameters to add delegate
*
* @returns IAction the extensionsData to be stored in the request
*/
public createAddDelegateAction(
parameters: ExtensionTypes.PnAnyDeclarative.IAddDelegateParameters,
): ExtensionTypes.IAction {
return {
action: ExtensionTypes.PnAnyDeclarative.ACTION.ADD_DELEGATE,
id: this.extensionId,
parameters: {
delegate: parameters.delegate,
},
};
}
/** Applies a creation
*
* @param extensionAction action to apply
* @param timestamp timestamp of the action
*
* @returns state of the extension created
*/
protected applyCreation(
extensionAction: ExtensionTypes.IAction,
timestamp: number,
): ExtensionTypes.IState {
const genericCreationAction = super.applyCreation(extensionAction, timestamp);
return {
...genericCreationAction,
events: [
{
name: 'create',
parameters: {
paymentInfo: extensionAction.parameters.paymentInfo,
refundInfo: extensionAction.parameters.refundInfo,
payeeDelegate: extensionAction.parameters.payeeDelegate,
payerDelegate: extensionAction.parameters.payerDelegate,
},
timestamp,
},
],
values: {
paymentInfo: extensionAction.parameters.paymentInfo,
receivedPaymentAmount: '0',
receivedRefundAmount: '0',
refundInfo: extensionAction.parameters.refundInfo,
sentPaymentAmount: '0',
sentRefundAmount: '0',
payeeDelegate: extensionAction.parameters.payeeDelegate,
payerDelegate: extensionAction.parameters.payerDelegate,
},
};
}
/** Applies a declare sent payment
*
* @param extensionsState previous state of the extensions
* @param extensionAction action to apply
* @param requestState request state read-only
* @param actionSigner identity of the signer
* @param timestamp timestamp of the action
*
* @returns state of the extension created
*/
protected applyDeclareSentPayment(
extensionState: ExtensionTypes.IState,
extensionAction: ExtensionTypes.IAction,
requestState: RequestLogicTypes.IRequest,
actionSigner: IdentityTypes.IIdentity,
timestamp: number,
): ExtensionTypes.IState {
this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYER);
if (!Utils.amount.isValid(extensionAction.parameters.amount)) {
throw Error(`The amount is not a valid amount`);
}
const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState);
// increment sentPaymentAmount
copiedExtensionState.values.sentPaymentAmount = Utils.amount.add(
copiedExtensionState.values.sentPaymentAmount,
extensionAction.parameters.amount,
);
// update events
copiedExtensionState.events.push({
name: ExtensionTypes.PnAnyDeclarative.ACTION.DECLARE_SENT_PAYMENT,
parameters: {
amount: extensionAction.parameters.amount,
note: extensionAction.parameters.note,
txHash: extensionAction.parameters.txHash,
network: extensionAction.parameters.network,
},
timestamp,
from: actionSigner,
});
return copiedExtensionState;
}
/** Applies a declare sent refund
*
* @param extensionsState previous state of the extensions
* @param extensionAction action to apply
* @param requestState request state read-only
* @param actionSigner identity of the signer
* @param timestamp timestamp of the action
*
* @returns state of the extension created
*/
protected applyDeclareSentRefund(
extensionState: ExtensionTypes.IState,
extensionAction: ExtensionTypes.IAction,
requestState: RequestLogicTypes.IRequest,
actionSigner: IdentityTypes.IIdentity,
timestamp: number,
): ExtensionTypes.IState {
this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYEE);
if (!Utils.amount.isValid(extensionAction.parameters.amount)) {
throw Error(`The amount is not a valid amount`);
}
const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState);
// increment sentRefundAmount
copiedExtensionState.values.sentRefundAmount = Utils.amount.add(
copiedExtensionState.values.sentRefundAmount,
extensionAction.parameters.amount,
);
// update events
copiedExtensionState.events.push({
name: ExtensionTypes.PnAnyDeclarative.ACTION.DECLARE_SENT_REFUND,
parameters: {
amount: extensionAction.parameters.amount,
note: extensionAction.parameters.note,
txHash: extensionAction.parameters.txHash,
network: extensionAction.parameters.network,
},
timestamp,
from: actionSigner,
});
return copiedExtensionState;
}
/** Applies a declare received payment
*
* @param extensionsState previous state of the extensions
* @param extensionAction action to apply
* @param requestState request state read-only
* @param actionSigner identity of the signer
* @param timestamp timestamp of the action
*
* @returns state of the extension created
*/
protected applyDeclareReceivedPayment(
extensionState: ExtensionTypes.IState,
extensionAction: ExtensionTypes.IAction,
requestState: RequestLogicTypes.IRequest,
actionSigner: IdentityTypes.IIdentity,
timestamp: number,
): ExtensionTypes.IState {
this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYEE);
if (!Utils.amount.isValid(extensionAction.parameters.amount)) {
throw Error(`The amount is not a valid amount`);
}
const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState);
// increment receivedPaymentAmount
copiedExtensionState.values.receivedPaymentAmount = Utils.amount.add(
copiedExtensionState.values.receivedPaymentAmount,
extensionAction.parameters.amount,
);
// update events
copiedExtensionState.events.push({
name: ExtensionTypes.PnAnyDeclarative.ACTION.DECLARE_RECEIVED_PAYMENT,
parameters: {
amount: extensionAction.parameters.amount,
note: extensionAction.parameters.note,
txHash: extensionAction.parameters.txHash,
network: extensionAction.parameters.network,
},
timestamp,
from: actionSigner,
});
return copiedExtensionState;
}
/** Applies a declare received refund
*
* @param extensionsState previous state of the extensions
* @param extensionAction action to apply
* @param requestState request state read-only
* @param actionSigner identity of the signer
* @param timestamp timestamp of the action
*
* @returns state of the extension created
*/
protected applyDeclareReceivedRefund(
extensionState: ExtensionTypes.IState,
extensionAction: ExtensionTypes.IAction,
requestState: RequestLogicTypes.IRequest,
actionSigner: IdentityTypes.IIdentity,
timestamp: number,
): ExtensionTypes.IState {
this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYER);
if (!Utils.amount.isValid(extensionAction.parameters.amount)) {
throw Error(`The amount is not a valid amount`);
}
const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState);
// increment receivedRefundAmount
copiedExtensionState.values.receivedRefundAmount = Utils.amount.add(
copiedExtensionState.values.receivedRefundAmount,
extensionAction.parameters.amount,
);
// update events
copiedExtensionState.events.push({
name: ExtensionTypes.PnAnyDeclarative.ACTION.DECLARE_RECEIVED_REFUND,
parameters: {
amount: extensionAction.parameters.amount,
note: extensionAction.parameters.note,
txHash: extensionAction.parameters.txHash,
network: extensionAction.parameters.network,
},
timestamp,
from: actionSigner,
});
return copiedExtensionState;
}
/** Applies an add of payment instruction
*
* @param extensionsState previous state of the extensions
* @param extensionAction action to apply
* @param requestState request state read-only
* @param actionSigner identity of the signer
* @param timestamp timestamp of the action
*
* @returns state of the extension created
*/
protected applyAddPaymentInstruction(
extensionState: ExtensionTypes.IState,
extensionAction: ExtensionTypes.IAction,
requestState: RequestLogicTypes.IRequest,
actionSigner: IdentityTypes.IIdentity,
timestamp: number,
): ExtensionTypes.IState {
if (extensionState.values.paymentInfo) {
throw Error(`The payment instruction already assigned`);
}
this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYEE);
const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState);
// assign paymentInfo
copiedExtensionState.values.paymentInfo = extensionAction.parameters.paymentInfo;
// update events
copiedExtensionState.events.push({
name: ExtensionTypes.PnAnyDeclarative.ACTION.ADD_PAYMENT_INSTRUCTION,
parameters: {
paymentInfo: extensionAction.parameters.paymentInfo,
},
timestamp,
from: actionSigner,
});
return copiedExtensionState;
}
/** Applies an add of a delegate
*
* @param extensionsState previous state of the extensions
* @param extensionAction action to apply
* @param requestState request state read-only
* @param actionSigner identity of the signer
* @param timestamp timestamp of the action
*
* @returns state of the extension created
*/
protected applyAddDelegate(
extensionState: ExtensionTypes.IState,
extensionAction: ExtensionTypes.IAction,
requestState: RequestLogicTypes.IRequest,
actionSigner: IdentityTypes.IIdentity,
timestamp: number,
): ExtensionTypes.IState {
let delegateStr: string;
if (Utils.identity.areEqual(actionSigner, requestState.payee)) {
delegateStr = 'payeeDelegate';
} else if (Utils.identity.areEqual(actionSigner, requestState.payer)) {
delegateStr = 'payerDelegate';
} else {
throw Error(`The signer must be the payee or the payer`);
}
if (extensionState.values[delegateStr]) {
throw Error(`The ${delegateStr} is already assigned`);
}
const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState);
// assign payeeDelegate or payerDelegate
copiedExtensionState.values[delegateStr] = extensionAction.parameters.delegate;
// update events
copiedExtensionState.events.push({
name: ExtensionTypes.PnAnyDeclarative.ACTION.ADD_DELEGATE,
parameters: {
delegate: extensionAction.parameters.delegate,
},
timestamp,
from: actionSigner,
});
return copiedExtensionState;
}
/** Applies an add of refund instruction
*
* @param extensionsState previous state of the extensions
* @param extensionAction action to apply
* @param requestState request state read-only
* @param actionSigner identity of the signer
* @param timestamp timestamp of the action
*
* @returns state of the extension created
*/
protected applyAddRefundInstruction(
extensionState: ExtensionTypes.IState,
extensionAction: ExtensionTypes.IAction,
requestState: RequestLogicTypes.IRequest,
actionSigner: IdentityTypes.IIdentity,
timestamp: number,
): ExtensionTypes.IState {
if (extensionState.values.refundInfo) {
throw Error(`The refund instruction already assigned`);
}
this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYER);
const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState);
// assign refundInfo
copiedExtensionState.values.refundInfo = extensionAction.parameters.refundInfo;
// update events
copiedExtensionState.events.push({
name: ExtensionTypes.PnAnyDeclarative.ACTION.ADD_REFUND_INSTRUCTION,
parameters: {
refundInfo: extensionAction.parameters.refundInfo,
},
timestamp,
from: actionSigner,
});
return copiedExtensionState;
}
/** Checks if signer is the right identity from the request and the role expected
*
* @param extensionsState previous state of the extensions
* @param requestState request state read-only
* @param actionSigner identity of the signer
* @param role The role to check (Payee or Payer)
*
* @returns throws in case of error
*/
protected checkIdentities(
extensionState: ExtensionTypes.IState,
requestState: RequestLogicTypes.IRequest,
actionSigner: IdentityTypes.IIdentity,
role: RequestLogicTypes.ROLE,
): void {
let requestRole;
let requestRoleStr;
let requestRoleDelegate;
if (role === RequestLogicTypes.ROLE.PAYER) {
requestRole = requestState.payer;
requestRoleStr = 'payer';
requestRoleDelegate = extensionState.values.payerDelegate;
}
if (role === RequestLogicTypes.ROLE.PAYEE) {
requestRole = requestState.payee;
requestRoleStr = 'payee';
requestRoleDelegate = extensionState.values.payeeDelegate;
}
if (!requestRole) {
throw Error(`The request must have a ${requestRoleStr}`);
}
if (
!Utils.identity.areEqual(actionSigner, requestRole) &&
!Utils.identity.areEqual(actionSigner, requestRoleDelegate)
) {
throw Error(`The signer must be the ${requestRoleStr} or the ${requestRoleStr}Delegate`);
}
}
} | the_stack |
import * as cdk from '@aws-cdk/core';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as ecs from '@aws-cdk/aws-ecs';
import * as logs from '@aws-cdk/aws-logs';
import * as elbv2 from '@aws-cdk/aws-elasticloadbalancingv2';
import * as ecr_assets from '@aws-cdk/aws-ecr-assets';
import * as path from 'path';
import * as ssm from '@aws-cdk/aws-ssm';
import * as iam from '@aws-cdk/aws-iam';
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
import * as events from '@aws-cdk/aws-events';
import * as targets from '@aws-cdk/aws-events-targets';
import { ITopic } from '@aws-cdk/aws-sns';
export interface ContentServerProps extends cdk.NestedStackProps {
readonly vpc: ec2.IVpc;
readonly fileSystemId: string;
readonly notifyTopic: ITopic;
readonly ecsCluster: ecs.Cluster;
readonly listener: elbv2.ApplicationListener;
readonly httpOnlyListener?: elbv2.ApplicationListener;
readonly dashboard: cloudwatch.Dashboard;
}
export class ContentServerStack extends cdk.NestedStack {
constructor(scope: cdk.Construct, id: string, props: ContentServerProps) {
super(scope, id, props);
const usage = 'ContentServer';
const imageAsset = new ecr_assets.DockerImageAsset(this, `${usage}DockerImage`, {
directory: path.join(__dirname, '../content-server'),
repositoryName: "opentuna/content-server"
});
const param = new ssm.StringParameter(this, 'CloudWatchConfigStringParameter', {
description: 'Parameter for CloudWatch agent',
parameterName: 'CloudWatchConfig',
stringValue: JSON.stringify(
{
"metrics": {
"namespace": "OpenTuna",
"metrics_collected": {
"cpu": {
"measurement": ["usage_idle", "usage_iowait", "usage_system", "usage_user"],
},
"net": {
"measurement": ["bytes_sent", "bytes_recv", "packets_sent", "packets_recv"],
},
"netstat": {
"measurement": ["tcp_established", "tcp_syn_sent", "tcp_close"],
}
}
},
"logs": {
"metrics_collected": {
"emf": {}
}
}
}
),
});
const httpPort = 80;
const taskDefinition = new ecs.FargateTaskDefinition(this, `${usage}TaskDefiniton`, {
volumes: [{
name: "efs-volume",
efsVolumeConfiguration: {
fileSystemId: props.fileSystemId,
rootDirectory: "/data",
},
}]
});
const logGroup = new logs.LogGroup(this, `${usage}LogGroup`, {
logGroupName: `/opentuna/contentserver`,
removalPolicy: cdk.RemovalPolicy.DESTROY
});
const container = taskDefinition.addContainer("content-server", {
image: ecs.ContainerImage.fromDockerImageAsset(imageAsset),
logging: new ecs.AwsLogDriver({
streamPrefix: usage,
// like [16/Jul/2020:02:24:46 +0000]
datetimeFormat: "\\[%d/%b/%Y:%H:%M:%S %z\\]",
logGroup,
}),
});
container.addMountPoints({
readOnly: true,
containerPath: "/mnt/efs",
sourceVolume: "efs-volume"
});
container.addPortMappings({
containerPort: httpPort,
});
// cloudwatch agent
const cloudWatchAgentlogGroup = new logs.LogGroup(this, `${usage}CloudWatchAgentLogGroup`, {
logGroupName: `/opentuna/${usage}/cloudwatch-agent`,
removalPolicy: cdk.RemovalPolicy.DESTROY
});
const cloudWatchAgent = taskDefinition.addContainer("cloudwatch-agent", {
image: ecs.ContainerImage.fromRegistry('amazon/cloudwatch-agent:latest'),
logging: new ecs.AwsLogDriver({
streamPrefix: usage,
logGroup: cloudWatchAgentlogGroup,
}),
essential: false,
secrets: {
"CW_CONFIG_CONTENT": ecs.Secret.fromSsmParameter(param),
}
});
const service = new ecs.FargateService(this, `${usage}Fargate`, {
cluster: props.ecsCluster,
desiredCount: 1,
platformVersion: ecs.FargatePlatformVersion.VERSION1_4,
taskDefinition,
});
// setup cloudwatch agent permissions
// allow execution role to read ssm parameter
param.grantRead(service.taskDefinition.executionRole!);
service.taskDefinition.executionRole!.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('CloudWatchAgentServerPolicy'));
service.taskDefinition.taskRole.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('CloudWatchAgentServerPolicy'));
const targetGroup = props.listener.addTargets('ContentServer', {
port: httpPort,
protocol: elbv2.ApplicationProtocol.HTTP,
targets: [service],
healthCheck: {
enabled: true,
timeout: cdk.Duration.seconds(15),
},
});
// allow /debian, /debian-security and /ubuntu to be accessed by HTTP, bypassing HTTPS redirection
if (props.httpOnlyListener) {
props.httpOnlyListener.addTargets('ContentServer', {
port: httpPort,
protocol: elbv2.ApplicationProtocol.HTTP,
targets: [service],
pathPatterns: [
'/debian/*',
'/debian-security/*',
'/ubuntu/*',
],
priority: 20,
healthCheck: {
enabled: true,
timeout: cdk.Duration.seconds(15),
},
});
}
// auto scaling
const scaling = service.autoScaleTaskCount({
minCapacity: 1,
maxCapacity: 16
});
const bytesSentEth1 = new cloudwatch.Metric({
namespace: 'OpenTuna',
metricName: 'net_bytes_sent',
dimensions: {
interface: "eth1"
},
statistic: cloudwatch.Statistic.AVERAGE,
});
// each task instance has about 500Mbps bandwidth
// 500Mbps * 60s/min / 8b/B = 3750MB/min
// must use direct metric because of api limitation
// so only eth1 is used
scaling.scaleToTrackCustomMetric('NetworkBandwidthScaling', {
metric: bytesSentEth1,
targetValue: 3 * 1024 * 1024 * 1024, // 3GiB/min
scaleInCooldown: cdk.Duration.minutes(10),
scaleOutCooldown: cdk.Duration.minutes(3),
});
const cpuUsage = {
namespace: 'OpenTuna',
dimensions: {
cpu: "cpu-total"
},
statistic: cloudwatch.Statistic.AVERAGE,
period: cdk.Duration.minutes(1),
};
const cpuUsageIowait = new cloudwatch.Metric({
metricName: 'cpu_usage_iowait',
...cpuUsage
});
// peak iowait% is around 40%
scaling.scaleToTrackCustomMetric('CpuIowaitScaling', {
metric: cpuUsageIowait,
targetValue: 25,
scaleInCooldown: cdk.Duration.minutes(10),
scaleOutCooldown: cdk.Duration.minutes(3),
});
// Add widget for content server
const bytesEth1 = {
namespace: 'OpenTuna',
dimensions: {
interface: "eth1"
},
statistic: cloudwatch.Statistic.SUM,
period: cdk.Duration.minutes(1),
};
props.dashboard.addWidgets(new cloudwatch.GraphWidget({
title: 'Content Server Bandwidth',
left: [
new cloudwatch.Metric({
metricName: 'net_bytes_sent',
label: 'Sent B/min',
...bytesEth1
}),
new cloudwatch.Metric({
metricName: 'net_bytes_recv',
label: 'Recv B/min',
...bytesEth1
})
]
}), new cloudwatch.GraphWidget({
title: 'Content Server Packets',
left: [
new cloudwatch.Metric({
metricName: 'net_packets_sent',
label: 'Sent p/min',
...bytesEth1
}),
new cloudwatch.Metric({
metricName: 'net_packets_recv',
label: 'Recv p/min',
...bytesEth1
})
]
}), new cloudwatch.GraphWidget({
title: 'Content Server Cpu',
left: [
new cloudwatch.Metric({
metricName: 'cpu_usage_iowait',
label: 'iowait%',
...cpuUsage
}),
new cloudwatch.Metric({
metricName: 'cpu_usage_idle',
label: 'idle%',
...cpuUsage
}),
new cloudwatch.Metric({
metricName: 'cpu_usage_user',
label: 'user%',
...cpuUsage
}),
new cloudwatch.Metric({
metricName: 'cpu_usage_system',
label: 'system%',
...cpuUsage
}),
]
}), new cloudwatch.GraphWidget({
title: 'Content Server Task Count',
left: [service.metricCpuUtilization({
statistic: cloudwatch.Statistic.SAMPLE_COUNT,
period: cdk.Duration.minutes(1),
label: 'Task Count'
})]
}));
// Monitor auto scaling event
const rule = new events.Rule(this, 'AutoScaleRule', {
description: 'Monitor content server auto scaling',
eventPattern: {
source: ["aws.application-autoscaling"],
},
targets: [new targets.SnsTopic(props.notifyTopic, {
message: events.RuleTargetInput.fromText(`Service ${events.EventField.fromPath('$.detail.resourceId')} is scaled from ${events.EventField.fromPath('$.detail.oldDesiredCapacity')} to ${events.EventField.fromPath('$.detail.newDesiredCapacity')}`),
})]
});
cdk.Tags.of(this).add('component', usage);
}
} | the_stack |
import type { Server } from "http";
import type { Server as SecureServer } from "https";
import { Optional } from "typescript-optional";
import type { Express } from "express";
import { v4 as uuidV4 } from "uuid";
import knex, { Knex } from "knex";
import OAS from "../../json/openapi.json";
import {
Secp256k1Keys,
Logger,
Checks,
LoggerProvider,
JsObjectSigner,
IJsObjectSignerOptions,
} from "@hyperledger/cactus-common";
import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs";
import {
checkValidInitializationRequest,
sendTransferInitializationResponse,
} from "./server/transfer-initialization";
import {
ICactusPlugin,
IPluginWebService,
IWebServiceEndpoint,
Configuration,
} from "@hyperledger/cactus-core-api";
import {
TransferInitializationV1Response,
DefaultApi as OdapApi,
SessionData,
ClientV1Request,
TransferCommenceV1Request,
TransferCommenceV1Response,
LockEvidenceV1Request,
LockEvidenceV1Response,
CommitPreparationV1Request,
CommitFinalV1Request,
CommitPreparationV1Response,
CommitFinalV1Response,
TransferCompleteV1Request,
TransferInitializationV1Request,
OdapLocalLog,
RecoverV1Message,
RecoverUpdateV1Message,
RecoverUpdateAckV1Message,
RollbackV1Message,
SessionDataRollbackActionsPerformedEnum,
RollbackAckV1Message,
} from "../generated/openapi/typescript-axios";
import { CommitFinalRequestEndpointV1 } from "../web-services/server-side/commit-final-request-endpoint";
import { PluginRegistry } from "@hyperledger/cactus-core";
import {
DefaultApi as FabricApi,
FabricContractInvocationType,
FabricSigningCredential,
RunTransactionRequest as FabricRunTransactionRequest,
} from "@hyperledger/cactus-plugin-ledger-connector-fabric";
import {
DefaultApi as BesuApi,
Web3SigningCredential,
EthContractInvocationType,
InvokeContractV1Request as BesuInvokeContractV1Request,
} from "@hyperledger/cactus-plugin-ledger-connector-besu";
import { CommitFinalResponseEndpointV1 } from "../web-services/client-side/commit-final-response-endpoint";
import { CommitPreparationResponseEndpointV1 } from "../web-services/client-side/commite-prepare-response-endpoint";
import { LockEvidenceResponseEndpointV1 } from "../web-services/client-side/lock-evidence-response-endpoint";
import { TransferCommenceResponseEndpointV1 } from "../web-services/client-side/transfer-commence-response-endpoint";
import { TransferInitiationResponseEndpointV1 } from "../web-services/client-side/transfer-initiation-response-endpoint";
import { LockEvidenceRequestEndpointV1 } from "../web-services/server-side/lock-evidence-request-endpoint";
import { TransferCommenceRequestEndpointV1 } from "../web-services/server-side/transfer-commence-request-endpoint";
import { TransferCompleteRequestEndpointV1 } from "../web-services/server-side/transfer-complete-request-endpoint";
import { TransferInitiationRequestEndpointV1 } from "../web-services/server-side/transfer-initiation-request-endpoint";
import { CommitPreparationRequestEndpointV1 } from "../web-services/server-side/commite-prepare-request-endpoint";
import { randomInt } from "crypto";
import {
checkValidInitializationResponse,
sendTransferInitializationRequest,
} from "./client/transfer-initialization";
import { ClientRequestEndpointV1 } from "../web-services/client-side/client-request-endpoint";
import {
checkValidTransferCommenceResponse,
sendTransferCommenceRequest,
} from "./client/transfer-commence";
import {
checkValidtransferCommenceRequest,
sendTransferCommenceResponse,
} from "./server/transfer-commence";
import {
checkValidLockEvidenceResponse,
sendLockEvidenceRequest,
} from "./client/lock-evidence";
import {
checkValidLockEvidenceRequest,
sendLockEvidenceResponse,
} from "./server/lock-evidence";
import {
checkValidCommitFinalResponse,
sendCommitFinalRequest,
} from "./client/commit-final";
import {
checkValidCommitPreparationResponse,
sendCommitPreparationRequest,
} from "./client/commit-preparation";
import {
checkValidCommitFinalRequest,
sendCommitFinalResponse,
} from "./server/commit-final";
import { sendTransferCompleteRequest } from "./client/transfer-complete";
import { checkValidTransferCompleteRequest } from "./server/transfer-complete";
import {
checkValidCommitPreparationRequest,
sendCommitPreparationResponse,
} from "./server/commit-preparation";
import {
checkValidRecoverMessage,
sendRecoverMessage,
} from "./recovery/recover";
import {
checkValidRecoverUpdateMessage,
sendRecoverUpdateMessage,
} from "./recovery/recover-update";
import {
checkValidRecoverUpdateAckMessage,
sendRecoverUpdateAckMessage,
} from "./recovery/recover-update-ack";
import {
checkValidRecoverSuccessMessage,
sendRecoverSuccessMessage,
} from "./recovery/recover-success";
import { SHA256 } from "crypto-js";
import { RecoverMessageEndpointV1 } from "../web-services/recovery/recover-message-endpoint";
import { RecoverUpdateMessageEndpointV1 } from "../web-services/recovery/recover-update-message-endpoint";
import { RecoverUpdateAckMessageEndpointV1 } from "../web-services/recovery/recover-update-ack-message-endpoint";
import { RecoverSuccessMessageEndpointV1 } from "../web-services/recovery/recover-success-message-endpoint";
import { RollbackMessageEndpointV1 } from "../web-services/recovery/rollback-message-endpoint";
import {
checkValidRollbackMessage,
sendRollbackMessage,
} from "./recovery/rollback";
import {
besuAssetExists,
fabricAssetExists,
isFabricAssetLocked,
} from "../../../test/typescript/make-checks-ledgers";
import { AxiosResponse } from "axios";
import {
checkValidRollbackAckMessage,
sendRollbackAckMessage,
} from "./recovery/rollback-ack";
export enum OdapMessageType {
InitializationRequest = "urn:ietf:odap:msgtype:init-transfer-msg",
InitializationResponse = "urn:ietf:odap:msgtype:init-transfer-ack-msg",
TransferCommenceRequest = "urn:ietf:odap:msgtype:transfer-commence-msg",
TransferCommenceResponse = "urn:ietf:odap:msgtype:transfer-commence-ack-msg",
LockEvidenceRequest = "urn:ietf:odap:msgtype:lock-evidence-req-msg",
LockEvidenceResponse = "urn:ietf:odap:msgtype:lock-evidence-ack-msg",
CommitPreparationRequest = "urn:ietf:odap:msgtype:commit-prepare-msg",
CommitPreparationResponse = "urn:ietf:odap:msgtype:commit-ack-msg",
CommitFinalRequest = "urn:ietf:odap:msgtype:commit-final-msg",
CommitFinalResponse = "urn:ietf:odap:msgtype:commit-ack-msg",
TransferCompleteRequest = "urn:ietf:odap:msgtype:commit-transfer-complete-msg",
}
export interface IPluginOdapGatewayConstructorOptions {
name: string;
dltIDs: string[];
instanceId: string;
keyPair?: IOdapGatewayKeyPairs;
backupGatewaysAllowed?: string[];
ipfsPath?: string;
fabricPath?: string;
besuPath?: string;
fabricSigningCredential?: FabricSigningCredential;
fabricChannelName?: string;
fabricContractName?: string;
besuContractName?: string;
besuWeb3SigningCredential?: Web3SigningCredential;
besuKeychainId?: string;
fabricAssetID?: string;
fabricAssetSize?: string;
besuAssetID?: string;
knexConfig?: Knex.Config;
}
export interface IOdapGatewayKeyPairs {
publicKey: Uint8Array;
privateKey: Uint8Array;
}
export interface IOdapLogIPFS {
key: string;
hash: string;
signature: string;
signerPubKey: string;
}
export class PluginOdapGateway implements ICactusPlugin, IPluginWebService {
name: string;
sessions: Map<string, SessionData>;
pubKey: string;
privKey: string;
public static readonly CLASS_NAME = "OdapGateway";
private readonly log: Logger;
private readonly instanceId: string;
public ipfsApi?: ObjectStoreIpfsApi;
public fabricApi?: FabricApi;
public besuApi?: BesuApi;
public pluginRegistry: PluginRegistry;
public database?: Knex;
private endpoints: IWebServiceEndpoint[] | undefined;
//map[]object, object refer to a state
//of a specific comminications
public supportedDltIDs: string[];
public backupGatewaysAllowed: string[];
private odapSigner: JsObjectSigner;
public fabricAssetLocked: boolean;
public fabricAssetDeleted: boolean;
public fabricAssetSize?: string;
public besuAssetCreated: boolean;
public fabricSigningCredential?: FabricSigningCredential;
public fabricChannelName?: string;
public fabricContractName?: string;
public besuContractName?: string;
public besuWeb3SigningCredential?: Web3SigningCredential;
public besuKeychainId?: string;
public fabricAssetID?: string;
public besuAssetID?: string;
public constructor(options: IPluginOdapGatewayConstructorOptions) {
const fnTag = `${this.className}#constructor()`;
Checks.truthy(options, `${fnTag} arg options`);
Checks.truthy(options.instanceId, `${fnTag} arg options.instanceId`);
Checks.nonBlankString(options.instanceId, `${fnTag} options.instanceId`);
const level = "INFO";
const label = this.className;
this.log = LoggerProvider.getOrCreate({ level, label });
this.instanceId = options.instanceId;
this.name = options.name;
this.supportedDltIDs = options.dltIDs;
this.sessions = new Map();
this.backupGatewaysAllowed = options.backupGatewaysAllowed || [];
const keyPairs = options.keyPair
? options.keyPair
: Secp256k1Keys.generateKeyPairsBuffer();
this.pubKey = PluginOdapGateway.bufArray2HexStr(keyPairs.publicKey);
this.privKey = PluginOdapGateway.bufArray2HexStr(keyPairs.privateKey);
const odapSignerOptions: IJsObjectSignerOptions = {
privateKey: this.privKey,
logLevel: "debug",
};
this.odapSigner = new JsObjectSigner(odapSignerOptions);
this.fabricAssetDeleted = false;
this.fabricAssetLocked = false;
this.besuAssetCreated = false;
this.pluginRegistry = new PluginRegistry();
if (options.ipfsPath != undefined) this.defineIpfsConnection(options);
if (options.fabricPath != undefined) this.defineFabricConnection(options);
if (options.besuPath != undefined) this.defineBesuConnection(options);
this.defineKnexConnection(options.knexConfig);
}
public defineKnexConnection(knexConfig?: Knex.Config): void {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const config = require("../../../../knex/knexfile.ts")[
process.env.ENVIRONMENT || "development"
];
this.database = knex(knexConfig || config);
}
private defineIpfsConnection(
options: IPluginOdapGatewayConstructorOptions,
): void {
const config = new Configuration({ basePath: options.ipfsPath });
const apiClient = new ObjectStoreIpfsApi(config);
this.ipfsApi = apiClient;
}
private defineFabricConnection(
options: IPluginOdapGatewayConstructorOptions,
): void {
const fnTag = `${this.className}#defineFabricConnection()`;
const config = new Configuration({ basePath: options.fabricPath });
const apiClient = new FabricApi(config);
this.fabricApi = apiClient;
const notEnoughFabricParams: boolean =
options.fabricSigningCredential == undefined ||
options.fabricChannelName == undefined ||
options.fabricContractName == undefined ||
options.fabricAssetID == undefined;
if (notEnoughFabricParams) {
throw new Error(
`${fnTag}, fabric params missing should have: signing credentials, contract name, channel name, asset ID`,
);
}
this.fabricSigningCredential = options.fabricSigningCredential;
this.fabricChannelName = options.fabricChannelName;
this.fabricContractName = options.fabricContractName;
this.fabricAssetID = options.fabricAssetID;
this.fabricAssetSize = options.fabricAssetSize
? options.fabricAssetSize
: "1";
}
private defineBesuConnection(
options: IPluginOdapGatewayConstructorOptions,
): void {
const fnTag = `${this.className}#defineBesuConnection()`;
const config = new Configuration({ basePath: options.besuPath });
const apiClient = new BesuApi(config);
this.besuApi = apiClient;
const notEnoughBesuParams: boolean =
options.besuContractName == undefined ||
options.besuWeb3SigningCredential == undefined ||
options.besuKeychainId == undefined ||
options.besuAssetID == undefined;
if (notEnoughBesuParams) {
throw new Error(
`${fnTag}, besu params missing. Should have: signing credentials, contract name, key chain ID, asset ID`,
);
}
this.besuContractName = options.besuContractName;
this.besuWeb3SigningCredential = options.besuWeb3SigningCredential;
this.besuKeychainId = options.besuKeychainId;
this.besuAssetID = options.besuAssetID;
}
public get className(): string {
return PluginOdapGateway.CLASS_NAME;
}
public getOpenApiSpec(): unknown {
return OAS;
}
/*public getAspect(): PluginAspect {
return PluginAspect.WEB_SERVICE;
}*/
public async onPluginInit(): Promise<unknown> {
return;
}
async registerWebServices(app: Express): Promise<IWebServiceEndpoint[]> {
const webServices = await this.getOrCreateWebServices();
await Promise.all(webServices.map((ws) => ws.registerExpress(app)));
return webServices;
}
public async getOrCreateWebServices(): Promise<IWebServiceEndpoint[]> {
if (Array.isArray(this.endpoints)) {
return this.endpoints;
}
// Server endpoints
const transferInitiationRequestEndpoint = new TransferInitiationRequestEndpointV1(
{
gateway: this,
},
);
const transferCommenceRequestEndpoint = new TransferCommenceRequestEndpointV1(
{
gateway: this,
},
);
const lockEvidenceRequestEndpoint = new LockEvidenceRequestEndpointV1({
gateway: this,
});
const commitPreparationRequestEndpoint = new CommitPreparationRequestEndpointV1(
{
gateway: this,
},
);
const commitFinalRequestEndpoint = new CommitFinalRequestEndpointV1({
gateway: this,
});
const transferCompleteRequestEndpoint = new TransferCompleteRequestEndpointV1(
{
gateway: this,
},
);
// Client endpoints
const clientRequestEndpoint = new ClientRequestEndpointV1({
gateway: this,
});
const transferInitiationResponseEndpoint = new TransferInitiationResponseEndpointV1(
{
gateway: this,
},
);
const transferCommenceResponseEndpoint = new TransferCommenceResponseEndpointV1(
{
gateway: this,
},
);
const lockEvidenceResponseEndpoint = new LockEvidenceResponseEndpointV1({
gateway: this,
});
const commitPreparationResponseEndpoint = new CommitPreparationResponseEndpointV1(
{
gateway: this,
},
);
const commitFinalResponseEndpoint = new CommitFinalResponseEndpointV1({
gateway: this,
});
// Recovery endpoints
const recoverEndpoint = new RecoverMessageEndpointV1({
gateway: this,
});
const recoverUpdateEndpoint = new RecoverUpdateMessageEndpointV1({
gateway: this,
});
const recoverUpdateAckEndpoint = new RecoverUpdateAckMessageEndpointV1({
gateway: this,
});
const recoverSuccessEndpoint = new RecoverSuccessMessageEndpointV1({
gateway: this,
});
const rollbackEndpoint = new RollbackMessageEndpointV1({
gateway: this,
});
this.endpoints = [
transferInitiationRequestEndpoint,
transferCommenceRequestEndpoint,
lockEvidenceRequestEndpoint,
commitPreparationRequestEndpoint,
commitFinalRequestEndpoint,
transferCompleteRequestEndpoint,
clientRequestEndpoint,
transferInitiationResponseEndpoint,
transferCommenceResponseEndpoint,
lockEvidenceResponseEndpoint,
commitPreparationResponseEndpoint,
commitFinalResponseEndpoint,
recoverEndpoint,
recoverUpdateEndpoint,
recoverUpdateAckEndpoint,
recoverSuccessEndpoint,
rollbackEndpoint,
];
return this.endpoints;
}
public getHttpServer(): Optional<Server | SecureServer> {
return Optional.empty();
}
public async shutdown(): Promise<void> {
this.log.info(`Shutting down ${this.className}...`);
}
public getInstanceId(): string {
return this.instanceId;
}
public getPackageName(): string {
return "@hyperledger/cactus-odap-gateway-business-logic-plugin";
}
getDatabaseInstance(): Knex.QueryBuilder {
const fnTag = `${this.className}#getDatabaseInstance()`;
if (this.database == undefined) {
throw new Error(`${fnTag}, database is undefined`);
}
return this.database("logs");
}
isClientGateway(sessionID: string): boolean {
const fnTag = `${this.className}#isClientGateway()`;
const sessionData = this.sessions.get(sessionID);
if (sessionData == undefined) {
throw new Error(`${fnTag}, session data is undefined`);
}
return sessionData.sourceGatewayPubkey == this.pubKey;
}
sign(msg: string): Uint8Array {
return this.odapSigner.sign(msg);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
verifySignature(obj: any, pubKey: string): boolean {
const sourceSignature = new Uint8Array(Buffer.from(obj.signature, "hex"));
const sourcePubkey = new Uint8Array(Buffer.from(pubKey, "hex"));
const signature = obj.signature;
obj.signature = "";
if (
!this.odapSigner.verify(
JSON.stringify(obj),
sourceSignature,
sourcePubkey,
)
) {
return false;
}
obj.signature = signature;
return true;
}
static bufArray2HexStr(array: Uint8Array): string {
return Buffer.from(array).toString("hex");
}
static getOdapLogKey(
sessionID: string,
type: string,
operation: string,
): string {
return `${sessionID}-${type}-${operation}`;
}
async recoverOpenSessions(remote: boolean) {
const fnTag = `${this.className}#recoverOpenSessions()`;
this.log.info(`${fnTag}, recovering open sessions...`);
if (this.database == undefined) {
throw new Error(`${fnTag}, database is undefined`);
}
const logs: OdapLocalLog[] = await this.getDatabaseInstance()
.select(
this.database.raw(
"sessionId, key, data, type, operation, MAX(timestamp) as timestamp",
),
)
.whereNot({ type: "proof" })
.groupBy("sessionID");
for (const log of logs) {
const sessionID = log.sessionID;
this.log.info(`${fnTag}, recovering session ${sessionID}...`);
if (log == undefined || log.data == undefined) {
throw new Error(`${fnTag}, invalid log}`);
}
const sessionData: SessionData = JSON.parse(log.data);
sessionData.lastLogEntryTimestamp = log.timestamp;
let amIBackup = false;
if (
this.pubKey != sessionData.sourceGatewayPubkey &&
this.pubKey != sessionData.recipientGatewayPubkey
) {
// this is a backup gateway -> for now we assume backup gateways only on the client side
sessionData.sourceGatewayPubkey = this.pubKey;
amIBackup = true;
}
this.sessions.set(sessionID, sessionData);
if (remote) await sendRecoverMessage(sessionID, this, amIBackup, true);
}
}
async storeInDatabase(odapLocalLog: OdapLocalLog) {
const fnTag = `${this.className}#storeInDatabase()`;
this.log.info(
`${fnTag}, Storing locally log: ${JSON.stringify(odapLocalLog)}`,
);
await this.getDatabaseInstance().insert(odapLocalLog);
}
async storeInIPFS(key: string, hash: string) {
const fnTag = `${this.className}#storeInIPFS()`;
if (this.ipfsApi == undefined) return;
const ipfsLog: IOdapLogIPFS = {
key: key,
hash: hash,
signature: "",
signerPubKey: this.pubKey,
};
ipfsLog.signature = PluginOdapGateway.bufArray2HexStr(
await this.sign(JSON.stringify(ipfsLog)),
);
const logBase64 = Buffer.from(JSON.stringify(ipfsLog)).toString("base64");
this.log.info(`${fnTag}, Storing in ipfs log: ${JSON.stringify(ipfsLog)}`);
const response = await this.ipfsApi.setObjectV1({
key: key,
value: logBase64,
});
if (response.status < 200 && response.status > 299) {
throw new Error(`${fnTag}, error when logging to ipfs`);
}
}
async storeOdapLog(odapLocalLog: OdapLocalLog): Promise<void> {
if (this.ipfsApi == undefined) return;
odapLocalLog.key = PluginOdapGateway.getOdapLogKey(
odapLocalLog.sessionID,
odapLocalLog.type,
odapLocalLog.operation,
);
odapLocalLog.timestamp = Date.now().toString();
await this.storeInDatabase(odapLocalLog);
// Keep the order consistent with the order of the fields in the table
// so that the hash matches when retrieving from the database
const hash = SHA256(
JSON.stringify(odapLocalLog, [
"sessionID",
"type",
"key",
"operation",
"timestamp",
"data",
]),
).toString();
await this.storeInIPFS(odapLocalLog.key, hash);
}
async storeOdapProof(odapLocalLog: OdapLocalLog): Promise<void> {
if (this.ipfsApi == undefined || odapLocalLog.data == undefined) return;
odapLocalLog.key = PluginOdapGateway.getOdapLogKey(
odapLocalLog.sessionID,
odapLocalLog.type,
odapLocalLog.operation,
);
odapLocalLog.timestamp = Date.now().toString();
await this.storeInDatabase(odapLocalLog);
const hash = SHA256(odapLocalLog.data).toString();
await this.storeInIPFS(odapLocalLog.key, hash);
}
async getLogFromDatabase(logKey: string): Promise<OdapLocalLog | undefined> {
const fnTag = `${this.className}#getLogFromDatabase()`;
this.log.info(`${fnTag}, retrieving log with key ${logKey}`);
return await this.getDatabaseInstance()
.where({ key: logKey })
.first()
.then((row) => {
this.log.info(`${fnTag}, retrieved log ${JSON.stringify(row)}`);
return row;
});
}
async getLastLogFromDatabase(
sessionID: string,
): Promise<OdapLocalLog | undefined> {
const fnTag = `${this.className}#getLastLog()`;
this.log.info(`${fnTag}, retrieving last log from sessionID ${sessionID}`);
return await this.getDatabaseInstance()
.orderBy("timestamp", "desc")
.where({ sessionID: sessionID })
.first()
.then((row) => {
this.log.info(`${fnTag}, retrieved log ${JSON.stringify(row)}`);
return row;
});
}
async getLogsMoreRecentThanTimestamp(
timestamp: string,
): Promise<OdapLocalLog[]> {
const fnTag = `${this.className}#getLogsMoreRecentThanTimestamp()`;
this.log.info(`${fnTag}, retrieving logs more recent than ${timestamp}`);
const logs: OdapLocalLog[] = await this.getDatabaseInstance()
.where("timestamp", ">", timestamp)
.whereNot("type", "like", "%proof%");
if (logs == undefined) {
throw new Error(`${fnTag}, error when retrieving log from database`);
}
this.log.info(`${fnTag}, there are ${logs.length} more recent logs`);
return logs;
}
async getLogFromIPFS(logKey: string): Promise<IOdapLogIPFS> {
const fnTag = `${this.className}#getOdapLogFromIPFS()`;
this.log.info(`Retrieving log with key: <${logKey}>`);
if (this.ipfsApi == undefined) {
throw new Error(`${fnTag}, ipfs is not defined`);
}
const response = await this.ipfsApi.getObjectV1({
key: logKey,
});
if (response.status < 200 && response.status > 299) {
throw new Error(`${fnTag}, error when logging to ipfs`);
}
const log: IOdapLogIPFS = JSON.parse(
Buffer.from(response.data.value, "base64").toString(),
);
if (log == undefined || log.signature == undefined) {
throw new Error(`${fnTag}, the log or its signature is not defined`);
}
if (!this.verifySignature(log, log.signerPubKey)) {
throw new Error(`${fnTag}, received log with invalid signature`);
}
return log;
}
static getOdapAPI(basePath: string): OdapApi {
const odapServerApiConfig = new Configuration({
basePath: basePath,
});
return new OdapApi(odapServerApiConfig);
}
async deleteDatabaseEntries(sessionID: string) {
this.log.info(
`deleting logs from database associated with sessionID: ${sessionID}`,
);
await this.getDatabaseInstance().where({ sessionID: sessionID }).del();
}
async resumeOdapSession(sessionID: string, remote: boolean) {
const fnTag = `${this.className}#continueOdapSession()`;
const sessionData = this.sessions.get(sessionID);
if (
sessionData == undefined ||
sessionData.step == undefined ||
sessionData.lastSequenceNumber == undefined
) {
throw new Error(`${fnTag}, session data is undefined`);
}
// if the other gateway made the rollback, we will do it as well
if (sessionData.rollback) {
await this.rollback(sessionID);
await sendRollbackAckMessage(sessionID, this, true);
return;
}
this.log.info(
`${fnTag}, recovering session ${sessionID} that was in step ${sessionData.step}`,
);
// If step is even then the last log was inserted by the server
// so we need to increase the step
if (this.isClientGateway(sessionID) && sessionData.step % 2 == 0) {
sessionData.step++;
}
this.sessions.set(sessionID, sessionData);
switch (sessionData.step) {
case 1:
return await sendTransferInitializationRequest(sessionID, this, remote);
case 2:
return await sendTransferInitializationResponse(
sessionID,
this,
remote,
);
case 3:
return await sendTransferCommenceRequest(sessionID, this, remote);
case 4:
return await sendTransferCommenceResponse(sessionID, this, remote);
case 5:
return await sendLockEvidenceRequest(sessionID, this, remote);
case 6:
return await sendLockEvidenceResponse(sessionID, this, remote);
case 7:
return await sendCommitPreparationRequest(sessionID, this, remote);
case 8:
return await sendCommitPreparationResponse(sessionID, this, remote);
case 9:
return await sendCommitFinalRequest(sessionID, this, remote);
case 10:
return await sendCommitFinalResponse(sessionID, this, remote);
case 11:
return await sendTransferCompleteRequest(sessionID, this, remote);
default:
this.sessions.delete(sessionID);
throw new Error(
`${fnTag}, invalid session data step. A new session should be initiated by the client gateway.`,
);
}
}
private updateLastMessageReceivedTimestamp(sessionID: string) {
const fnTag = `${this.className}#updateLastMessageReceivedTimestamp()`;
const sessionData = this.sessions.get(sessionID);
if (sessionData == undefined) {
throw new Error(`${fnTag}, session data is not correctly initialized`);
}
sessionData.lastMessageReceivedTimestamp = new Date().toString();
this.sessions.set(sessionID, sessionData);
}
//Server-side
async onTransferInitiationRequestReceived(
request: TransferInitializationV1Request,
): Promise<void> {
const fnTag = `${this.className}#onTransferInitiationRequestReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`server gateway received TransferInitializationRequest: ${JSON.stringify(
request,
)}`,
);
await checkValidInitializationRequest(request, this);
await sendTransferInitializationResponse(request.sessionID, this, true);
}
async onTransferCommenceRequestReceived(
request: TransferCommenceV1Request,
): Promise<void> {
const fnTag = `${this.className}#onTransferCommenceRequestReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`server gateway received TransferCommenceRequest: ${JSON.stringify(
request,
)}`,
);
this.updateLastMessageReceivedTimestamp(request.sessionID);
await checkValidtransferCommenceRequest(request, this);
await sendTransferCommenceResponse(request.sessionID, this, true);
}
async onLockEvidenceRequestReceived(
request: LockEvidenceV1Request,
): Promise<void> {
const fnTag = `${this.className}#onLockEvidenceRequestReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`server gateway received LockEvidenceRequest: ${JSON.stringify(request)}`,
);
this.updateLastMessageReceivedTimestamp(request.sessionID);
await checkValidLockEvidenceRequest(request, this);
await sendLockEvidenceResponse(request.sessionID, this, true);
}
async onCommitPrepareRequestReceived(
request: CommitPreparationV1Request,
): Promise<void> {
const fnTag = `${this.className}#onCommitPrepareRequestReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`server gateway received CommitPrepareRequest: ${JSON.stringify(
request,
)}`,
);
this.updateLastMessageReceivedTimestamp(request.sessionID);
await checkValidCommitPreparationRequest(request, this);
await sendCommitPreparationResponse(request.sessionID, this, true);
}
async onCommitFinalRequestReceived(
request: CommitFinalV1Request,
): Promise<void> {
const fnTag = `${this.className}#onCommitFinalRequestReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`server gateway received CommitFinalRequest: ${JSON.stringify(request)}`,
);
this.updateLastMessageReceivedTimestamp(request.sessionID);
await checkValidCommitFinalRequest(request, this);
await this.createBesuAsset(request.sessionID);
await sendCommitFinalResponse(request.sessionID, this, true);
}
async onTransferCompleteRequestReceived(
request: TransferCompleteV1Request,
): Promise<void> {
const fnTag = `${this.className}#onTransferCompleteRequestReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`server gateway received TransferCompleteRequest: ${JSON.stringify(
request,
)}`,
);
this.updateLastMessageReceivedTimestamp(request.sessionID);
await checkValidTransferCompleteRequest(request, this);
//this.deleteDatabaseEntries(request.sessionID);
}
//Client-side
async onTransferInitiationResponseReceived(
request: TransferInitializationV1Response,
): Promise<void> {
const fnTag = `${this.className}#onTransferInitiationResponseReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`client gateway received TransferInitiationResponse: ${JSON.stringify(
request,
)}`,
);
this.updateLastMessageReceivedTimestamp(request.sessionID);
await checkValidInitializationResponse(request, this);
await sendTransferCommenceRequest(request.sessionID, this, true);
}
async onTransferCommenceResponseReceived(
request: TransferCommenceV1Response,
): Promise<void> {
const fnTag = `${this.className}#onTransferCommenceResponseReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`client gateway received TransferCommenceResponse: ${JSON.stringify(
request,
)}`,
);
this.updateLastMessageReceivedTimestamp(request.sessionID);
await checkValidTransferCommenceResponse(request, this);
await this.lockFabricAsset(request.sessionID);
await sendLockEvidenceRequest(request.sessionID, this, true);
}
async onLockEvidenceResponseReceived(
request: LockEvidenceV1Response,
): Promise<void> {
const fnTag = `${this.className}#onLockEvidenceResponseReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`client gateway received LockEvidenceResponse: ${JSON.stringify(
request,
)}`,
);
this.updateLastMessageReceivedTimestamp(request.sessionID);
await checkValidLockEvidenceResponse(request, this);
await sendCommitPreparationRequest(request.sessionID, this, true);
}
async onCommitPrepareResponseReceived(
request: CommitPreparationV1Response,
): Promise<void> {
const fnTag = `${this.className}#onCommitPrepareResponseReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.updateLastMessageReceivedTimestamp(request.sessionID);
await checkValidCommitPreparationResponse(request, this);
await this.deleteFabricAsset(request.sessionID);
await sendCommitFinalRequest(request.sessionID, this, true);
}
async onCommitFinalResponseReceived(
request: CommitFinalV1Response,
): Promise<void> {
const fnTag = `${this.className}#onCommitFinalResponseReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`client gateway received CommitFinalResponse: ${JSON.stringify(request)}`,
);
this.updateLastMessageReceivedTimestamp(request.sessionID);
await checkValidCommitFinalResponse(request, this);
await sendTransferCompleteRequest(request.sessionID, this, true);
}
//Recover
async onRecoverMessageReceived(request: RecoverV1Message): Promise<void> {
const fnTag = `${this.className}#onRecoverMessageReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`gateway received Recover message: ${JSON.stringify(request)}`,
);
this.updateLastMessageReceivedTimestamp(request.sessionID);
await checkValidRecoverMessage(request, this);
await sendRecoverUpdateMessage(request.sessionID, this, true);
}
async onRecoverUpdateMessageReceived(
request: RecoverUpdateV1Message,
): Promise<void> {
const fnTag = `${this.className}#onRecoverUpdateMessageReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`gateway received RecoverUpdate message: ${JSON.stringify(request)}`,
);
this.updateLastMessageReceivedTimestamp(request.sessionID);
await checkValidRecoverUpdateMessage(request, this);
await sendRecoverUpdateAckMessage(request.sessionID, this, true);
}
async onRecoverUpdateAckMessageReceived(
request: RecoverUpdateAckV1Message,
): Promise<void> {
const fnTag = `${this.className}#onRecoverUpdateAckMessageReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`gateway received RecoverUpdateAck message: ${JSON.stringify(request)}`,
);
this.updateLastMessageReceivedTimestamp(request.sessionID);
await checkValidRecoverUpdateAckMessage(request, this);
await sendRecoverSuccessMessage(request.sessionID, this, true);
}
async onRecoverSuccessMessageReceived(
request: RecoverUpdateAckV1Message,
): Promise<void> {
const fnTag = `${this.className}#onRecoverSuccessMessageReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`gateway received RecoverSuccess message: ${JSON.stringify(request)}`,
);
this.updateLastMessageReceivedTimestamp(request.sessionID);
await checkValidRecoverSuccessMessage(request, this);
await this.resumeOdapSession(request.sessionID, true);
}
async onRollbackMessageReceived(request: RollbackV1Message): Promise<void> {
const fnTag = `${this.className}#onRollbackMessageReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`gateway received Rollback message: ${JSON.stringify(request)}`,
);
this.updateLastMessageReceivedTimestamp(request.sessionID);
await checkValidRollbackMessage(request, this);
await this.rollback(request.sessionID);
await sendRollbackAckMessage(request.sessionID, this, true);
}
async onRollbackAckMessageReceived(
request: RollbackAckV1Message,
): Promise<void> {
const fnTag = `${this.className}#onRollbackAckMessageReceived()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`gateway received Rollback Ack message: ${JSON.stringify(request)}`,
);
this.updateLastMessageReceivedTimestamp(request.sessionID);
await checkValidRollbackAckMessage(request, this);
//this.deleteDatabaseEntries(request.sessionID);
}
async runOdap(request: ClientV1Request): Promise<void> {
const fnTag = `${this.className}#runOdap()`;
this.log.info(`${fnTag}, start processing, time: ${Date.now()}`);
this.log.info(
`client gateway received ClientRequest: ${JSON.stringify(request)}`,
);
const sessionID = this.configureOdapSession(request);
if (sessionID == undefined) {
throw new Error(
`${fnTag}, session id undefined after session configuration`,
);
}
await sendTransferInitializationRequest(sessionID, this, true);
}
configureOdapSession(request: ClientV1Request) {
const sessionData: SessionData = {};
const sessionID = uuidV4();
sessionData.id = sessionID;
sessionData.step = 1;
sessionData.version = request.version;
sessionData.lastSequenceNumber = randomInt(4294967295);
sessionData.sourceBasePath = request.clientGatewayConfiguration.apiHost;
sessionData.recipientBasePath = request.serverGatewayConfiguration.apiHost;
sessionData.allowedSourceBackupGateways = this.backupGatewaysAllowed;
sessionData.allowedRecipientBackupGateways = [];
sessionData.payloadProfile = request.payloadProfile;
sessionData.loggingProfile = request.loggingProfile;
sessionData.accessControlProfile = request.accessControlProfile;
sessionData.applicationProfile = request.applicationProfile;
sessionData.assetProfile = request.payloadProfile.assetProfile;
sessionData.originatorPubkey = request.originatorPubkey;
sessionData.beneficiaryPubkey = request.beneficiaryPubkey;
sessionData.sourceGatewayPubkey = this.pubKey;
sessionData.sourceGatewayDltSystem = request.sourceGatewayDltSystem;
sessionData.recipientGatewayPubkey = request.recipientGatewayPubkey;
sessionData.recipientGatewayDltSystem = request.recipientGatewayDltSystem;
sessionData.rollbackActionsPerformed = [];
sessionData.rollbackProofs = [];
sessionData.lastMessageReceivedTimestamp = Date.now().toString();
sessionData.maxRetries = request.maxRetries;
sessionData.maxTimeout = request.maxTimeout;
this.sessions.set(sessionID, sessionData);
return sessionID;
}
async lockFabricAsset(sessionID: string): Promise<string> {
const fnTag = `${this.className}#lockFabricAsset()`;
const sessionData = this.sessions.get(sessionID);
if (sessionData == undefined) {
throw new Error(`${fnTag}, session data is not correctly initialized`);
}
let fabricLockAssetProof = "";
await this.storeOdapLog({
sessionID: sessionID,
type: "exec",
operation: "lock-asset",
data: JSON.stringify(sessionData),
});
if (this.fabricApi != undefined) {
const response = await this.fabricApi.runTransactionV1({
signingCredential: this.fabricSigningCredential,
channelName: this.fabricChannelName,
contractName: this.fabricContractName,
invocationType: FabricContractInvocationType.Send,
methodName: "LockAsset",
params: [this.fabricAssetID],
} as FabricRunTransactionRequest);
const receiptLockRes = await this.fabricApi.getTransactionReceiptByTxIDV1(
{
signingCredential: this.fabricSigningCredential,
channelName: this.fabricChannelName,
contractName: "qscc",
invocationType: FabricContractInvocationType.Call,
methodName: "GetBlockByTxID",
params: [this.fabricChannelName, response.data.transactionId],
} as FabricRunTransactionRequest,
);
this.log.warn(receiptLockRes.data);
fabricLockAssetProof = JSON.stringify(receiptLockRes.data);
}
sessionData.lockEvidenceClaim = fabricLockAssetProof;
this.sessions.set(sessionID, sessionData);
this.log.info(`${fnTag}, proof of the asset lock: ${fabricLockAssetProof}`);
await this.storeOdapProof({
sessionID: sessionID,
type: "proof",
operation: "lock",
data: fabricLockAssetProof,
});
await this.storeOdapLog({
sessionID: sessionID,
type: "done",
operation: "lock-asset",
data: JSON.stringify(sessionData),
});
return fabricLockAssetProof;
}
async unlockFabricAsset(sessionID: string): Promise<string> {
const fnTag = `${this.className}#unlockFabricAsset()`;
const sessionData = this.sessions.get(sessionID);
if (
sessionData == undefined ||
sessionData.rollbackActionsPerformed == undefined ||
sessionData.rollbackProofs == undefined
) {
throw new Error(`${fnTag}, session data is not correctly initialized`);
}
let fabricUnlockAssetProof = "";
await this.storeOdapLog({
sessionID: sessionID,
type: "exec-rollback",
operation: "unlock-asset",
data: JSON.stringify(sessionData),
});
if (this.fabricApi != undefined) {
const response = await this.fabricApi.runTransactionV1({
signingCredential: this.fabricSigningCredential,
channelName: this.fabricChannelName,
contractName: this.fabricContractName,
invocationType: FabricContractInvocationType.Send,
methodName: "UnlockAsset",
params: [this.fabricAssetID],
} as FabricRunTransactionRequest);
const receiptUnlock = await this.fabricApi.getTransactionReceiptByTxIDV1({
signingCredential: this.fabricSigningCredential,
channelName: this.fabricChannelName,
contractName: "qscc",
invocationType: FabricContractInvocationType.Call,
methodName: "GetBlockByTxID",
params: [this.fabricChannelName, response.data.transactionId],
} as FabricRunTransactionRequest);
this.log.warn(receiptUnlock.data);
fabricUnlockAssetProof = JSON.stringify(receiptUnlock.data);
}
sessionData.rollbackActionsPerformed.push(
SessionDataRollbackActionsPerformedEnum.Unlock,
);
sessionData.rollbackProofs.push(fabricUnlockAssetProof);
this.sessions.set(sessionID, sessionData);
this.log.info(
`${fnTag}, proof of the asset unlock: ${fabricUnlockAssetProof}`,
);
await this.storeOdapProof({
sessionID: sessionID,
type: "proof-rollback",
operation: "unlock",
data: fabricUnlockAssetProof,
});
await this.storeOdapLog({
sessionID: sessionID,
type: "done-rollback",
operation: "unlock-asset",
data: JSON.stringify(sessionData),
});
return fabricUnlockAssetProof;
}
async createFabricAsset(sessionID: string): Promise<string> {
const fnTag = `${this.className}#createFabricAsset()`;
const sessionData = this.sessions.get(sessionID);
if (
sessionData == undefined ||
this.fabricAssetID == undefined ||
this.fabricChannelName == undefined ||
this.fabricContractName == undefined ||
this.fabricSigningCredential == undefined ||
sessionData.rollbackProofs == undefined ||
sessionData.rollbackActionsPerformed == undefined
) {
throw new Error(`${fnTag}, session data is not correctly initialized`);
}
let fabricCreateAssetProof = "";
await this.storeOdapLog({
sessionID: sessionID,
type: "exec-rollback",
operation: "create-asset",
data: JSON.stringify(sessionData),
});
if (this.fabricApi != undefined) {
const response = await this.fabricApi.runTransactionV1({
contractName: this.fabricContractName,
channelName: this.fabricChannelName,
params: [this.fabricAssetID, "19"],
methodName: "CreateAsset",
invocationType: FabricContractInvocationType.Send,
signingCredential: this.fabricSigningCredential,
});
const receiptCreate = await this.fabricApi.getTransactionReceiptByTxIDV1({
signingCredential: this.fabricSigningCredential,
channelName: this.fabricChannelName,
contractName: "qscc",
invocationType: FabricContractInvocationType.Call,
methodName: "GetBlockByTxID",
params: [this.fabricChannelName, response.data.transactionId],
} as FabricRunTransactionRequest);
this.log.warn(receiptCreate.data);
fabricCreateAssetProof = JSON.stringify(receiptCreate.data);
}
sessionData.rollbackActionsPerformed.push(
SessionDataRollbackActionsPerformedEnum.Create,
);
sessionData.rollbackProofs.push(fabricCreateAssetProof);
this.sessions.set(sessionID, sessionData);
this.log.info(
`${fnTag}, proof of the asset creation: ${fabricCreateAssetProof}`,
);
await this.storeOdapProof({
sessionID: sessionID,
type: "proof-rollback",
operation: "create",
data: fabricCreateAssetProof,
});
await this.storeOdapLog({
sessionID: sessionID,
type: "done-rollback",
operation: "create-asset",
data: JSON.stringify(sessionData),
});
return fabricCreateAssetProof;
}
async deleteFabricAsset(sessionID: string): Promise<string> {
const fnTag = `${this.className}#deleteFabricAsset()`;
const sessionData = this.sessions.get(sessionID);
if (sessionData == undefined) {
throw new Error(`${fnTag}, session data is not correctly initialized`);
}
let fabricDeleteAssetProof = "";
await this.storeOdapLog({
sessionID: sessionID,
type: "exec",
operation: "delete-asset",
data: JSON.stringify(sessionData),
});
if (this.fabricApi != undefined) {
const deleteRes = await this.fabricApi.runTransactionV1({
signingCredential: this.fabricSigningCredential,
channelName: this.fabricChannelName,
contractName: this.fabricContractName,
invocationType: FabricContractInvocationType.Send,
methodName: "DeleteAsset",
params: [this.fabricAssetID],
} as FabricRunTransactionRequest);
const receiptDeleteRes = await this.fabricApi.getTransactionReceiptByTxIDV1(
{
signingCredential: this.fabricSigningCredential,
channelName: this.fabricChannelName,
contractName: "qscc",
invocationType: FabricContractInvocationType.Call,
methodName: "GetBlockByTxID",
params: [this.fabricChannelName, deleteRes.data.transactionId],
} as FabricRunTransactionRequest,
);
this.log.warn(receiptDeleteRes.data);
fabricDeleteAssetProof = JSON.stringify(receiptDeleteRes.data);
}
sessionData.commitFinalClaim = fabricDeleteAssetProof;
this.sessions.set(sessionID, sessionData);
this.log.info(
`${fnTag}, proof of the asset deletion: ${fabricDeleteAssetProof}`,
);
await this.storeOdapProof({
sessionID: sessionID,
type: "proof",
operation: "delete",
data: fabricDeleteAssetProof,
});
await this.storeOdapLog({
sessionID: sessionID,
type: "done",
operation: "delete-asset",
data: JSON.stringify(sessionData),
});
return fabricDeleteAssetProof;
}
async createBesuAsset(sessionID: string): Promise<string> {
const fnTag = `${this.className}#createBesuAsset()`;
const sessionData = this.sessions.get(sessionID);
if (sessionData == undefined) {
throw new Error(`${fnTag}, session data is not correctly initialized`);
}
let besuCreateAssetProof = "";
await this.storeOdapLog({
sessionID: sessionID,
type: "exec",
operation: "create-asset",
data: JSON.stringify(sessionData),
});
if (this.besuApi != undefined) {
const besuCreateRes = await this.besuApi.invokeContractV1({
contractName: this.besuContractName,
invocationType: EthContractInvocationType.Send,
methodName: "createAsset",
gas: 1000000,
params: [this.besuAssetID, 100], //the second is size, may need to pass this from client?
signingCredential: this.besuWeb3SigningCredential,
keychainId: this.besuKeychainId,
} as BesuInvokeContractV1Request);
if (besuCreateRes.status != 200) {
//await this.Revert(sessionID);
throw new Error(`${fnTag}, besu create asset error`);
}
const besuCreateResDataJson = JSON.parse(
JSON.stringify(besuCreateRes.data),
);
if (besuCreateResDataJson.out == undefined) {
throw new Error(`${fnTag}, besu res data out undefined`);
}
if (besuCreateResDataJson.out.transactionReceipt == undefined) {
throw new Error(`${fnTag}, undefined besu transact receipt`);
}
const besuCreateAssetReceipt =
besuCreateResDataJson.out.transactionReceipt;
besuCreateAssetProof = JSON.stringify(besuCreateAssetReceipt);
}
sessionData.commitAcknowledgementClaim = besuCreateAssetProof;
this.sessions.set(sessionID, sessionData);
this.log.info(
`${fnTag}, proof of the asset creation: ${besuCreateAssetProof}`,
);
await this.storeOdapProof({
sessionID: sessionID,
type: "proof",
operation: "create",
data: besuCreateAssetProof,
});
await this.storeOdapLog({
sessionID: sessionID,
type: "done",
operation: "create-asset",
data: JSON.stringify(sessionData),
});
return besuCreateAssetProof;
}
async deleteBesuAsset(sessionID: string): Promise<string> {
const fnTag = `${this.className}#deleteBesuAsset()`;
const sessionData = this.sessions.get(sessionID);
if (
sessionData == undefined ||
sessionData.rollbackActionsPerformed == undefined ||
sessionData.rollbackProofs == undefined
) {
throw new Error(`${fnTag}, session data is not correctly initialized`);
}
let besuDeleteAssetProof = "";
await this.storeOdapLog({
sessionID: sessionID,
type: "exec-rollback",
operation: "delete-asset",
data: JSON.stringify(sessionData),
});
if (this.besuApi != undefined) {
// we need to lock the asset first
await this.besuApi.invokeContractV1({
contractName: this.besuContractName,
invocationType: EthContractInvocationType.Send,
methodName: "lockAsset",
gas: 1000000,
params: [this.besuAssetID],
signingCredential: this.besuWeb3SigningCredential,
keychainId: this.besuKeychainId,
} as BesuInvokeContractV1Request);
const assetCreationResponse = await this.besuApi.invokeContractV1({
contractName: this.besuContractName,
invocationType: EthContractInvocationType.Send,
methodName: "deleteAsset",
gas: 1000000,
params: [this.besuAssetID],
signingCredential: this.besuWeb3SigningCredential,
keychainId: this.besuKeychainId,
} as BesuInvokeContractV1Request);
if (assetCreationResponse.status != 200) {
throw new Error(`${fnTag}, besu delete asset error`);
}
const assetCreationResponseDataJson = JSON.parse(
JSON.stringify(assetCreationResponse.data),
);
if (assetCreationResponseDataJson.out == undefined) {
throw new Error(`${fnTag}, besu res data out undefined`);
}
if (assetCreationResponseDataJson.out.transactionReceipt == undefined) {
throw new Error(`${fnTag}, undefined besu transact receipt`);
}
const besuCreateAssetReceipt =
assetCreationResponseDataJson.out.transactionReceipt;
besuDeleteAssetProof = JSON.stringify(besuCreateAssetReceipt);
}
sessionData.rollbackActionsPerformed.push(
SessionDataRollbackActionsPerformedEnum.Delete,
);
sessionData.rollbackProofs.push(besuDeleteAssetProof);
this.sessions.set(sessionID, sessionData);
this.log.info(
`${fnTag}, proof of the asset deletion: ${besuDeleteAssetProof}`,
);
await this.storeOdapProof({
sessionID: sessionID,
type: "proof-rollback",
operation: "delete",
data: besuDeleteAssetProof,
});
await this.storeOdapLog({
sessionID: sessionID,
type: "done-rollback",
operation: "delete-asset",
data: JSON.stringify(sessionData),
});
return besuDeleteAssetProof;
}
async Revert(sessionID: string): Promise<void> {
await this.rollback(sessionID);
await sendRollbackMessage(sessionID, this, true);
}
async rollback(sessionID: string) {
const fnTag = `${this.className}#rollback()`;
const sessionData = this.sessions.get(sessionID);
if (
sessionData == undefined ||
sessionData.step == undefined ||
sessionData.lastSequenceNumber == undefined
) {
throw new Error(`${fnTag}, session data is undefined`);
}
sessionData.rollback = true;
this.log.info(`${fnTag}, rolling back session ${sessionID}`);
if (this.isClientGateway(sessionID)) {
if (
this.fabricApi == undefined ||
this.fabricContractName == undefined ||
this.fabricChannelName == undefined ||
this.fabricAssetID == undefined ||
this.fabricSigningCredential == undefined
)
return;
if (
await fabricAssetExists(
this,
this.fabricContractName,
this.fabricChannelName,
this.fabricAssetID,
this.fabricSigningCredential,
)
) {
if (
await isFabricAssetLocked(
this,
this.fabricContractName,
this.fabricChannelName,
this.fabricAssetID,
this.fabricSigningCredential,
)
) {
// Rollback locking of the asset
await this.unlockFabricAsset(sessionID);
}
} else {
// Rollback extinguishment of the asset
await this.createFabricAsset(sessionID);
}
} else {
if (
this.besuApi == undefined ||
this.besuContractName == undefined ||
this.besuKeychainId == undefined ||
this.besuAssetID == undefined ||
this.besuWeb3SigningCredential == undefined
)
return;
if (
await besuAssetExists(
this,
this.besuContractName,
this.besuKeychainId,
this.besuAssetID,
this.besuWeb3SigningCredential,
)
) {
// Rollback creation of the asset
await this.deleteBesuAsset(sessionID);
}
}
}
async makeRequest(
sessionID: string,
request: Promise<AxiosResponse>,
message: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<any> {
const fnTag = `${this.className}#makeRequest()`;
const sessionData = this.sessions.get(sessionID);
if (
sessionData == undefined ||
sessionData.maxTimeout == undefined ||
sessionData.maxRetries == undefined
) {
throw new Error(`${fnTag}, session data is not correctly initialized`);
}
let numberOfTries = 0;
let response = undefined;
while (numberOfTries < sessionData.maxRetries) {
response = await request.catch(() => {
this.log.info(`${fnTag}, ${message} message failed. Trying again...`);
numberOfTries++;
});
if (response != void 0) break;
}
if (response != void 0 && response.status == 200) {
return;
}
// When rolling back there is no problem of not receiving an answer
if (!message.match("Rollback")) {
this.log.info(
`${fnTag}, ${message} message was not sent. Initiating time...`,
);
await new Promise((resolve) =>
setTimeout(resolve, sessionData.maxTimeout),
).then(async () => {
// we check if a message was received, otherwise we have a timeout and rollback
const sessionData = this.sessions.get(sessionID);
if (
sessionData == undefined ||
sessionData.lastMessageReceivedTimestamp == undefined ||
sessionData.maxTimeout == undefined
) {
throw new Error(
`${fnTag}, session data is not correctly initialized`,
);
}
const differenceOfTime =
new Date().getTime() -
new Date(sessionData.lastMessageReceivedTimestamp).getTime();
if (differenceOfTime > sessionData.maxTimeout) {
this.log.info(`${fnTag}, no response received, rolling back`);
await this.Revert(sessionID);
throw new Error(
`${fnTag}, ${message} message failed. Timeout exceeded. Check connection with server gateway.`,
);
}
this.log.info(`${fnTag}, a response was received`);
return;
});
}
return response;
}
} | the_stack |
import { SchemaItemType } from "./ECObjects";
import { AnyClass, AnyECType } from "./Interfaces";
import { ECClass, StructClass } from "./Metadata/Class";
import { Constant } from "./Metadata/Constant";
import { CustomAttributeContainerProps } from "./Metadata/CustomAttribute";
import { CustomAttributeClass } from "./Metadata/CustomAttributeClass";
import { EntityClass } from "./Metadata/EntityClass";
import { Enumeration } from "./Metadata/Enumeration";
import { Format } from "./Metadata/Format";
import { InvertedUnit } from "./Metadata/InvertedUnit";
import { KindOfQuantity } from "./Metadata/KindOfQuantity";
import { Mixin } from "./Metadata/Mixin";
import { Phenomenon } from "./Metadata/Phenomenon";
import { AnyProperty, Property } from "./Metadata/Property";
import { PropertyCategory } from "./Metadata/PropertyCategory";
import { RelationshipClass, RelationshipConstraint } from "./Metadata/RelationshipClass";
import { Schema } from "./Metadata/Schema";
import { SchemaItem } from "./Metadata/SchemaItem";
import { Unit } from "./Metadata/Unit";
import { UnitSystem } from "./Metadata/UnitSystem";
/**
* Interface to allow schema traversal/deserialization workflows to visit
* each part, item, class, etc. that exists in a given schema.
* @beta
*/
export interface ISchemaPartVisitor {
/**
* Called for a partially loaded schema. During deserialization, this would
* be after a schema and all its references are deserialized, but _before_
* any of its items or custom attributes have been deserialized.
* @param schema A partially-loaded Schema.
*/
/* async */ visitEmptySchema?: (schema: Schema) => Promise<void>;
/**
* Called for a partially loaded schema. During deserialization, this would
* be after a schema and all its references are deserialized, but _before_
* any of its items or custom attributes have been deserialized.
* @param schema A partially-loaded Schema.
*/
visitEmptySchemaSync?: (schema: Schema) => void;
/**
* Called for a fully loaded schema.
* @param schema A fully-loaded Schema.
*/
/* async */ visitFullSchema?: (schema: Schema) => Promise<void>;
/**
* Called for a fully loaded schema.
* @param schema A fully-loaded Schema.
*/
visitFullSchemaSync?: (schema: Schema) => void;
/**
* Called for each [[SchemaItem]] instance.
* @param schemaItem a SchemaItem object.
*/
/* async */ visitSchemaItem?: (schemaItem: SchemaItem) => Promise<void>;
/**
* Called for each [[SchemaItem]] instance.
* @param schemaItem a SchemaItem object.
*/
visitSchemaItemSync?: (schemaItem: SchemaItem) => void;
/**
* Called for each [[AnyClass]] instance.
* @param ecClass an ECClass object.
*/
/* async */ visitClass?: (ecClass: AnyClass) => Promise<void>;
/**
* Called for each [[AnyClass]] instance.
* @param ecClass an ECClass object.
*/
visitClassSync?: (ecClass: AnyClass) => void;
/**
* Called for each [[AnyProperty]] instance of an ECClass.
* @param property an AnyProperty object.
*/
/* async */ visitProperty?: (property: AnyProperty) => Promise<void>;
/**
* Called for each [[AnyProperty]] instance of an ECClass.
* @param property an AnyProperty object.
*/
visitPropertySync?: (property: AnyProperty) => void;
/**
* Called for each [[EntityClass]] instance.
* @param entityClass an EntityClass object.
*/
/* async */ visitEntityClass?: (entityClass: EntityClass) => Promise<void>;
/**
* Called for each [[EntityClass]] instance.
* @param entityClass an EntityClass object.
*/
visitEntityClassSync?: (entityClass: EntityClass) => void;
/**
* Called for each [[StructClass]] instance.
* @param structClass a StructClass object.
*/
/* async */ visitStructClass?: (structClass: StructClass) => Promise<void>;
/**
* Called for each [[StructClass]] instance.
* @param structClass a StructClass object.
*/
visitStructClassSync?: (structClass: StructClass) => void;
/**
* Called for each [[Mixin]] instance.
* @param mixin a Mixin object.
*/
/* async */ visitMixin?: (mixin: Mixin) => Promise<void>;
/**
* Called for each [[Mixin]] instance.
* @param mixin a Mixin object.
*/
visitMixinSync?: (mixin: Mixin) => void;
/**
* Called for each [[RelationshipClass]] instance.
* @param relationshipClass a RelationshipClass object.
*/
/* async */ visitRelationshipClass?: (relationshipClass: RelationshipClass) => Promise<void>;
/**
* Called for each [[RelationshipClass]] instance.
* @param relationshipClass a RelationshipClass object.
*/
visitRelationshipClassSync?: (relationshipClass: RelationshipClass) => void;
/**
* Called for each [[RelationshipConstraint]] of each RelationshipClass.
* @param relationshipConstraint a RelationshipConstraint object.
*/
/* async */ visitRelationshipConstraint?: (relationshipConstraint: RelationshipConstraint) => Promise<void>;
/**
* Called for each [[RelationshipConstraint]] of each RelationshipClass.
* @param relationshipConstraint a RelationshipConstraint object.
*/
visitRelationshipConstraintSync?: (relationshipConstraint: RelationshipConstraint) => void;
/**
* Called for each [[CustomAttributeClass]] instance.
* @param customAttributeClass a CustomAttributeClass object.
*/
/* async */ visitCustomAttributeClass?: (customAttributeClass: CustomAttributeClass) => Promise<void>;
/**
* Called for each [[CustomAttributeClass]] instance.
* @param customAttributeClass a CustomAttributeClass object.
*/
visitCustomAttributeClassSync?: (customAttributeClass: CustomAttributeClass) => void;
/**
* Called for each CustomAttribute container in the schema.
* @param customAttributeContainer a CustomAttributeContainerProps object.
*/
/* async */ visitCustomAttributeContainer?: (customAttributeContainer: CustomAttributeContainerProps) => Promise<void>;
/**
* Called for each CustomAttribute container in the schema.
* @param customAttributeContainer a CustomAttributeContainerProps object.
*/
visitCustomAttributeContainerSync?: (customAttributeContainer: CustomAttributeContainerProps) => void;
/**
* Called for each [[Enumeration]] instance.
* @param enumeration an Enumeration object.
*/
/* async */ visitEnumeration?: (enumeration: Enumeration) => Promise<void>;
/**
* Called for each [[Enumeration]] instance.
* @param enumeration an Enumeration object.
*/
visitEnumerationSync?: (enumeration: Enumeration) => void;
/**
* Called for each [[KindOfQuantity]] instance.
* @param koq a KindOfQuantity object.
*/
/* async */ visitKindOfQuantity?: (koq: KindOfQuantity) => Promise<void>;
/**
* Called for each [[KindOfQuantity]] instance.
* @param koq a KindOfQuantity object.
*/
visitKindOfQuantitySync?: (koq: KindOfQuantity) => void;
/**
* Called for each [[PropertyCategory]] instance.
* @param category a PropertyCategory object.
*/
/* async */ visitPropertyCategory?: (category: PropertyCategory) => Promise<void>;
/**
* Called for each [[PropertyCategory]] instance.
* @param category a PropertyCategory object.
*/
visitPropertyCategorySync?: (category: PropertyCategory) => void;
/**
* Called for each [[Format]] instance.
* @param format a Format object.
*/
/* async */ visitFormat?: (format: Format) => Promise<void>;
/**
* Called for each [[Format]] instance.
* @param format a Format object.
*/
visitFormatSync?: (format: Format) => void;
/**
* Called for each [[Unit]] instance.
* @param unit a Unit object.
*/
/* async */ visitUnit?: (unit: Unit) => Promise<void>;
/**
* Called for each [[Unit]] instance.
* @param unit a Unit object.
*/
visitUnitSync?: (unit: Unit) => void;
/**
* Called for each [[InvertedUnit]] instance.
* @param invertedUnit an InvertedUnit object.
*/
/* async */ visitInvertedUnit?: (invertedUnit: InvertedUnit) => Promise<void>;
/**
* Called for each [[InvertedUnit]] instance.
* @param invertedUnit an InvertedUnit object.
*/
visitInvertedUnitSync?: (invertedUnit: InvertedUnit) => void;
/**
* Called for each [[UnitSystem]] instance.
* @param unitSystem a UnitSystem object.
*/
/* async */ visitUnitSystem?: (unitSystem: UnitSystem) => Promise<void>;
/**
* Called for each [[UnitSystem]] instance.
* @param unitSystem a UnitSystem object.
*/
visitUnitSystemSync?: (unitSystem: UnitSystem) => void;
/**
* Called for each [[Phenomenon]] instance.
* @param phenomena a Phenomenon object.
*/
/* async */ visitPhenomenon?: (phenomena: Phenomenon) => Promise<void>;
/**
* Called for each [[Phenomenon]] instance.
* @param phenomena a Phenomenon object.
*/
visitPhenomenonSync?: (phenomena: Phenomenon) => void;
/**
* Called for each [[Constant]] instance.
* @param constant a Constant object.
*/
/* async */ visitConstant?: (constant: Constant) => Promise<void>;
/**
* Called for each [[Constant]] instance.
* @param constant a Constant object.
*/
visitConstantSync?: (constant: Constant) => void;
}
function isCustomAttributeContainer(object: any): object is CustomAttributeContainerProps {
return "customAttributes" in object;
}
/**
* A helper class to call methods on the provided [[ISchemaPartVisitor]].
* @beta
*/
export class SchemaPartVisitorDelegate {
private _visitor: ISchemaPartVisitor;
constructor(visitor: ISchemaPartVisitor) {
this._visitor = visitor;
}
/**
* Calls (async) visitEmptySchema or visitFullSchema on the configured [[ISchemaPartVisitor]].
* @param schema The schema to pass to the visitor.
* @param fullSchema Indicates if the schema is partially or fully-loaded.
*/
public async visitSchema(schema: Schema, fullSchema: boolean = true): Promise<void> {
if (!fullSchema && this._visitor.visitEmptySchema)
await this._visitor.visitEmptySchema(schema);
if (fullSchema && this._visitor.visitFullSchema)
await this._visitor.visitFullSchema(schema);
}
/**
* Calls (synchronously) visitEmptySchema or visitFullSchema on the configured [[ISchemaPartVisitor]].
* @param schema The schema to pass to the visitor.
* @param fullSchema Indicates if the schema is partially or fully-loaded.
*/
public visitSchemaSync(schema: Schema, fullSchema: boolean = true): void {
if (!fullSchema && this._visitor.visitEmptySchemaSync)
this._visitor.visitEmptySchemaSync(schema);
if (fullSchema && this._visitor.visitFullSchemaSync)
this._visitor.visitFullSchemaSync(schema);
}
/**
* Calls (async) the appropriate visit methods on the configured [[ISchemaPartVisitor]]
* based on the type of the part specified.
* @param schemaPart The schema part to pass to the visitor methods.
*/
public async visitSchemaPart(schemaPart: AnyECType): Promise<void> {
if (SchemaItem.isSchemaItem(schemaPart)) {
await this.visitSchemaItem(schemaPart);
} else if (Property.isProperty(schemaPart) && this._visitor.visitProperty) {
await this._visitor.visitProperty(schemaPart);
} else if (RelationshipConstraint.isRelationshipConstraint(schemaPart) && this._visitor.visitRelationshipConstraint) {
await this._visitor.visitRelationshipConstraint(schemaPart);
}
if (isCustomAttributeContainer(schemaPart) && this._visitor.visitCustomAttributeContainer) {
await this._visitor.visitCustomAttributeContainer(schemaPart);
}
}
/**
* Calls (synchronously) the appropriate visit methods on the configured [[ISchemaPartVisitor]]
* based on the type of the part specified.
* @param schemaPart The schema part to pass to the visitor methods.
*/
public visitSchemaPartSync(schemaPart: AnyECType): void {
if (SchemaItem.isSchemaItem(schemaPart)) {
this.visitSchemaItemSync(schemaPart);
} else if (Property.isProperty(schemaPart) && this._visitor.visitPropertySync) {
this._visitor.visitPropertySync(schemaPart);
} else if (RelationshipConstraint.isRelationshipConstraint(schemaPart) && this._visitor.visitRelationshipConstraintSync) {
this._visitor.visitRelationshipConstraintSync(schemaPart);
}
if (isCustomAttributeContainer(schemaPart) && this._visitor.visitCustomAttributeContainerSync)
this._visitor.visitCustomAttributeContainerSync(schemaPart);
}
private async visitSchemaItem(schemaItem: SchemaItem) {
if (this._visitor.visitSchemaItem)
await this._visitor.visitSchemaItem(schemaItem);
if (ECClass.isECClass(schemaItem) && this._visitor.visitClass)
await this._visitor.visitClass(schemaItem as AnyClass);
switch (schemaItem.schemaItemType) {
case SchemaItemType.Constant:
if (this._visitor.visitConstant)
await this._visitor.visitConstant(schemaItem as Constant);
break;
case SchemaItemType.CustomAttributeClass:
if (this._visitor.visitCustomAttributeClass)
await this._visitor.visitCustomAttributeClass(schemaItem as CustomAttributeClass);
break;
case SchemaItemType.EntityClass:
if (this._visitor.visitEntityClass)
await this._visitor.visitEntityClass(schemaItem as EntityClass);
break;
case SchemaItemType.Enumeration:
if (this._visitor.visitEnumeration)
await this._visitor.visitEnumeration(schemaItem as Enumeration);
break;
case SchemaItemType.Format:
if (this._visitor.visitFormat)
await this._visitor.visitFormat(schemaItem as Format);
break;
case SchemaItemType.InvertedUnit:
if (this._visitor.visitInvertedUnit)
await this._visitor.visitInvertedUnit(schemaItem as InvertedUnit);
break;
case SchemaItemType.KindOfQuantity:
if (this._visitor.visitKindOfQuantity)
await this._visitor.visitKindOfQuantity(schemaItem as KindOfQuantity);
break;
case SchemaItemType.Mixin:
if (this._visitor.visitMixin)
await this._visitor.visitMixin(schemaItem as Mixin);
break;
case SchemaItemType.Phenomenon:
if (this._visitor.visitPhenomenon)
await this._visitor.visitPhenomenon(schemaItem as Phenomenon);
break;
case SchemaItemType.PropertyCategory:
if (this._visitor.visitPropertyCategory)
await this._visitor.visitPropertyCategory(schemaItem as PropertyCategory);
break;
case SchemaItemType.RelationshipClass:
if (this._visitor.visitRelationshipClass)
await this._visitor.visitRelationshipClass(schemaItem as RelationshipClass);
break;
case SchemaItemType.StructClass:
if (this._visitor.visitStructClass)
await this._visitor.visitStructClass(schemaItem as StructClass);
break;
case SchemaItemType.Unit:
if (this._visitor.visitUnit)
await this._visitor.visitUnit(schemaItem as Unit);
break;
case SchemaItemType.UnitSystem:
if (this._visitor.visitUnitSystem)
await this._visitor.visitUnitSystem(schemaItem as UnitSystem);
break;
}
}
private visitSchemaItemSync(schemaItem: SchemaItem) {
if (this._visitor.visitSchemaItemSync)
this._visitor.visitSchemaItemSync(schemaItem);
if (ECClass.isECClass(schemaItem) && this._visitor.visitClassSync)
this._visitor.visitClassSync(schemaItem as AnyClass);
switch (schemaItem.schemaItemType) {
case SchemaItemType.Constant:
if (this._visitor.visitConstantSync)
this._visitor.visitConstantSync(schemaItem as Constant);
break;
case SchemaItemType.CustomAttributeClass:
if (this._visitor.visitCustomAttributeClassSync)
this._visitor.visitCustomAttributeClassSync(schemaItem as CustomAttributeClass);
break;
case SchemaItemType.EntityClass:
if (this._visitor.visitEntityClassSync)
this._visitor.visitEntityClassSync(schemaItem as EntityClass);
break;
case SchemaItemType.Enumeration:
if (this._visitor.visitEnumerationSync)
this._visitor.visitEnumerationSync(schemaItem as Enumeration);
break;
case SchemaItemType.Format:
if (this._visitor.visitFormatSync)
this._visitor.visitFormatSync(schemaItem as Format);
break;
case SchemaItemType.InvertedUnit:
if (this._visitor.visitInvertedUnitSync)
this._visitor.visitInvertedUnitSync(schemaItem as InvertedUnit);
break;
case SchemaItemType.KindOfQuantity:
if (this._visitor.visitKindOfQuantitySync)
this._visitor.visitKindOfQuantitySync(schemaItem as KindOfQuantity);
break;
case SchemaItemType.Mixin:
if (this._visitor.visitMixinSync)
this._visitor.visitMixinSync(schemaItem as Mixin);
break;
case SchemaItemType.Phenomenon:
if (this._visitor.visitPhenomenonSync)
this._visitor.visitPhenomenonSync(schemaItem as Phenomenon);
break;
case SchemaItemType.PropertyCategory:
if (this._visitor.visitPropertyCategorySync)
this._visitor.visitPropertyCategorySync(schemaItem as PropertyCategory);
break;
case SchemaItemType.RelationshipClass:
if (this._visitor.visitRelationshipClassSync)
this._visitor.visitRelationshipClassSync(schemaItem as RelationshipClass);
break;
case SchemaItemType.StructClass:
if (this._visitor.visitStructClassSync)
this._visitor.visitStructClassSync(schemaItem as StructClass);
break;
case SchemaItemType.Unit:
if (this._visitor.visitUnitSync)
this._visitor.visitUnitSync(schemaItem as Unit);
break;
case SchemaItemType.UnitSystem:
if (this._visitor.visitUnitSystemSync)
this._visitor.visitUnitSystemSync(schemaItem as UnitSystem);
break;
}
}
} | the_stack |
import 'reflect-metadata';
import 'mocha';
import { expect } from "chai";
import { Container } from 'inversify';
import { TYPES } from '../../base/types';
import { ConsoleLogger } from "../../utils/logging";
import { EMPTY_ROOT } from "../../base/model/smodel-factory";
import { SModelElement, SModelElementSchema, SModelRoot, SModelRootSchema } from "../../base/model/smodel";
import { CommandExecutionContext } from "../../base/commands/command";
import { AnimationFrameSyncer } from "../../base/animations/animation-frame-syncer";
import { CompoundAnimation } from "../../base/animations/animation";
import { SNodeSchema, SGraphSchema } from "../../graph/sgraph";
import { SGraphFactory } from "../../graph/sgraph-factory";
import { FadeAnimation } from "../../features/fade/fade";
import { MoveAnimation } from "../../features/move/move";
import { UpdateModelCommand } from "./update-model";
import { ModelMatcher } from "./model-matching";
import defaultModule from "../../base/di.config";
function compare(expected: SModelElementSchema, actual: SModelElement) {
for (const p in expected) {
if (expected.hasOwnProperty(p)) {
const expectedProp = (expected as any)[p];
const actualProp = (actual as any)[p];
if (p === 'children') {
for (const i in expectedProp) {
if (expectedProp.hasOwnProperty(i)) {
compare(expectedProp[i], actualProp[i]);
}
}
} else {
expect(actualProp).to.deep.equal(expectedProp);
}
}
}
}
describe('UpdateModelCommand', () => {
const container = new Container();
container.load(defaultModule);
container.rebind(TYPES.IModelFactory).to(SGraphFactory).inSingletonScope();
const graphFactory = container.get<SGraphFactory>(TYPES.IModelFactory);
const emptyRoot = graphFactory.createRoot(EMPTY_ROOT);
const context: CommandExecutionContext = {
root: emptyRoot,
modelFactory: graphFactory,
duration: 0,
modelChanged: undefined!,
logger: new ConsoleLogger(),
syncer: new AnimationFrameSyncer()
};
const model1 = graphFactory.createRoot({
id: 'model',
type: 'graph',
children: []
});
const model2: SModelRootSchema = {
id: 'model',
type: 'graph2',
children: []
};
const command1 = new UpdateModelCommand({
kind: UpdateModelCommand.KIND,
newRoot: model2,
animate: false
});
it('replaces the model if animation is suppressed', () => {
context.root = model1; /* the old model */
const newModel = command1.execute(context);
compare(model2, newModel as SModelRoot);
expect(model1).to.equal(command1.oldRoot);
expect(newModel).to.equal(command1.newRoot);
});
it('undo() returns the previous model', () => {
context.root = graphFactory.createRoot(model2);
expect(model1).to.equal(command1.undo(context));
});
it('redo() returns the new model', () => {
context.root = model1; /* the old model */
const newModel = command1.redo(context);
compare(model2, newModel as SModelRoot);
});
class TestUpdateModelCommand extends UpdateModelCommand {
testAnimation(root: SModelRoot, execContext: CommandExecutionContext) {
this.oldRoot = root;
this.newRoot = execContext.modelFactory.createRoot(this.action.newRoot!);
const matcher = new ModelMatcher();
const matchResult = matcher.match(root, this.newRoot);
return this.computeAnimation(this.newRoot, matchResult, execContext);
}
}
it('fades in new elements', () => {
const command2 = new TestUpdateModelCommand({
kind: UpdateModelCommand.KIND,
animate: true,
newRoot: {
type: 'graph',
id: 'model',
children: [
{
type: 'node',
id: 'child1'
},
{
type: 'node',
id: 'child2'
}
]
}
});
const animation = command2.testAnimation(model1, context);
expect(animation).to.be.an.instanceOf(FadeAnimation);
const fades = (animation as FadeAnimation).elementFades;
expect(fades).to.have.lengthOf(2);
for (const fade of fades) {
expect(fade.type).to.equal('in');
expect(fade.element.type).to.equal('node');
expect(fade.element.id).to.be.oneOf(['child1', 'child2']);
}
});
it('fades out deleted elements', () => {
const model3 = graphFactory.createRoot({
type: 'graph',
id: 'model',
children: [
{
type: 'node',
id: 'child1'
},
{
type: 'node',
id: 'child2'
}
]
});
const command2 = new TestUpdateModelCommand({
kind: UpdateModelCommand.KIND,
animate: true,
newRoot: {
type: 'graph',
id: 'model',
children: []
}
});
const animation = command2.testAnimation(model3, context);
expect(animation).to.be.an.instanceOf(FadeAnimation);
const fades = (animation as FadeAnimation).elementFades;
expect(fades).to.have.lengthOf(2);
for (const fade of fades) {
expect(fade.type).to.equal('out');
expect(fade.element.type).to.equal('node');
expect(fade.element.id).to.be.oneOf(['child1', 'child2']);
}
});
it('moves relocated elements', () => {
const model3 = graphFactory.createRoot({
type: 'graph',
id: 'model',
children: [
{
type: 'node',
id: 'child1',
position: { x: 100, y: 100 }
} as SNodeSchema
]
});
const command2 = new TestUpdateModelCommand({
kind: UpdateModelCommand.KIND,
animate: true,
newRoot: {
type: 'graph',
id: 'model',
children: [
{
type: 'node',
id: 'child1',
position: { x: 150, y: 200 }
} as SNodeSchema
]
}
});
const animation = command2.testAnimation(model3, context);
expect(animation).to.be.an.instanceOf(MoveAnimation);
const moves = (animation as MoveAnimation).elementMoves;
const child1Move = moves.get('child1')!;
expect(child1Move.elementId).to.equal('child1');
expect(child1Move.fromPosition).to.deep.equal({ x: 100, y: 100 });
expect(child1Move.toPosition).to.deep.equal({ x: 150, y: 200 });
});
it('combines fade and move animations', () => {
const model3 = graphFactory.createRoot({
type: 'graph',
id: 'model',
children: [
{
type: 'node',
id: 'child1',
position: { x: 100, y: 100 }
} as SNodeSchema,
{
type: 'node',
id: 'child2'
}
]
});
const command2 = new TestUpdateModelCommand({
kind: UpdateModelCommand.KIND,
animate: true,
newRoot: {
type: 'graph',
id: 'model',
children: [
{
type: 'node',
id: 'child1',
position: { x: 150, y: 200 }
} as SNodeSchema,
{
type: 'node',
id: 'child3'
}
]
}
});
const animation = command2.testAnimation(model3, context);
expect(animation).to.be.an.instanceOf(CompoundAnimation);
const components = (animation as CompoundAnimation).components;
expect(components).to.have.lengthOf(2);
const fadeAnimation = components[0] as FadeAnimation;
expect(fadeAnimation).to.be.an.instanceOf(FadeAnimation);
expect(fadeAnimation.elementFades).to.have.lengthOf(2);
for (const fade of fadeAnimation.elementFades) {
if (fade.type === 'in')
expect(fade.element.id).to.equal('child3');
else if (fade.type === 'out')
expect(fade.element.id).to.equal('child2');
}
const moveAnimation = components[1] as MoveAnimation;
expect(moveAnimation).to.be.an.instanceOf(MoveAnimation);
const child1Move = moveAnimation.elementMoves.get('child1')!;
expect(child1Move.elementId).to.equal('child1');
expect(child1Move.fromPosition).to.deep.equal({ x: 100, y: 100 });
expect(child1Move.toPosition).to.deep.equal({ x: 150, y: 200 });
});
it('applies a given model diff', () => {
context.root = graphFactory.createRoot({
type: 'graph',
id: 'model',
children: [
{
type: 'node',
id: 'child1',
position: { x: 100, y: 100 }
} as SNodeSchema,
{
type: 'node',
id: 'child2'
}
]
});
const command2 = new TestUpdateModelCommand({
kind: UpdateModelCommand.KIND,
animate: false,
matches: [
{
right: {
type: 'node',
id: 'child3'
},
rightParentId: 'model'
},
{
left: {
type: 'node',
id: 'child2'
},
leftParentId: 'model'
},
{
left: {
type: 'node',
id: 'child1',
position: { x: 100, y: 100 }
} as SNodeSchema,
leftParentId: 'model',
right: {
type: 'node',
id: 'child1',
position: { x: 150, y: 200 }
} as SNodeSchema,
rightParentId: 'model',
}
]
});
const newModel = command2.execute(context) as SModelRoot;
expect(newModel.children).to.have.lengthOf(2);
const expected: SGraphSchema = {
type: 'graph',
id: 'model',
children: [
{
type: 'node',
id: 'child3'
},
{
type: 'node',
id: 'child1',
position: { x: 150, y: 200 }
} as SNodeSchema
]
};
compare(expected, newModel);
});
}); | the_stack |
import * as React from 'react';
import {
Input
} from 'antd';
import { InputProps } from 'antd/lib/input';
import LoadingOutlined from '@ant-design/icons/LoadingOutlined';
import CloseCircleOutlined from '@ant-design/icons/CloseCircleOutlined';
import OlMap from 'ol/Map';
import _debounce from 'lodash/debounce';
import Logger from '@terrestris/base-util/dist/Logger';
import WfsFilterUtil from '@terrestris/ol-util/dist/WfsFilterUtil/WfsFilterUtil';
import { CSS_PREFIX } from '../../constants';
import './WfsSearchInput.less';
interface DefaultProps {
/**
* A nested object mapping feature types to an object of attribute details,
* which are also mapped by search attribute name.
*
* Example:
* ```
* attributeDetails: {
* featType1: {
* attr1: {
* matchCase: true,
* type: 'number',
* exactSearch: false
* },
* attr2: {
* matchCase: false,
* type: 'string',
* exactSearch: true
* }
* },
* featType2: {...}
* }
* ```
*/
attributeDetails: {
[featureType: string]: {
[attributeName: string]: {
matchCase: boolean;
type: string;
exactSearch: boolean;
};
};
};
/**
* SRS name. No srsName attribute will be set on geometries when this is not
* provided.
*/
srsName: string;
/**
* The output format of the response.
*/
outputFormat: string;
/**
* Options which are added to the fetch-POST-request. credentials is set to
* 'same-origin' as default but can be overwritten. See also
* https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
*/
additionalFetchOptions: any;
/**
* The minimal amount of characters entered in the input to start a search.
*/
minChars: number;
/**
* Delay in ms before actually sending requests.
*/
delay: number;
/**
* Indicate if we should render the input and results. When setting to false,
* you need to handle user input and results yourself
*/
visible?: boolean;
/**
* The searchTerm may be given as prop. This is useful when setting
* `visible` to `false`.
*/
searchTerm?: string;
}
interface BaseProps {
/**
* An optional CSS class which should be added.
*/
className?: string;
/**
* The base URL. Please make sure that the WFS-Server supports CORS.
*/
baseUrl: string;
/**
* An object mapping feature types to an array of attributes that should be searched through.
*/
searchAttributes: {
[featureType: string]: string[];
};
/**
* The namespace URI used for features.
*/
featureNS?: string;
/**
* The prefix for the feature namespace.
*/
featurePrefix?: string;
/**
* The feature type names.
*/
featureTypes: string[];
/**
* Maximum number of features to fetch.
*/
maxFeatures?: number;
/**
* Geometry name to use in a BBOX filter.
*/
geometryName?: string;
/**
* Optional list of property names to serialize.
*/
propertyNames?: string[];
/**
* The ol.map to interact with on selection.
*/
map: OlMap;
/**
* Optional callback function, that will be called before WFS search starts.
* Can be useful if input value manipulation is needed (e.g. umlaut
* replacement `ä => oa` etc.)
*/
onBeforeSearch?: (value: string) => string;
/**
* An onFetchSuccess callback function which gets called with the
* successfully fetched data.
* Please note: if omitted only data fetch will be performed and no data
* will be shown afterwards!
*/
onFetchSuccess?: (data: any) => void;
/**
* An onFetchError callback function which gets called if data fetch is
* failed.
*/
onFetchError?: (data: any) => void;
/**
* Optional callback function, that will be called if 'clear' button of
* input field was clicked.
*/
onClearClick?: () => void;
/**
* Options which are passed to the constructor of the ol.format.WFS.
* compare: https://openlayers.org/en/latest/apidoc/module-ol_format_WFS.html
*/
wfsFormatOptions?: any;
}
interface WfsSearchState {
searchTerm: string;
data: any[];
fetching: boolean;
}
export type WfsSearchInputProps = BaseProps & Partial<DefaultProps> & InputProps;
/**
* The WfsSearchInput field.
* Implements an input field to do a WFS-GetFeature request.
*
* The GetFeature request is created with `ol.format.WFS.writeGetFeature`
* so most of the WFS specific options work like document in the corresponding
* API-docs: https://openlayers.org/en/latest/apidoc/module-ol_format_WFS.html
*
* @class WfsSearchInput
* @extends React.Component
*/
export class WfsSearchInput extends React.Component<WfsSearchInputProps, WfsSearchState> {
static defaultProps: DefaultProps = {
srsName: 'EPSG:3857',
outputFormat: 'application/json',
minChars: 3,
additionalFetchOptions: {},
attributeDetails: {},
delay: 300,
visible: true
};
/**
* The reference to the Input Element of the WfsSearch.
* @private
*/
_inputRef: any;
/**
* The className added to this component.
* @private
*/
className = `${CSS_PREFIX}wfssearchinput`;
/**
* Create the WfsSearchInput.
*
* @param props The initial props.
* @constructs WfsSearchInput
*/
constructor(props: WfsSearchInputProps) {
super(props);
this.state = {
searchTerm: '',
data: [],
fetching: false
};
this.onUpdateInput = this.onUpdateInput.bind(this);
// delay requests invoking
this.doSearch = _debounce(this.doSearch, this.props.delay);
}
/**
* Trigger search when searchTerm prop has changed
*
* @param prevProps Previous props
*/
componentDidUpdate(prevProps) {
if (this.props.searchTerm !== prevProps.searchTerm) {
const evt = {
target: {
value: this.props.searchTerm
}
};
this.onUpdateInput(evt);
}
}
/**
* Called if the input is being updated. It sets the current inputValue
* as searchTerm and starts a search if the inputValue has
* a length of at least `this.props.minChars` (default 3).
*
* @param evt The input value from `keyup` event.
* Gets undefined if clear btn is pressed.
*/
onUpdateInput(evt: any) {
const {
minChars,
onBeforeSearch
} = this.props;
this.setState({
data: []
});
let value = '';
if (evt && evt.target && evt.target.value) {
value = evt.target.value;
}
if (onBeforeSearch) {
value = onBeforeSearch(value);
}
this.setState({
searchTerm: value
}, () => {
if (this.state.searchTerm && this.state.searchTerm.length >= minChars) {
this.doSearch();
}
});
}
/**
* Perform the search.
* @private
*/
doSearch() {
const {
additionalFetchOptions,
baseUrl,
featureNS,
featurePrefix,
featureTypes,
geometryName,
maxFeatures,
outputFormat,
propertyNames,
srsName,
wfsFormatOptions,
searchAttributes,
attributeDetails
} = this.props;
const searchOpts = {
featureNS,
featurePrefix,
featureTypes,
geometryName,
maxFeatures,
outputFormat,
propertyNames,
srsName,
wfsFormatOptions,
searchAttributes,
attributeDetails
};
const request = WfsFilterUtil.getCombinedRequests(
searchOpts, this.state.searchTerm
);
if (request) {
this.setState({
fetching: true
}, () => {
fetch(`${baseUrl}`, {
method: 'POST',
credentials: additionalFetchOptions.credentials
? additionalFetchOptions.credentials
: 'same-origin',
body: new XMLSerializer().serializeToString(request),
...additionalFetchOptions
})
.then(response => response.json())
.then(this.onFetchSuccess.bind(this))
.catch(this.onFetchError.bind(this));
});
} else {
this.onFetchError('Missing GetFeature request parameters');
}
}
/**
* This function gets called on success of the WFS GetFeature fetch request.
* It sets the response as data.
* If an additional function `onFetchSuccess` is provided, it will be called
* as callback.
* @param response The found features.
*/
onFetchSuccess(response: any) {
const {
onFetchSuccess
} = this.props;
const data = response.features ? response.features : [];
data.forEach(feature => feature.searchTerm = this.state.searchTerm);
this.setState({
data,
fetching: false
}, () => {
if (onFetchSuccess) {
onFetchSuccess(data);
}
});
}
/**
* This function gets called when the WFS GetFeature fetch request returns an error.
* It logs the error to the console.
* If an additional function `onFetchSuccess` is provided, it will be called
* as callback.
*
* @param error The errorstring.
*/
onFetchError(error: string) {
const {
onFetchError
} = this.props;
Logger.error(`Error while requesting WFS GetFeature: ${error}`);
this.setState({
fetching: false
}, () => {
if (onFetchError) {
onFetchError(error);
}
});
}
/**
* Resets input field value and previously fetched data on reset button click.
*/
resetSearch() {
const {
onClearClick
} = this.props;
this._inputRef.input.value = '';
this.setState({
data: []
}, () => {
if (onClearClick) {
onClearClick();
}
});
}
/**
* The render function.
*/
render() {
const {
fetching
} = this.state;
const {
additionalFetchOptions,
baseUrl,
className,
featureNS,
featurePrefix,
featureTypes,
geometryName,
map,
maxFeatures,
minChars,
outputFormat,
propertyNames,
searchAttributes,
attributeDetails,
srsName,
wfsFormatOptions,
visible,
onFetchSuccess,
onFetchError,
onClearClick,
onBeforeSearch,
...passThroughProps
} = this.props;
if (visible === false) {
return null;
}
const finalClassName = className
? `${className} ${this.className}`
: this.className;
return (
<Input
className={finalClassName}
ref={inputRef => {this._inputRef = inputRef; }}
suffix={
fetching ?
<LoadingOutlined
onClick={this.resetSearch.bind(this)}
/> :
<CloseCircleOutlined
onClick={this.resetSearch.bind(this)}
/>
}
onPressEnter={this.onUpdateInput}
onKeyUp={this.onUpdateInput}
{...passThroughProps}
/>
);
}
}
export default WfsSearchInput; | the_stack |
import {
CURRENT_SITE_NAME, EUROPE_LIST, TMDB_API_KEY,
TMDB_API_URL, PT_GEN_API,
DOUBAN_SUGGEST_API, CURRENT_SITE_INFO, USE_CHINESE,
TORRENT_INFO,
} from './const';
import i18nConfig from './i18n.json';
import Notification from './components/Notification';
interface RequestOptions {
method?: 'GET' | 'POST'
responseType?: 'json' | 'blob' | 'arraybuffer' | undefined
headers?: Tampermonkey.RequestHeaders
data?: any
timeout?: number
}
const formatTorrentTitle = (title:string) => {
// 保留5.1 H.264中间的点
return title.replace(/\.(?!(\d+))/ig, ' ')
.replace(/\.(?=\d{4}|48|57|72|2k|4k|7.1|6.1|5.1|4.1|2.0|1.0)/ig, ' ').trim();
};
const handleError = (error:any) => {
Notification.open({
description: error.message || error,
});
};
const getDoubanInfo = async (doubanUrl:string) => {
try {
if (doubanUrl) {
const data = await fetch(doubanUrl, {
responseType: undefined,
});
if (data) {
const doubanData = await getDataFromDoubanPage(data);
doubanData.format = getDoubanFormat(doubanData);
return doubanData;
}
// 豆瓣读书无需二次获取数据
if (doubanUrl.match(/\/book/)) {
throw data.error;
} else {
const doubanInfo = await getAnotherDoubanInfo(doubanUrl);
return doubanInfo;
}
} else {
throw $t('豆瓣链接获取失败');
}
} catch (error) {
handleError(error);
}
};
const getDoubanBookInfo = async (doubanUrl:string):Promise<Douban.BookData|undefined> => {
const reqUrl = `${PT_GEN_API}?url=${doubanUrl}`;
const data = await fetch(reqUrl, {
responseType: 'json',
});
const { chinese_title, origin_title } = data;
let foreignTitle = '';
if (chinese_title !== origin_title) {
foreignTitle = origin_title;
}
if (data) {
return {
...data,
chineseTitle: chinese_title,
foreignTitle,
};
}
};
const getDataFromDoubanPage = async (domString:string): Promise<Douban.DoubanData> => {
const dom = new DOMParser().parseFromString(domString, 'text/html');
const fetchAnchor = function (anchor:JQuery) {
return anchor[0]?.nextSibling?.nodeValue?.trim() ?? '';
};
// title
const chineseTitle = $('title', dom).text().replace('(豆瓣)', '').trim();
const foreignTitle = $('span[property="v:itemreviewed"]', dom).text().replace(chineseTitle, '').trim();
let aka:string[] = []; let transTitle: string; let thisTitle: string;
const akaAnchor = $('#info span.pl:contains("又名")', dom);
if (akaAnchor.length > 0) {
const data = fetchAnchor(akaAnchor).split(' / ').sort((a:string, b:string) => { // 首字(母)排序
return a.localeCompare(b);
}).join('/');
aka = data.split('/');
}
if (foreignTitle) {
transTitle = chineseTitle + (aka.length > 0 ? (`/${aka.join('/')}`) : '');
thisTitle = foreignTitle;
} else {
transTitle = aka.join('/') || '';
thisTitle = chineseTitle;
}
// json
const jsonData = JSON.parse($('head > script[type="application/ld+json"]', dom).html().replace(/(\r\n|\n|\r|\t)/gm, ''));
const rating = jsonData.aggregateRating ? jsonData.aggregateRating.ratingValue : 0;
const votes = jsonData.aggregateRating ? jsonData.aggregateRating.ratingCount : 0;
const director = jsonData.director ? jsonData.director : [];
const writer = jsonData.author ? jsonData.author : [];
const cast = jsonData.actor ? jsonData.actor : [];
const poster = jsonData.image
.replace(/s(_ratio_poster|pic)/g, 'l$1')
.replace(/img\d/, 'img9');
// rate
const doubanLink = `https://movie.douban.com${jsonData.url}`;
let imdbId = ''; let imdbLink = ''; let imdbAverageRating; let imdbVotes; let imdbRating = '';
const imdbLinkAnchor = $('#info span.pl:contains("IMDb")', dom);
const hasImdb = imdbLinkAnchor.length > 0;
if (hasImdb) {
imdbId = fetchAnchor(imdbLinkAnchor);
imdbLink = `https://www.imdb.com/title/${imdbId}/`;
const imdbData = await fetch(
`https://p.media-imdb.com/static-content/documents/v1/title/${imdbId}/ratings%3Fjsonp=imdb.rating.run:imdb.api.title.ratings/data.json`,
{
responseType: undefined,
},
);
imdbAverageRating = imdbData.match(/rating":(\d\.\d)/)?.[1] ?? 0;
imdbVotes = imdbData.match(/ratingCount":(\d+)/)?.[1] ?? 0;
imdbRating = `${imdbAverageRating}/10 from ${imdbVotes} users`;
}
const year = ` ${$('#content > h1 > span.year', dom).text().substr(1, 4)}`;
const playDate = $('#info span[property="v:initialReleaseDate"]', dom).map(function () { // 上映日期
return $(this).text().trim();
}).toArray().sort((a, b) => { // 按上映日期升序排列
return new Date(a).getTime() - new Date(b).getTime();
});
const introductionDom = $('#link-report > span.all.hidden, #link-report > [property="v:summary"]', dom);
const summary = (
introductionDom.length > 0 ? introductionDom.text() : '暂无相关剧情介绍'
).split('\n').map(a => a.trim()).filter(a => a.length > 0).join('\n'); // 处理简介缩进
const genre = $('#info span[property="v:genre"]', dom).map(function () { // 类别
return $(this).text().trim();
}).toArray(); // 类别
const language = fetchAnchor($('#info span.pl:contains("语言")', dom));
const region = fetchAnchor($('#info span.pl:contains("制片国家/地区")', dom)); // 产地
const runtimeAnchor = $('#info span.pl:contains("单集片长")', dom);
const runtime = runtimeAnchor[0] ? fetchAnchor(runtimeAnchor) : $('#info span[property="v:runtime"]', dom).text().trim();
const episodesAnchor = $('#info span.pl:contains("集数")'); // 集数
const episodes = episodesAnchor[0] ? fetchAnchor(episodesAnchor) : '';
let tags;
const tag_another = $('div.tags-body > a[href^="/tag"]', dom);
if (tag_another.length > 0) {
tags = tag_another.map(function () {
return $(this).text();
}).get();
}
// awards
const awardsPage = await fetch(`${doubanLink}/awards`, {
responseType: undefined,
});
const awardsDoc = new DOMParser().parseFromString(awardsPage, 'text/html');
const awards = $('#content > div > div.article', awardsDoc).html()
.replace(/[ \n]/g, '')
.replace(/<\/li><li>/g, '</li> <li>')
.replace(/<\/a><span/g, '</a> <span')
.replace(/<(div|ul)[^>]*>/g, '\n')
.replace(/<[^>]+>/g, '')
.replace(/ /g, ' ')
.replace(/ +\n/g, '\n')
.trim();
return {
imdbLink,
imdbId,
imdbAverageRating,
imdbVotes,
imdbRating,
chineseTitle,
foreignTitle,
aka,
transTitle: transTitle.split('/'),
thisTitle: thisTitle.split('/'),
year,
playDate,
region,
genre,
language: language.split(','),
episodes,
duration: runtime,
introduction: summary,
doubanLink,
doubanRatingAverage: rating || 0,
doubanVotes: votes,
doubanRating: `${rating || 0}/10 from ${votes} users`,
poster,
director,
cast,
writer,
awards,
tags,
};
};
const getAnotherDoubanInfo = async (doubanUrl:string): Promise<Douban.DoubanData|void> => {
try {
if (doubanUrl) {
const doubanId = doubanUrl.match(/subject\/(\d+)/)?.[1] ?? '';
if (!doubanId) {
throw $t('豆瓣ID获取失败');
}
const data = await fetch(`https://api.wmdb.tv/movie/api?id=${doubanId}`);
if (data && data.id) {
return formatDoubanInfo(data);
}
throw data.message || $t('获取豆瓣信息失败');
} else {
throw $t('豆瓣链接获取失败');
}
} catch (error) {
handleError(error);
}
};
const formatDoubanInfo = (data:Douban.DoubanQueryData) => {
const {
doubanId, imdbId, imdbRating,
imdbVotes, dateReleased, alias,
originalName, doubanRating, episodes,
doubanVotes, year, duration, director,
data: info, actor, writer,
} = data;
const [chineseInfo, englishInfo] = info;
const chineseTitle = chineseInfo.name;
const foreignTitle = englishInfo.name;
const directorArray = director.map(item => {
return {
name: `${item.data[0].name} ${item.data[1].name}`,
};
});
const actorArray = actor.map(item => {
return {
name: `${item.data[0].name} ${item.data[1].name}`,
};
});
const writerArray = writer.map(item => {
return {
name: `${item.data[0].name} ${item.data[1].name}`,
};
});
let transTitle = alias?.split('/') ?? '';
if (chineseTitle !== originalName && !alias.includes(chineseTitle)) {
transTitle = [chineseTitle].concat(transTitle);
}
const formatData: Douban.DoubanData = {
imdbLink: `https://www.imdb.com/title/${imdbId}`,
imdbId,
imdbAverageRating: imdbRating,
imdbVotes,
imdbRating: `${imdbRating}/10 from ${imdbVotes} users`,
chineseTitle,
foreignTitle,
aka: alias.split('/'),
transTitle,
thisTitle: [originalName],
year,
playDate: [dateReleased?.match(/\d+-\d+-\d+/)?.[0] ?? ''] ?? [],
region: info[0].country,
genre: chineseInfo.genre.split('/'),
language: chineseInfo.language.split('/'),
episodes,
duration: `${duration / 60} 分钟`,
introduction: chineseInfo.description,
doubanLink: `https://movie.douban.com/subject/${doubanId}`,
doubanRatingAverage: doubanRating || 0,
doubanVotes,
doubanRating: `${doubanRating}/10 from ${doubanVotes} users`,
poster: chineseInfo.poster,
director: directorArray,
cast: actorArray,
writer: writerArray,
};
formatData.format = getDoubanFormat(formatData);
return formatData;
};
const getDoubanFormat = (data: Douban.DoubanData) => {
const {
poster, thisTitle, transTitle, genre,
year: movieYear, region, language, playDate,
imdbRating, imdbLink, doubanRating, doubanLink,
episodes: showEpisodes, duration: movieDuration,
director: directors, writer: writers, cast: actors, introduction,
awards, tags,
} = data;
let descr = poster ? `[img]${poster}[/img]\n\n` : '';
descr += transTitle ? `◎译 名 ${transTitle.join('/')}\n` : '';
descr += thisTitle ? `◎片 名 ${thisTitle.join('/')}\n` : '';
descr += movieYear ? `◎年 代 ${movieYear.trim()}\n` : '';
descr += region ? `◎产 地 ${region}\n` : '';
descr += genre ? `◎类 别 ${genre.join(' / ')}\n` : '';
descr += language ? `◎语 言 ${language}\n` : '';
descr += playDate ? `◎上映日期 ${playDate.join(' / ')}\n` : '';
descr += imdbRating ? `◎IMDb评分 ${imdbRating}\n` : '';
descr += imdbLink ? `◎IMDb链接 ${imdbLink}\n` : '';
descr += doubanRating ? `◎豆瓣评分 ${doubanRating}\n` : '';
descr += doubanLink ? `◎豆瓣链接 ${doubanLink}\n` : '';
descr += showEpisodes ? `◎集 数 ${showEpisodes}\n` : '';
descr += movieDuration ? `◎片 长 ${movieDuration}\n` : '';
descr += directors && directors.length > 0 ? `◎导 演 ${directors.map(x => x.name).join(' / ')}\n` : '';
descr += writers && writers.length > 0 ? `◎编 剧 ${writers.map(x => x.name).join(' / ')} \n` : '';
descr += actors && actors.length > 0 ? `◎主 演 ${actors.map(x => x.name).join(`\n${' '.repeat(14)} `).trim()} \n` : '';
descr += tags && tags.length > 0 ? `\n◎标 签 ${tags.join(' | ')} \n` : '';
descr += introduction ? `\n◎简 介\n\n ${introduction.replace(/\n/g, `\n${' '.repeat(2)}`)} \n` : '';
descr += awards ? `\n◎获奖情况\n\n ${awards.replace(/\n/g, `\n${' '.repeat(6)}`)} \n` : '';
return descr.trim();
};
const getDoubanIdByIMDB = async (query:string):(Promise<Douban.Season|undefined>) => {
try {
const imdbId = getIMDBIdByUrl(query);
const params = imdbId || query;
const url = DOUBAN_SUGGEST_API.replace('{query}', params);
const data = await fetch(url, {
responseType: undefined,
});
const doc = new DOMParser().parseFromString(data, 'text/html');
const linkDom: HTMLLinkElement|null = doc.querySelector('.result-list .result h3 a');
if (!linkDom) {
throw $t('豆瓣ID获取失败');
} else {
const { href, textContent } = linkDom;
const season = textContent?.match(/第(.+?)季/)?.[1] ?? '';
const doubanId = decodeURIComponent(href).match(/subject\/(\d+)/)?.[1] ?? '';
return ({
id: doubanId,
season,
title: textContent || '',
});
}
} catch (error) {
handleError(error);
}
};
const getIMDBData = async (imdbUrl: string):Promise<IMDB.ImdbData|undefined> => {
try {
if (!imdbUrl) {
throw new Error('$t(缺少IMDB信息)');
}
const data = await fetch(`${PT_GEN_API}?url=${imdbUrl}`);
if (data && data.success) {
return data;
}
throw data.error || $t('请求失败');
} catch (error) {
handleError(error);
}
};
const transferImgs = async (screenshot: string, authToken: string, imgHost = 'https://imgbb.com/json') => {
try {
const isHdbHost = !!screenshot.match(/i\.hdbits\.org/);
const formData = new FormData();
if (isHdbHost || imgHost.includes('gifyu')) {
const promiseArray = [urlToFile(screenshot)];
const [fileData] = await Promise.all(promiseArray);
formData.append('type', 'file');
formData.append('source', fileData);
} else {
formData.append('type', 'url');
formData.append('source', screenshot);
}
formData.append('action', 'upload');
formData.append('timestamp', `${Date.now()}`);
formData.append('auth_token', authToken);
const res = await fetch(imgHost, {
method: 'POST',
data: formData,
timeout: 3e5,
});
if (res.status_txt !== 'OK') {
throw $t('上传失败,请重试');
}
if (res.image) {
return res.image;
}
throw $t('上传失败,请重试');
} catch (error) {
console.log('err:', error);
handleError(error);
}
};
const uploadToPixhost = async (screenshots: string[]) => {
try {
const params = encodeURI(`imgs=${screenshots.join('\n')}&content_type=1&max_th_size=300`);
const res = await fetch('https://pixhost.to/remote/', {
method: 'POST',
data: params,
timeout: 3e5,
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
},
responseType: undefined,
});
const data = res.match(/(upload_results = )({.*})(;)/);
if (!data) {
throw $t('上传失败,请重试');
}
let imgResultList = [];
if (data && data.length) {
imgResultList = JSON.parse(data[2]).images;
if (imgResultList.length < 1) {
throw new Error($t('上传失败,请重试'));
}
return imgResultList;
}
throw new Error($t('上传失败,请重试'));
} catch (error) {
handleError(error);
}
};
// 获取更加准确的分类
const getPreciseCategory = (torrentInfo: TorrentInfo.Info, category: string) => {
const { description, title, subtitle, doubanInfo } = torrentInfo;
const movieGenre = (description + doubanInfo).match(/(类\s+别)\s+(.+)?/)?.[2] ?? '';
if (category === 'movie') {
if (movieGenre.match(/动画/)) {
category = 'cartoon';
} else if (movieGenre.match(/纪录/)) {
category = 'documentary';
}
} else if (category?.match(/tv/)) {
if (movieGenre.match(/动画/)) {
category = 'cartoon';
} else if (movieGenre.match(/纪录/)) {
category = 'documentary';
} else if (title.match(/(s0?\d{1,2})?e(p)?\d{1,2}/i) || subtitle?.match(/第[^\s]集/)) {
category = 'tv';
} else {
category = 'tvPack';
}
}
return category;
};
const getUrlParam = (key:string) => {
const reg = new RegExp(`(^|&)${key}=([^&]*)(&|$)`);
const regArray = location.search.substring(1).match(reg);
if (regArray) {
return decodeURIComponent(regArray[2]);
}
return '';
};
// 获取音频编码
const getAudioCodecFromTitle = (title:string) => {
if (!title) {
return '';
}
title = title.replace(/:|-|\s/g, '');
if (title.match(/atmos/i)) {
return 'atmos';
} else if (title.match(/dtshdma/i)) {
return 'dtshdma';
} else if (title.match(/dtsx/i)) {
return 'dtsx';
} else if (title.match(/dts/i)) {
return 'dts';
} else if (title.match(/truehd/i)) {
return 'truehd';
} else if (title.match(/lpcm/i)) {
return 'lpcm';
} else if (title.match(/flac/i)) {
return 'flac';
} else if (title.match(/aac/i)) {
return 'aac';
} else if (title.match(/DD\+|DDP|DolbyDigitalPlus/i)) {
return 'dd+';
} else if (title.match(/DD|DolbyDigital/i)) {
return 'dd';
} else if (title.match(/ac3/i)) {
return 'ac3';
}
return '';
};
const getVideoCodecFromTitle = (title:string, videoType = '') => {
title = title.replace(/\.|-/g, '');
if (title.match(/x264/i) || (title.match(/h264|avc/i) && videoType === 'encode')) {
return 'x264';
} else if (title.match(/h264|AVC/i)) {
return 'h264';
} else if (title.match(/x265/i) || (title.match(/h265|hevc/i) && videoType === 'encode')) {
return 'x265';
} else if (title.match(/hevc|h265/i)) {
return 'hevc';
} else if (title.match(/vc-?1/i)) {
return 'vc1';
} else if (title.match(/mpeg-?2/i)) {
return 'mpeg2';
} else if (title.match(/mpeg-?4/i)) {
return 'mpeg4';
}
return '';
};
const getFilterImages = (bbcode:string): string[] => {
if (!bbcode) {
return [];
}
let allImages = bbcode.match(/(\[url=(http(s)*:\/{2}.+?)\])?\[img\](.+?)\[\/img](\[url\])?/g);
if (allImages && allImages.length > 0) {
allImages = allImages.map(img => {
if (img.match(/\[url=.+?\]/)) {
return `${img}[/url]`;
}
return img;
});
// 过滤imdb、豆瓣、chd、柠檬无关图片
return allImages.filter(item => {
return !item.match(/MoreScreens|PTer\.png|trans\.gif|PTerREMUX\.png|PTerWEB\.png|CS\.png|Ourbits_info|GDJT|douban|logo|(2019\/03\/28\/5c9cb8f8216d7\.png)|_front|(info_01\.png)|(screens\.png)|(04\/6b\/Ggp5ReQb_o)|(ce\/e7\/KCmGFMOB_o)/);
});
}
return [];
};
const getScreenshotsFromBBCode = async (bbcode: string) => {
const allImages = getFilterImages(bbcode);
if (allImages && allImages.length > 0) {
const result = [];
for (const img of allImages) {
const originalUrl = await getOriginalImgUrl(img);
result.push(originalUrl);
}
return result;
}
return [];
};
/*
* 过滤真实原始截图地址
* 如果原图地址没有文件名后缀,截图地址则为缩略图地址
* */
const getOriginalImgUrl = async (urlBBcode:string) => {
let imgUrl:string = '';
if (urlBBcode.match(/\[url=http(s)*:.+/)) {
imgUrl = urlBBcode.match(/=(([^\]])+)/)?.[1] ?? '';
if (imgUrl.match(/img\.hdbits\.org/)) {
const imgId = urlBBcode.match(/\[url=https:\/\/img\.hdbits\.org\/(\w+)?\]/)?.[1] ?? '';
imgUrl = `https://i.hdbits.org/${imgId}.png`;
} else if (urlBBcode.match(/img\.pterclub\.com/)) {
imgUrl = urlBBcode.match(/img\](([^[])+)/)?.[1] ?? '';
imgUrl = imgUrl.replace(/\.th/g, '');
} else if (urlBBcode.match(/https?:\/\/imgbox\.com/)) {
imgUrl = urlBBcode.match(/img\](([^[])+)/)?.[1] ?? '';
imgUrl = imgUrl.replace(/thumbs(\d)/, 'images$1').replace(/_t(\.png)/, '_o.png');
} else if (imgUrl.match(/imagebam\.com/)) {
const originalPage = await fetch(imgUrl, {
responseType: undefined,
});
const doc = new DOMParser().parseFromString(originalPage, 'text/html');
imgUrl = $('.main-image', doc).attr('src') as string;
} else if (imgUrl.match(/beyondhd\.co/)) {
imgUrl = urlBBcode.match(/img\](([^[])+)/)?.[1] ?? '';
imgUrl = imgUrl.replace(/\.(th|md)\.(png|jpg|gif)/, '.$2');
} else if (!imgUrl.match(/\.(jpg|png|gif|bmp)$/)) {
imgUrl = urlBBcode.match(/img\](([^[])+)/)?.[1] ?? '';
} else if (urlBBcode.match(/https:\/\/pixhost\.to/)) {
const hostNumber = urlBBcode.match(/img\]https:\/\/t(\d+)\./)?.[1];
imgUrl = imgUrl.replace(/(pixhost\.to)\/show/, `img${hostNumber}.$1/images`);
}
} else if (urlBBcode.match(/\[img\]/)) {
imgUrl = urlBBcode.match(/img\](([^[])+)/)?.[1] ?? '';
}
return imgUrl;
};
// 从标题获取source
const getSourceFromTitle = (title: string) => {
if (title.match(/(uhd|2160|4k).*(blu(-)?ray|remux)/i)) {
return 'uhdbluray';
} else if (title.match(/blu(-)?ray|remux/i)) {
return 'bluray';
} else if (title.match(/hdtv/i)) {
return 'hdtv';
} else if (title.match(/web(-(rip|dl))+/i)) {
return 'web';
} else if (title.match(/hddvd/i)) {
return 'hddvd';
} else if (title.match(/dvd/i)) {
return 'dvd';
} else if (title.match(/vhs/i)) {
return 'vhs';
}
return 'other';
};
// 获取副标题
const getSubTitle = (data: Douban.DoubanData) => {
const { chineseTitle, thisTitle: originalTitle, transTitle } = data;
let title = '';
if (chineseTitle.match(/[\u4e00-\u9fa5]+/)) {
title += chineseTitle;
}
const moreTitle = originalTitle.concat(transTitle).filter(item => title !== item);
let seasonEpisode = TORRENT_INFO.title.match(/S\d+EP?(\d+)?/i)?.[1] ?? '';
seasonEpisode = seasonEpisode.replace(/^0/i, '');
const episode = seasonEpisode ? ` 第${seasonEpisode}集` : '';
const hardcodedSub = TORRENT_INFO.hardcodedSub ? '| 硬字幕' : '';
return `${title}${moreTitle.length > 0 ? '/' : ''}${moreTitle.join('/')}${episode} ${hardcodedSub}`;
};
/*
* 替换豆瓣演员中的英文名称
* @param {any}
* @return
* */
const replaceEngName = (string:string) => {
return string.replace(/\s+[A-Za-z\s]+/, '');
};
const getAreaCode = (area:string) => {
const europeList = EUROPE_LIST;
if (area) {
if (area.match(/USA|US|Canada|CA|美国|加拿大|United States/i)) {
return 'US';
} else if (europeList.includes(area) || area.match(/欧|英|法|德|俄|意|苏联|EU/i)) {
return 'EU';
} else if (area.match(/Japan|日本|JP/i)) {
return 'JP';
} else if (area.match(/Korea|韩国|KR/i)) {
return 'KR';
} else if (area.match(/Taiwan|台湾|TW/i)) {
return 'TW';
} else if (area.match(/Hong\s?Kong|香港|HK/i)) {
return 'HK';
} else if (area.match(/CN|China|大陆|中|内地|Mainland/i)) {
return 'CN';
}
}
return 'OT';
};
/*
* 获取蓝光类型
* @param {size}文件大小单位Bytes
* @return
* */
const getBDType = (size: number) => {
const GBSize = size / 1e9;
if (GBSize < 5) {
return 'DVD5';
} else if (GBSize < 9) {
return 'DVD9';
} else if (GBSize < 25) {
return 'BD25';
} else if (GBSize < 50) {
return 'BD50';
} else if (GBSize < 66) {
return 'BD66';
} else if (GBSize < 100) {
return 'BD100';
}
};
const getTMDBIdByIMDBId = async (imdbid: string) => {
try {
const url = `${TMDB_API_URL}/3/find/${imdbid}?api_key=${TMDB_API_KEY}&language=en&external_source=imdb_id`;
const data = await fetch(url);
const isMovie = data.movie_results && data.movie_results.length > 0;
const isTV = !data.tv_results && data.tv_results.length > 0;
if (!isMovie && !isTV) {
throw $t('请求失败');
}
const tmdbData = isMovie ? data.movie_results[0] : data.tv_results[0];
return tmdbData;
} catch (error) {
return {};
}
};
const getTMDBVideos = async (tmdbId: string) => {
const url = `${TMDB_API_URL}/3/movie/${tmdbId}/videos?api_key=${TMDB_API_KEY}&language=en`;
const data = await fetch(url);
return data.results || [];
};
const getIMDBIdByUrl = (imdbLink: string) => {
const imdbIdArray = /tt\d+/.exec(imdbLink);
if (imdbIdArray && imdbIdArray[0]) {
return imdbIdArray[0];
}
return '';
};
const getSize = (size: string) => {
if (!size) {
return 0;
}
if (size.match(/T/i)) {
return (parseFloat(size) * 1024 * 1024 * 1024 * 1024) || 0;
} else if (size.match(/G/i)) {
return (parseFloat(size) * 1024 * 1024 * 1024) || 0;
} else if (size.match(/M/i)) {
return (parseFloat(size) * 1024 * 1024) || 0;
} else if (size.match(/K/i)) {
return (parseFloat(size) * 1024) || 0;
}
return 0;
};
const getInfoFromMediaInfo = (mediaInfo:string) => {
if (!mediaInfo) {
return {};
}
const mediaArray = mediaInfo.split(/\n\s*\n/).filter(item => !!item.trim());
const [generalPart, videoPart] = mediaArray;
const secondVideoPart = mediaArray.filter(item => item.startsWith('Video #2'));
const [audioPart, ...otherAudioPart] = mediaArray.filter(item => item.startsWith('Audio'));
const textPart = mediaArray.filter(item => item.startsWith('Text'));
const completeName = getMediaValueByKey('Complete name', generalPart);
const format = completeName?.match(/\.(\w+)$/i)?.[1]?.toLowerCase() ?? '';
const fileName = completeName.replace(/\.\w+$/i, '');
const fileSize = getSize(getMediaValueByKey('File size', generalPart));
const { videoCodec, hdrFormat, isDV } = getVideoCodecByMediaInfo(videoPart, generalPart, secondVideoPart);
const { audioCodec, channelName, languageArray } = getAudioCodecByMediaInfo(audioPart, otherAudioPart);
const subtitleLanguageArray = textPart.map(item => {
return getMediaValueByKey('Language', item);
}).filter(sub => !!sub);
const mediaTags = getMediaTags(audioCodec, channelName, languageArray, subtitleLanguageArray, hdrFormat, isDV);
const resolution = getResolution(videoPart);
return {
fileName,
fileSize,
format,
subtitles: subtitleLanguageArray,
videoCodec,
audioCodec,
resolution,
mediaTags,
};
};
const getMediaValueByKey = (key:string, mediaInfo:string) => {
if (!mediaInfo) {
return '';
}
const keyRegStr = key.replace(/\s/, '\\s*').replace(/(\(|\))/g, '\\$1');
const reg = new RegExp(`${keyRegStr}\\s*:\\s([^\\n]+)`, 'i');
return mediaInfo.match(reg)?.[1] ?? '';
};
const getResolution = (mediaInfo:string) => {
const height = parseInt(getMediaValueByKey('Height', mediaInfo).replace(/\s/g, ''), 10);
const width = parseInt(getMediaValueByKey('Width', mediaInfo).replace(/\s/g, ''), 10);
const ScanType = getMediaValueByKey('Scan type', mediaInfo);
if (height > 1080) {
return '2160p';
} else if (height > 720 && ScanType === 'Progressive') {
return '1080p';
} else if (height > 720 && ScanType !== 'Progressive') {
return '1080i';
} else if (height > 576 || width > 1024) {
return '720p';
} else if (height > 480 || width === 1024) {
return '576p';
} else if (width >= 840 || height === 480) {
return '480p';
} else if (width && height) {
return `${width}x${height}`;
}
return '';
};
const getMediaTags = (
audioCodec:string,
channelName:string,
languageArray:string[],
subtitleLanguageArray:string[],
hdrFormat:string, isDV:boolean): TorrentInfo.MediaTags => {
const hasChineseAudio = languageArray.includes('Chinese');
const hasChineseSubtitle = subtitleLanguageArray.includes('Chinese');
const mediaTags: TorrentInfo.MediaTags = {};
if (hasChineseAudio) {
mediaTags.chinese_audio = true;
}
if (languageArray.includes('Cantonese')) {
mediaTags.cantonese_audio = true;
}
if (hasChineseSubtitle) {
mediaTags.chinese_subtitle = true;
}
if (hdrFormat) {
if (hdrFormat.match(/HDR10\+/i)) {
mediaTags.hdr10_plus = true;
} else if (hdrFormat.match(/HDR/i)) {
mediaTags.hdr = true;
}
}
if (isDV) {
mediaTags.dolby_vision = true;
}
if (audioCodec.match(/dtsx|atmos/ig)) {
mediaTags.dts_x = true;
} else if (audioCodec.match(/atmos/ig)) {
mediaTags.dolby_atmos = true;
}
return mediaTags;
};
const getVideoCodecByMediaInfo = (mainVideo:string, generalPart:string, secondVideo:string[]) => {
const generalFormat = getMediaValueByKey('Format', generalPart);
const videoFormat = getMediaValueByKey('Format', mainVideo);
const videoFormatVersion = getMediaValueByKey('Format version', mainVideo);
const videoCodeId = getMediaValueByKey('Codec ID', mainVideo);
const hdrFormat = getMediaValueByKey('HDR format', mainVideo);
const isDV = hdrFormat.match(/Dolby\s*Vision/i) ||
(secondVideo.length > 0 && getMediaValueByKey('HDR format', secondVideo[0]).match(/Dolby\s*Vision/i));
const isEncoded = !!getMediaValueByKey('Encoding settings', mainVideo);
let videoCodec = '';
if (generalFormat === 'DVD Video') {
videoCodec = 'mpeg2';
} else if (generalFormat === 'MPEG-4') {
videoCodec = 'mpeg4';
} else if (videoFormat === 'MPEG Video' && videoFormatVersion === 'Version 2') {
videoCodec = 'mpeg2';
} else if (videoCodeId.match(/xvid/i)) {
videoCodec = 'xvid';
} else if (videoFormat.match(/HEVC/i) && !isEncoded) {
videoCodec = 'hevc';
} else if (videoFormat.match(/HEVC/i) && isEncoded) {
videoCodec = 'x265';
} else if (videoFormat.match(/AVC/i) && isEncoded) {
videoCodec = 'x264';
} else if (videoFormat.match(/AVC/i) && !isEncoded) {
videoCodec = 'h264';
} else if (videoFormat.match(/VC-1/i)) {
videoCodec = 'vc1';
}
return {
videoCodec,
hdrFormat,
isDV: !!isDV,
};
};
const getAudioCodecByMediaInfo = (mainAudio:string, otherAudio:string[]) => {
const audioFormat = getMediaValueByKey('Format', mainAudio);
const audioChannels = getMediaValueByKey('Channel(s)', mainAudio);
const commercialName = getMediaValueByKey('Commercial name', mainAudio);
const languageArray = [mainAudio, ...otherAudio].map(item => {
return getMediaValueByKey('Language', item);
});
let channelName = '';
let audioCodec = '';
const channelNumber = parseInt(audioChannels, 10);
if (channelNumber && channelNumber >= 6) {
channelName = `${channelNumber - 1}.1`;
} else {
channelName = `${channelNumber}.0`;
}
if (audioFormat.match(/MLP FBA/i) && commercialName.match(/Dolby Atmos/i)) {
audioCodec = 'atmos';
} else if (audioFormat.match(/MLP FBA/i) && !commercialName.match(/Dolby Atmos/i)) {
audioCodec = 'truehd';
} else if (audioFormat.match(/AC-3/i) && commercialName.match(/Dolby Digital Plus/i)) {
audioCodec = 'dd+';
} else if (audioFormat.match(/AC-3/i) && commercialName.match(/Dolby Digital/i)) {
audioCodec = 'dd';
} else if (audioFormat.match(/AC-3/i)) {
audioCodec = 'ac3';
} else if (audioFormat.match(/DTS XLL X/i)) {
audioCodec = 'dtsx';
} else if (audioFormat.match(/DTS/i) && commercialName.match(/DTS-HD Master Audio/i)) {
audioCodec = 'dtshdma';
} else if (audioFormat.match(/DTS/i)) {
audioCodec = 'dts';
} else if (audioFormat.match(/FLAC/i)) {
audioCodec = 'flac';
} else if (audioFormat.match(/AAC/i)) {
audioCodec = 'aac';
} else if (audioFormat.match(/LPCM/i)) {
audioCodec = 'lpcm';
}
return {
audioCodec,
channelName,
languageArray,
};
};
const getInfoFromBDInfo = (bdInfo:string) => {
if (!bdInfo) {
return {};
}
const splitArray = bdInfo.split('Disc Title');
// 如果有多个bdinfo只取第一个
if (splitArray.length > 2) {
bdInfo = splitArray[1];
}
const videoMatch = bdInfo.match(/VIDEO:(\s|Codec|Bitrate|Description|Language|-)*((.|\n)*)AUDIO:/i);
const hasFileInfo = bdInfo.match(/FILES:/i);
const subtitleReg = new RegExp(`SUBTITLE(S)*:(\\s|Codec|Bitrate|Description|Language|-)*((.|\\n)*)${hasFileInfo ? 'FILES:' : ''}`, 'i');
const subtitleMatch = bdInfo.match(subtitleReg);
const audioReg = new RegExp(`AUDIO:(\\s|Codec|Bitrate|Description|Language|-)*((.|\\n)*)${subtitleMatch ? '(SUBTITLE(S)?)' : hasFileInfo ? 'FILES:' : ''}`, 'i');
const audioMatch = bdInfo.match(audioReg);
const fileSize = bdInfo.match(/Disc\s*Size:\s*((\d|,| )+)bytes/)?.[1]?.replace(/,/g, '');
const quickSummaryStyle = !bdInfo.match(/PLAYLIST REPORT/i); // 是否为bdinfo的另一种格式quickSummary
const videoPart = splitBDMediaInfo(videoMatch, 2);
const [mainVideo = '', otherVideo = ''] = videoPart;
const videoCodec = mainVideo.match(/2160/) ? 'hevc' : 'h264';
const hdrFormat = mainVideo.match(/\/\s*HDR(\d)*(\+)*\s*\//i)?.[0] ?? '';
const isDV = !!otherVideo.match(/\/\s*Dolby\s*Vision\s*/i);
const audioPart = splitBDMediaInfo(audioMatch, 2);
const subtitlePart = splitBDMediaInfo(subtitleMatch, 3);
const resolution = mainVideo.match(/\d{3,4}(p|i)/)?.[0];
const { audioCodec = '', channelName = '', languageArray = [] } = getBDAudioInfo(audioPart, quickSummaryStyle);
const subtitleLanguageArray = subtitlePart.map(item => {
const quickStyleMatch = item.match(/(\w+)\s*\//)?.[1] ?? '';
const normalMatch = item.match(/Graphics\s*(\w+)\s*(\d|\.)+\s*kbps/i)?.[1] ?? '';
const language = quickSummaryStyle ? quickStyleMatch : normalMatch;
return language;
}).filter(sub => !!sub);
const mediaTags = getMediaTags(audioCodec, channelName, languageArray, subtitleLanguageArray, hdrFormat, isDV);
return {
fileSize,
videoCodec,
subtitles: subtitleLanguageArray,
audioCodec,
resolution,
mediaTags,
format: 'm2ts',
};
};
const splitBDMediaInfo = (matchArray:string[]|null, matchIndex:number) => {
return matchArray?.[matchIndex]?.split('\n').filter(item => !!item) ?? [];
};
const getBDAudioInfo = (audioPart:string[], quickSummaryStyle:boolean) => {
if (audioPart.length < 1) {
return {};
}
const sortArray = audioPart.sort((a, b) => {
const firstBitrate = parseInt(a.match(/\/\s*(\d+)\s*kbps/i)?.[1] ?? '', 10);
const lastBitrate = parseInt(b.match(/\/\s*(\d+)\s*kbps/i)?.[1] ?? '', 10);
return lastBitrate - firstBitrate;
});
const [mainAudio, secondAudio] = sortArray;
const mainAudioCodec = getAudioCodecFromTitle(mainAudio);
const secondAudioCodec = getAudioCodecFromTitle(secondAudio);
let audioCodec = mainAudioCodec;
let channelName = mainAudio.match(/\d\.\d/)?.[0];
if (mainAudioCodec === 'lpcm' && secondAudioCodec === 'dtshdma') {
audioCodec = secondAudioCodec;
channelName = mainAudio.match(/\d\.\d/)?.[0];
}
const languageArray = sortArray.map(item => {
const quickStyleMatch = item.match(/(\w+)\s*\//)?.[1] ?? '';
const normalMatch = item.match(/Audio\s*(\w+)\s*\d+\s*kbps/)?.[1] ?? '';
const language = quickSummaryStyle ? quickStyleMatch : normalMatch;
return language;
});
return {
audioCodec,
channelName,
languageArray,
};
};
interface TagParam {
pre: (string|null)[]
post: (string|null|undefined)[]
}
const wrappingBBCodeTag = ({ pre, post }:TagParam, preTag:string|null, poTag?:string|null) => {
const isPre = typeof pre !== 'undefined' && pre !== null;
const isPost = typeof post !== 'undefined' && post !== null;
if (isPre) {
pre.unshift(preTag);
}
if (isPost) {
post.push(poTag);
}
};
// 过滤掉一些声明或者无意义文字
const getFilterBBCode = (content:Element) => {
if (content) {
const bbCodes = htmlToBBCode(content);
return bbCodes?.replace(/\[quote\]((.|\n)*?)\[\/quote\]/g, (match, p1) => {
if ((p1 && p1.match(/温馨提示|郑重|PT站|网上搜集|本种子|商业盈利|商业用途|带宽|寬帶|法律责任|Quote:|正版|商用|注明|后果|负责/))) {
return '';
}
return match;
}) ?? '';
}
return '';
};
const rgb2hex = (rgb:string) => {
const result = rgb?.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i) ?? [];
return (result.length === 4)
? `#${
(`0${parseInt(result[1], 10).toString(16)}`).slice(-2)
}${(`0${parseInt(result[2], 10).toString(16)}`).slice(-2)
}${(`0${parseInt(result[3], 10).toString(16)}`).slice(-2)}`
: '';
};
const ensureProperColor = (color:string) => {
if (/rgba?/.test(color)) return rgb2hex(color);
return color;
};
// html转BBCode代码
const htmlToBBCode = (node:Element) => {
const bbCodes :string[] = [];
const pre:string[] = [];
const post:string[] = [];
const pp = wrappingBBCodeTag.bind(null, { pre, post });
switch (node.nodeType) {
case 1: { // tag
switch (node.tagName.toUpperCase()) {
case 'SCRIPT': { return ''; }
case 'UL': { pp(null, null); break; }
case 'OL': { pp('[list=1]', '[/list]'); break; }
case 'LI': {
const { className } = node;
if (CURRENT_SITE_INFO.siteType === 'UNIT3D' && className) {
return `[quote]${node?.textContent?.trim()}[/quote]`;
}
pp('[*]', '\n'); break;
}
case 'B': { pp('[b]', '[/b]'); break; }
case 'U': { pp('[u]', '[/u]'); break; }
case 'I': { pp('[i]', '[/i]'); break; }
case 'DIV': {
const { className } = node;
if (className === 'codemain') {
// 兼容朋友
if (node.children[0] && node.children[0].tagName === 'PRE') {
pp('');
break;
} else {
node.innerHTML = node.innerHTML.replace(/ /g, ' ');
return `\n[quote]${node.textContent}[/quote]`;
}
} else if (className === 'hidden' && CURRENT_SITE_NAME === 'HDT') {
pp('\n[quote]', '[/quote]'); break;
} else if (className.match('spoiler') && CURRENT_SITE_NAME === 'KG') {
if (className === 'spoiler-content') {
pp('\n[quote]', '[/quote]');
} else if (className === 'spoiler-header') {
return '';
}
break;
} else if (CURRENT_SITE_NAME === 'BeyondHD') {
if (className === 'spoilerChild') {
pp('\n[quote]', '[/quote]');
} else if (className === 'spoilerHide') {
return '';
}
break;
} else if (className === 'spoiler-text' && CURRENT_SITE_INFO.siteType === 'AvistaZ') {
pp('\n[quote]', '[/quote]'); break;
} else if (className === 'spoiler-toggle' && CURRENT_SITE_INFO.siteType === 'AvistaZ') {
return '';
} else {
pp('\n', '\n'); break;
}
}
case 'P': { pp('\n'); break; }
case 'BR': {
if ((CURRENT_SITE_INFO.siteType === 'NexusPHP' && CURRENT_SITE_NAME !== 'OurBits') ||
CURRENT_SITE_NAME?.match(/^(UHDBits|HDBits|BTN)/)) {
pp('');
} else {
pp('\n');
}
break;
}
case 'SPAN': { pp(null, null); break; }
case 'BLOCKQUOTE':
case 'PRE':
case 'FIELDSET': {
pp('[quote]', '[/quote]'); break;
}
case 'CENTER': {
pp('[center]', '[/center]'); break;
}
case 'TD': {
if (CURRENT_SITE_NAME?.match(/^(TTG|HDBits|KG|HDSpace)/) || CURRENT_SITE_NAME === 'HDT' ||
CURRENT_SITE_INFO.siteType === 'UNIT3D') {
pp('[quote]', '[/quote]'); break;
} else if (CURRENT_SITE_NAME === 'EMP') {
pp(''); break;
} else {
return '';
}
}
case 'IMG': {
let imgUrl = '';
const { src, title } = node as HTMLImageElement;
const dataSrc = node.getAttribute('data-src') || node.getAttribute('data-echo');
// blu等unit3d站点会把:m:转成icon图片
if (title === ':m:') {
return ':m:';
}
if (dataSrc) {
imgUrl = dataSrc.match(/(http(s)?:)?\/\//) ? dataSrc : `${location.origin}/${dataSrc}`;
} else if (src && !src.match(/ico_\w+.gif|jinzhuan|thumbsup|kralimarko/)) {
imgUrl = src;
} else {
return '';
}
return `[img]${imgUrl}[/img]`;
}
case 'FONT': {
const { color, size } = node as HTMLFontElement;
if (color) {
pp(`[color=${ensureProperColor(color)}]`, '[/color]');
}
if (size) {
pp(`[size=${size}]`, '[/size]');
}
break;
}
case 'A': {
const { href, textContent } = node as HTMLLinkElement;
if (href && href.length > 0) {
if (CURRENT_SITE_NAME === 'HDSpace') {
const div = $(node).find('div');
if (div[0] && div.attr('id')) {
const imgUrl = div.find('img').attr('src');
return `[url=${href}][img]${imgUrl}[/img][/url]`;
}
} else if (href.match(/javascript:void/) || (textContent === 'show' && CURRENT_SITE_NAME === 'HDT')) {
return '';
} else {
pp(`[url=${href}]`, '[/url]');
}
}
break;
}
case 'H1': { pp('[b][size="7"]', '[/size][/b]\n'); break; }
case 'H2': { pp('[b][size="6"]', '[/size][/b]\n'); break; }
case 'H3': { pp('[b][size="5"]', '[/size][/b]\n'); break; }
case 'H4': { pp('[b][size="4"]', '[/size][/b]\n'); break; }
}
const { textAlign, fontWeight, fontStyle, textDecoration, color } = (node as HTMLElement).style;
if (textAlign) {
switch (textAlign.toUpperCase()) {
case 'LEFT': { pp('[left]', '[/left]'); break; }
case 'RIGHT': { pp('[right]', '[/right]'); break; }
case 'CENTER': { pp('[center]', '[/center]'); break; }
}
}
if (fontWeight === 'bold' || ~~fontWeight >= 600) {
pp('[b]', '[/b]');
}
if (fontStyle === 'italic') pp('[i]', '[/i]');
if (textDecoration === 'underline') pp('[u]', '[/u]');
if (color && color.trim() !== '') pp(`[color=${ensureProperColor(color)}]`, '[/color]');
break;
}
case 3: {
if (node?.textContent?.trim()?.match(/^(引用|Quote|代码|代碼|Show|Hide|Hidden text|Hidden content|\[show\]|\[Show\])/)) {
return '';
}
return node.textContent;
} // textNode
default: return null;
}
node.childNodes.forEach((node) => {
const code = htmlToBBCode(node as Element);
if (code) {
bbCodes.push(code);
}
});
return pre.concat(bbCodes).concat(post).join('');
};
htmlToBBCode(document.createElement('ul'));
const getTagsFromSubtitle = (title:string) => {
const tags: TorrentInfo.MediaTags = {};
if (title.match(/diy/i)) {
tags.diy = true;
}
if (title.match(/国配|国语|普通话|国粤/i) && !title.match(/多国语言/)) {
tags.chinese_audio = true;
}
if (title.match(/Atmos|杜比全景声/i)) {
tags.dolby_atoms = true;
}
if (title.match(/HDR/i)) {
if (title.match(/HDR10\+/i)) {
tags.hdr10_plus = true;
} else {
tags.hdr = true;
}
}
if (title.match(/DoVi|(Dolby\s*Vision)|杜比视界/i)) {
tags.dolby_vision = true;
}
if (title.match(/粤/i)) {
tags.cantonese_audio = true;
}
if (title.match(/简繁|繁简|繁体|简体|中字|中英|中文/i)) {
tags.chinese_subtitle = true;
}
if (title.match(/Criterion|CC标准/i)) {
tags.the_criterion_collection = true;
}
return tags;
};
const getBDInfoOrMediaInfo = (bbcode:string) => {
const quoteList = bbcode?.match(/\[quote\](.|\n)+?\[\/quote\]/g) ?? [];
let bdinfo = ''; let mediaInfo = '';
quoteList.forEach(quote => {
const quoteContent = quote.replace(/\[\/?quote\]/g, '').replace(/\u200D/g, '');
if (quoteContent.match(/Disc\s?Size|\.mpls/i)) {
bdinfo += quoteContent;
}
if (quoteContent.match(/(Unique\s*ID)|(Codec\s*ID)|(Stream\s*size)/i)) {
mediaInfo += quoteContent;
}
});
if (!bdinfo) {
bdinfo = bbcode.match(/Disc\s+(Info|Title|Label)[^[]+/i)?.[0] ?? '';
}
return {
bdinfo,
mediaInfo,
};
};
const replaceRegSymbols = (string:string) => {
return string.replace(/([*.?+$^[\](){}|\\/])/g, '\\$1');
};
// https://greasyfork.org/zh-CN/scripts/389810-rottentomatoes-utility-library-custom-api
const getRtIdFromTitle = async (title:string, tv:boolean, year:string) => {
console.log(title, year);
const MAX_YEAR_DIFF = 2;
tv = tv || false;
const yearVal = parseInt(year, 10) || 1800;
const url = `https://www.rottentomatoes.com/api/private/v2.0/search/?limit=2&q=${title}`;
const data = await fetch(url);
const movies = tv ? data.tvSeries : data.movies;
if (!Array.isArray(movies) || movies.length < 1) {
console.log('no search results');
return {};
}
const sorted = movies.concat();
if (year && sorted) {
sorted.sort((a, b) => {
if (Math.abs(a.year - yearVal) !== Math.abs(b.year - yearVal)) {
// Prefer closest year to the given one
return Math.abs(a.year - yearVal) - Math.abs(b.year - yearVal);
}
return b.year - a.year; // In a tie, later year should come first
});
}
// Search for matches with exact title in order of proximity by year
let bestMatch, closeMatch;
for (const m of sorted) {
m.title = m.title || m.name;
if (m.title.toLowerCase() === title.toLowerCase()) {
bestMatch = bestMatch || m;
console.log('bestMatch', bestMatch);
// RT often includes original titles in parentheses for foreign films, so only check if they start the same
} else if (m.title.toLowerCase().startsWith(title.toLowerCase())) {
closeMatch = closeMatch || m;
console.log('closeMatch', closeMatch);
}
if (bestMatch && closeMatch) {
break;
}
}
// Fall back on closest year match if within 2 years, or whatever the first result was.
// RT years are often one year later than imdb, or even two
const yearComp = (imdb: number, rt: number) => {
return rt - imdb <= MAX_YEAR_DIFF && imdb - rt < MAX_YEAR_DIFF;
};
if (yearVal && (!bestMatch || !yearComp(yearVal, bestMatch.year))) {
if (closeMatch && yearComp(yearVal, closeMatch.year)) {
bestMatch = closeMatch;
} else if (yearComp(yearVal, sorted[0].year)) {
bestMatch = sorted[0];
}
}
bestMatch = bestMatch || closeMatch || movies[0];
if (bestMatch) {
const id = bestMatch && bestMatch.url.replace(/\/s\d{2}\/?$/, ''); // remove season suffix from tv matches
const score = bestMatch?.meterScore ?? '0';
return {
id,
score,
};
}
console.log('no match found on rt');
return {};
};
const uploadToPtpImg = async (imgArray: Array<string | File>, isFiles: boolean = false) => {
try {
const apiKey = getValue('easy-seed.ptp-img-api-key', false);
if (!apiKey) {
Notification.open({
message: $t('ptpimg上传失败'),
description: $t('请到配置面板中填入ptpimg的api_key'),
});
return;
}
const options: RequestOptions = {
method: 'POST',
responseType: 'json',
};
if (isFiles) {
const formData = new FormData();
imgArray.forEach((img, index) => {
formData.append(`file-upload[${index}]`, img);
});
formData.append('api_key', apiKey);
options.data = formData;
} else {
const data = `link-upload=${imgArray.join('\n')}&api_key=${apiKey}`;
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
};
options.data = data;
}
interface PTPImg{
code:string
ext:string
}
const data:PTPImg[] = await fetch('https://ptpimg.me/upload.php', options);
if (!data) {
throw $t('上传失败,请重试');
}
let imgResultList = [];
if (data && data.length) {
imgResultList = data.map(img => {
return `https://ptpimg.me/${img.code}.${img.ext}`;
});
return imgResultList;
}
throw $t('上传失败,请重试');
} catch (error) {
handleError(error);
}
};
const $t = (key:string) => {
const languageKey = USE_CHINESE ? 'zh_CN' : 'en_US';
return i18nConfig[languageKey][key as keyof typeof i18nConfig.zh_CN] || key;
};
const urlToFile = async (url: string): Promise<File> => {
const filename = url.match(/\/([^/]+)$/)?.[1] ?? 'filename';
const data: Blob = await fetch(url, {
responseType: 'blob',
});
const file = new File([data], filename, { type: data.type });
return file;
};
const saveScreenshotsToPtpimg = async (imgArray: Array<string>) => {
try {
const isHdbHost = !!imgArray[0].match(/i\.hdbits\.org/);
const isPtpHost = !!imgArray[0].match(/ptpimg\.me/);
if (isPtpHost) {
throw $t('无需转存');
} else if (isHdbHost) {
const promiseArray = imgArray.map(item => {
return urlToFile(item);
});
const fileArray = await Promise.all(promiseArray);
const data = uploadToPtpImg(fileArray, true);
return data;
} else {
const data = await uploadToPtpImg(imgArray);
return data;
}
} catch (error) {
handleError(error);
}
};
const getValue = (key: string, needParse = true) => {
const data = <string>GM_getValue(key);
if (data && needParse) {
return JSON.parse(data);
}
return data;
};
const fetch = (url: string, options?: RequestOptions): Promise<any> => {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'GET',
url,
responseType: 'json',
...options,
onload: (res) => {
const { statusText, status, response } = res;
if (status !== 200) {
reject(new Error(statusText || `${status}`));
} else {
resolve(response);
}
},
ontimeout: () => {
reject(new Error('timeout'));
},
onerror: (error) => {
reject(error);
},
});
});
};
const getTvSeasonData = async (data:Douban.Season) => {
const { title: torrentTitle } = TORRENT_INFO;
const { season = '', title } = data;
if (season) {
const seasonNumber = torrentTitle.match(/S(?!eason)?0?(\d+)\.?(EP?\d+)?/i)?.[1] ?? '1';
if (parseInt(seasonNumber, 10) === 1) {
return data;
}
const query = title.replace(/第.+?季/, `第${seasonNumber}季`);
const response = await getDoubanIdByIMDB(query);
return response;
}
};
export {
getUrlParam,
formatTorrentTitle,
getAudioCodecFromTitle,
replaceEngName,
getSubTitle,
getAreaCode,
getBDType,
getTMDBIdByIMDBId,
getIMDBIdByUrl,
getSize,
getInfoFromMediaInfo,
getInfoFromBDInfo,
getSourceFromTitle,
htmlToBBCode,
getFilterBBCode,
getBDInfoOrMediaInfo,
getScreenshotsFromBBCode,
getTagsFromSubtitle,
getVideoCodecFromTitle,
transferImgs,
getDoubanInfo,
getDoubanIdByIMDB,
getPreciseCategory,
getAnotherDoubanInfo,
replaceRegSymbols,
getIMDBData,
getTMDBVideos,
getRtIdFromTitle,
getFilterImages,
uploadToPtpImg,
$t,
urlToFile,
getOriginalImgUrl,
saveScreenshotsToPtpimg,
fetch,
uploadToPixhost,
getValue,
getTvSeasonData,
getDoubanBookInfo,
}; | the_stack |
import ARToolKit from "./artoolkit/ARToolKit";
import ARToolKitCameraParam from "./artoolkit/ARToolKitCameraParam";
import { ARToolKitController } from "./artoolkit/ARToolKitController";
import * as THREE from "three";
import { Source } from "./THREEAR";
import { PatternMarker } from "./PatternMarker";
import { BarcodeMarker } from "./BarcodeMarker";
import cameraParametersData from "./artoolkit/CameraParameters";
export interface MarkerPositioningParameters {
smooth: boolean;
smoothCount: number;
smoothTolerance: number;
smoothThreshold: number;
}
export interface ControllerParameters {
source: Source;
positioning: MarkerPositioningParameters;
lostTimeout: number;
debug: boolean;
changeMatrixMode: "modelViewMatrix" | "cameraTransformMatrix";
detectionMode: "color" | "color_and_matrix" | "mono" | "mono_and_matrix";
matrixCodeType: string;
cameraParametersUrl: string | Uint8Array;
maxDetectionRate: number;
canvasWidth: number;
canvasHeight: number;
patternRatio: number;
imageSmoothingEnabled: boolean;
}
interface Markers {
pattern: PatternMarker[];
barcode: BarcodeMarker[];
}
/**
* The controller is returned from THREE ARs initialize method, in the returned promise.
* It provides methods for controlling AR state such as add markers to track and updating
* to check for markers in the current provided source (i.e. webcam, video, image).
* @param parameters parameters for determining things like detection mode and smoothing
*/
export class Controller extends THREE.EventDispatcher {
public postInit: Promise<any>;
public disposed: boolean;
public markers: Markers;
private parameters: ControllerParameters;
private arController: ARToolKitController | null;
private smoothMatrices: any[];
private _updatedAt: any;
private _artoolkitProjectionAxisTransformMatrix: any;
constructor(parameters: Partial<ControllerParameters>) {
if (!parameters.source) {
throw Error("Source must be provided");
}
super();
// handle default parameters
this.parameters = {
source: parameters.source,
changeMatrixMode: "modelViewMatrix",
lostTimeout: 1000,
// handle default parameters
positioning: {
// turn on/off camera smoothing
smooth: true,
// number of matrices to smooth tracking over, more = smoother but slower follow
smoothCount: 5,
// distance tolerance for smoothing, if smoothThreshold # of matrices are under tolerance, tracking will stay still
smoothTolerance: 0.01,
// threshold for smoothing, will keep still unless enough matrices are over tolerance
smoothThreshold: 2,
},
// debug - true if one should display artoolkit debug canvas, false otherwise
debug: false,
// the mode of detection - ['color', 'color_and_matrix', 'mono', 'mono_and_matrix']
detectionMode: "mono",
// type of matrix code - valid iif detectionMode end with 'matrix' -
// [3x3, 3x3_HAMMING63, 3x3_PARITY65, 4x4, 4x4_BCH_13_9_3, 4x4_BCH_13_5_5]
matrixCodeType: "3x3",
// url of the camera parameters
cameraParametersUrl: cameraParametersData,
// tune the maximum rate of pose detection in the source image
maxDetectionRate: 60,
// resolution of at which we detect pose in the source image
canvasWidth: 640,
canvasHeight: 480,
// the patternRatio inside the artoolkit marker - artoolkit only
patternRatio: 0.5,
// enable image smoothing or not for canvas copy - default to true
// https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/imageSmoothingEnabled
imageSmoothingEnabled: false,
};
// create the marker Root
// this.parameters.group.matrixAutoUpdate = false;
// this.parameters.group.visible = false;
this.markers = {
pattern: [],
barcode: [],
};
this.smoothMatrices = []; // last DEBOUNCE_COUNT modelViewMatrix
this.arController = null;
this._updatedAt = null;
this.setParameters(parameters);
this.disposed = false;
this.postInit = this.initialize();
}
public setParameters(parameters: any) {
if (!parameters) {
return;
}
for (const key in parameters) {
if (key) {
const newValue = parameters[key];
if (newValue === undefined) {
console.warn(key + "' parameter is undefined.");
continue;
}
const currentValue = (this.parameters as any)[key];
if (currentValue === undefined) {
console.warn(key + "' is not a property of this material.");
continue;
}
(this.parameters as any)[key] = newValue;
}
}
}
public onResize(renderer: THREE.WebGLRenderer) {
this.parameters.source.onResizeElement();
this.parameters.source.copyElementSizeTo(renderer.domElement);
if (this.arController !== null) {
this.parameters.source.copyElementSizeTo(this.arController.canvas);
}
}
public update(srcElement: any) {
// be sure arController is fully initialized
if (this.arController === null) {
return false;
}
// honor this.parameters.maxDetectionRate
const present = performance.now();
if (
this._updatedAt !== null &&
present - this._updatedAt < 1000 / this.parameters.maxDetectionRate
) {
return false;
}
this._updatedAt = present;
// mark all markers to invisible before processing this frame
this.markers.pattern.forEach((m) => (m.markerObject.visible = false));
this.markers.barcode.forEach((m) => (m.markerObject.visible = false));
// process this frame
this.arController.process(srcElement);
// Check if any markers have been lost after processing
this.checkForLostMarkers();
// return true as we processed the frame
return true;
}
public trackMarker(marker: PatternMarker | BarcodeMarker) {
if (marker instanceof PatternMarker) {
this.trackPatternMarker(marker);
} else if (marker instanceof BarcodeMarker) {
this.trackBarcode(marker);
}
}
public dispose() {
if (this.arController) {
this.arController.dispose();
this.arController = null;
this.disposed = true;
this.markers = {
pattern: [],
barcode: [],
};
}
}
private initialize() {
return new Promise((resolve, reject) => {
this.parameters.source
.initialize()
.then(() => {
this._initArtoolkit(() => {
const { camera, renderer } = this.parameters.source;
if (renderer !== null) {
// handle resize
window.addEventListener("resize", () => {
this.onResize(renderer);
});
this.onResize(renderer);
} else {
throw Error("Renderer is not defined");
}
if (camera !== null) {
camera.projectionMatrix.copy(this.getProjectionMatrix());
} else {
throw Error("Camera is not defined");
}
// dispatch event
this.dispatchEvent({
type: "initialized",
});
resolve(this);
});
})
.catch((error) => {
reject(error);
});
});
}
private _initArtoolkit(onCompleted: () => any) {
// set this._artoolkitProjectionAxisTransformMatrix to change artoolkit
// projection matrix axis to match usual` webgl one
this._artoolkitProjectionAxisTransformMatrix = new THREE.Matrix4();
this._artoolkitProjectionAxisTransformMatrix.multiply(
new THREE.Matrix4().makeRotationY(Math.PI)
);
this._artoolkitProjectionAxisTransformMatrix.multiply(
new THREE.Matrix4().makeRotationZ(Math.PI)
);
// get cameraParameters
const cameraParameters = new ARToolKitCameraParam(
this.parameters.cameraParametersUrl,
() => {
// init controller
this.arController = new ARToolKitController(
this.parameters.canvasWidth,
this.parameters.canvasHeight,
cameraParameters
);
// honor this.parameters.imageSmoothingEnabled
(this.arController
.ctx as any).mozImageSmoothingEnabled = this.parameters.imageSmoothingEnabled;
(this.arController
.ctx as any).webkitImageSmoothingEnabled = this.parameters.imageSmoothingEnabled;
(this.arController
.ctx as any).msImageSmoothingEnabled = this.parameters.imageSmoothingEnabled;
(this.arController
.ctx as any).imageSmoothingEnabled = this.parameters.imageSmoothingEnabled;
// honor this.parameters.debug
if (this.parameters.debug === true) {
this.arController.debugSetup();
this.arController.canvas.style.position = "absolute";
this.arController.canvas.style.top = "0px";
this.arController.canvas.style.opacity = "0.6";
this.arController.canvas.style.pointerEvents = "none";
this.arController.canvas.style.zIndex = "-1";
}
// setPatternDetectionMode
const detectionModes = {
color: ARToolKit.AR_TEMPLATE_MATCHING_COLOR,
color_and_matrix: ARToolKit.AR_TEMPLATE_MATCHING_COLOR_AND_MATRIX,
mono: ARToolKit.AR_TEMPLATE_MATCHING_MONO,
mono_and_matrix: ARToolKit.AR_TEMPLATE_MATCHING_MONO_AND_MATRIX,
};
const detectionMode = detectionModes[this.parameters.detectionMode];
this.arController.setPatternDetectionMode(detectionMode);
// setMatrixCodeType
const matrixCodeTypes: any = {
"3x3": ARToolKit.AR_MATRIX_CODE_3x3,
"3x3_HAMMING63": ARToolKit.AR_MATRIX_CODE_3x3_HAMMING63,
"3x3_PARITY65": ARToolKit.AR_MATRIX_CODE_3x3_PARITY65,
"4x4": ARToolKit.AR_MATRIX_CODE_4x4,
"4x4_BCH_13_9_3": ARToolKit.AR_MATRIX_CODE_4x4_BCH_13_9_3,
"4x4_BCH_13_5_5": ARToolKit.AR_MATRIX_CODE_4x4_BCH_13_5_5,
};
const matrixCodeType = matrixCodeTypes[this.parameters.matrixCodeType];
this.arController.setMatrixCodeType(matrixCodeType);
// set the patternRatio for artoolkit
this.arController.setPattRatio(this.parameters.patternRatio);
// set thresholding in artoolkit
// this seems to be the default
// arController.setThresholdMode(artoolkit.AR_LABELING_THRESH_MODE_MANUAL)
// adatative consume a LOT of cpu...
// arController.setThresholdMode(artoolkit.AR_LABELING_THRESH_MODE_AUTO_ADAPTIVE)
// arController.setThresholdMode(artoolkit.AR_LABELING_THRESH_MODE_AUTO_OTSU)
// check if arController is init
this.arController.setLogLevel(1);
this.arController.addEventListener("getMarker", (event: any) => {
this.handleMarkerDetection(event);
});
// notify
onCompleted();
},
(err: any) => {
throw err;
// onerror
}
);
return this;
}
private handleMarkerDetection(event: any) {
if (event.data.type === ARToolKit.BARCODE_MARKER) {
this.markers.barcode.forEach((barcodeMarker) => {
if (event.data.marker.idMatrix === barcodeMarker.barcodeValue) {
this.onMarkerFound(event, barcodeMarker);
}
});
} else if (event.data.type === ARToolKit.PATTERN_MARKER) {
this.markers.pattern.forEach((patternMarker) => {
if (event.data.marker.idPatt === patternMarker.id) {
this.onMarkerFound(event, patternMarker);
}
});
}
}
private checkForLostMarkers() {
[...this.markers.pattern, ...this.markers.barcode].forEach((marker) => {
if (
marker.lastDetected &&
marker.found &&
new Date().getTime() - marker.lastDetected.getTime() >
this.parameters.lostTimeout
) {
this.onMarkerLost(marker);
}
});
}
private getProjectionMatrix() {
// get projectionMatrixArr from artoolkit
const controller = this.arController as ARToolKitController;
const projectionMatrixArr = Array.from(controller.getCameraMatrix());
const projectionMatrix = new THREE.Matrix4().fromArray(projectionMatrixArr);
// apply context._axisTransformMatrix - change artoolkit axis to match usual webgl one
projectionMatrix.multiply(this._artoolkitProjectionAxisTransformMatrix);
// Hotfix for z-fighting bug
// somehow ARToolKitController.ts L1031 & L1032 don't work
const near = 0.1;
const far = 1000;
projectionMatrix.elements[10] = -(far + near) / (far - near);
projectionMatrix.elements[14] = -(2 * far * near) / (far - near);
// return the result
return projectionMatrix;
}
private trackPatternMarker(marker: PatternMarker) {
if (this.arController === null) {
return;
}
this.markers.pattern.push(marker);
// start tracking this pattern
const onSuccess = (markerId: number) => {
marker.id = markerId;
(this.arController as any).trackPatternMarkerId(markerId, marker.size);
};
const onError = (err: any) => {
throw Error(err);
};
if (marker.patternUrl) {
this.arController.loadMarker(marker.patternUrl, onSuccess, onError);
} else {
throw Error("No patternUrl defined in parameters");
}
}
private trackBarcode(marker: BarcodeMarker) {
if (this.arController === null) {
return;
}
this.markers.barcode.push(marker);
let barcodeMarkerId: number | null = null;
if (marker.barcodeValue !== undefined) {
barcodeMarkerId = marker.barcodeValue;
marker.id = barcodeMarkerId;
this.arController.trackBarcodeMarkerId(barcodeMarkerId, marker.size);
} else {
throw Error("No barcodeValue defined in parameters");
}
}
private onMarkerFound(event: any, marker: BarcodeMarker | PatternMarker) {
// Check to make sure that the minimum confidence is met
if (
event.data.type === ARToolKit.PATTERN_MARKER &&
event.data.marker.cfPatt < marker.minConfidence
) {
return;
}
if (
event.data.type === ARToolKit.BARCODE_MARKER &&
event.data.marker.cfMatt < marker.minConfidence
) {
return;
}
marker.found = true;
marker.lastDetected = new Date();
const modelViewMatrix = new THREE.Matrix4().fromArray(event.data.matrix);
this.updateWithModelViewMatrix(modelViewMatrix, marker.markerObject);
this.dispatchEvent({
type: "markerFound",
marker,
});
}
private onMarkerLost(marker: BarcodeMarker | PatternMarker) {
marker.found = false;
this.dispatchEvent({
type: "markerLost",
marker,
});
}
/**
* When you actually got a new modelViewMatrix, you need to perfom a whole bunch
* of things. it is done here.
*/
private updateWithModelViewMatrix(
modelViewMatrix: THREE.Matrix4,
markerObject: THREE.Object3D
): boolean {
// mark object as visible
// this.parameters.group.visible = true;
markerObject.visible = true;
// apply context._axisTransformMatrix - change artoolkit axis to match usual webgl one
const transformMatrix = this._artoolkitProjectionAxisTransformMatrix;
const tmpMatrix = new THREE.Matrix4().copy(transformMatrix);
tmpMatrix.multiply(modelViewMatrix);
modelViewMatrix.copy(tmpMatrix);
let renderRequired = false;
// change axis orientation on marker - artoolkit say Z is normal to the marker - ar.js say Y is normal to the marker
const markerAxisTransformMatrix = new THREE.Matrix4().makeRotationX(
Math.PI / 2
);
modelViewMatrix.multiply(markerAxisTransformMatrix);
// change this.parameters.group.matrix based on parameters.changeMatrixMode
if (this.parameters.changeMatrixMode === "modelViewMatrix") {
if (this.parameters.positioning.smooth) {
let averages: number[] = []; // average values for matrix over last smoothCount
let exceedsAverageTolerance = 0;
this.smoothMatrices.push(modelViewMatrix.elements.slice()); // add latest
if (
this.smoothMatrices.length <
this.parameters.positioning.smoothCount + 1
) {
markerObject.matrix.copy(modelViewMatrix); // not enough for average
} else {
this.smoothMatrices.shift(); // remove oldest entry
averages = [];
// loop over entries in matrix
for (let i = 0; i < modelViewMatrix.elements.length; i++) {
let sum = 0;
// calculate average for this entry
for (let j = 0; j < this.smoothMatrices.length; j++) {
sum += this.smoothMatrices[j][i];
}
averages[i] = sum / this.parameters.positioning.smoothCount;
// check how many elements vary from the average by at least AVERAGE_MATRIX_TOLERANCE
const vary = Math.abs(averages[i] - modelViewMatrix.elements[i]);
if (vary >= this.parameters.positioning.smoothTolerance) {
exceedsAverageTolerance++;
}
}
// if moving (i.e. at least AVERAGE_MATRIX_THRESHOLD
// entries are over AVERAGE_MATRIX_TOLERANCE
if (
exceedsAverageTolerance >=
this.parameters.positioning.smoothThreshold
) {
// then update matrix values to average, otherwise, don't render to minimize jitter
for (let i = 0; i < modelViewMatrix.elements.length; i++) {
modelViewMatrix.elements[i] = averages[i];
}
markerObject.matrix.copy(modelViewMatrix);
renderRequired = true; // render required in animation loop
}
}
} else {
markerObject.matrix.copy(modelViewMatrix);
}
// this.parameters.group.matrix.copy(modelViewMatrix);
} else if (this.parameters.changeMatrixMode === "cameraTransformMatrix") {
markerObject.matrix.getInverse(modelViewMatrix);
} else {
throw Error();
}
// decompose - the matrix into .position, .quaternion, .scale
markerObject.matrix.decompose(
markerObject.position,
markerObject.quaternion,
markerObject.scale
);
return renderRequired;
}
}
export default Controller; | the_stack |
import {DiagnosticKind, Log, Source, spanRanges} from "../../utils/log";
import {Token, TokenKind, tokenToString} from "../scanner/scanner";
import {Precedence} from "../parser/parser";
export enum PreprocessorValue {
FALSE,
TRUE,
ERROR,
}
export class PreprocessorFlag {
isDefined: boolean;
name: string;
next: PreprocessorFlag;
}
// This preprocessor implements the flag-only conditional behavior from C#.
// There are two scopes for flags: global-level and file-level. This is stored
// using an ever-growing linked list of PreprocessorFlag objects that turn a
// flag either on or off. That way file-level state can just reference the
// memory of the global-level state and the global-level state can easily be
// restored after parsing a file just by restoring the pointer.
export class Preprocessor {
firstFlag: PreprocessorFlag;
isDefineAndUndefAllowed: boolean;
previous: Token;
current: Token;
log: Log;
peek(kind: TokenKind): boolean {
return this.current.kind == kind;
}
eat(kind: TokenKind): boolean {
if (this.peek(kind)) {
this.advance();
return true;
}
return false;
}
advance(): void {
if (!this.peek(TokenKind.END_OF_FILE)) {
this.previous = this.current;
this.current = this.current.next;
}
}
unexpectedToken(): void {
this.log.error(this.current.range, `Unexpected ${tokenToString(this.current.kind)}`);
}
expect(kind: TokenKind): boolean {
if (!this.peek(kind)) {
this.log.error(
this.current.range,
`Expected ${tokenToString(kind)} but found ${tokenToString(this.current.kind)}`
);
return false;
}
this.advance();
return true;
}
removeTokensFrom(before: Token): void {
before.next = this.current;
this.previous = before;
}
isDefined(name: string): boolean {
var flag = this.firstFlag;
while (flag != null) {
if (flag.name == name) {
return flag.isDefined;
}
flag = flag.next;
}
return false;
}
define(name: string, isDefined: boolean): void {
var flag = new PreprocessorFlag();
flag.isDefined = isDefined;
flag.name = name;
flag.next = this.firstFlag;
this.firstFlag = flag;
}
run(source: Source, log: Log): void {
var firstToken = source.firstToken;
if (firstToken != null && firstToken.kind == TokenKind.PREPROCESSOR_NEEDED) {
var firstFlag = this.firstFlag;
// Initialize
this.isDefineAndUndefAllowed = true;
this.previous = firstToken;
this.current = firstToken.next;
this.log = log;
// Don't parse this file if preprocessing failed
if (!this.scan(true)) {
source.firstToken = null;
return;
}
// Make sure blocks are balanced
if (!this.peek(TokenKind.END_OF_FILE)) {
this.unexpectedToken();
}
// Restore the global-level state instead of letting the file-level state
// leak over into the next file that the preprocessor is run on
this.firstFlag = firstFlag;
// Skip over the PREPROCESSOR_NEEDED token so the parser doesn't see it
source.firstToken = source.firstToken.next;
}
}
// Scan over the next reachable tokens, evaluate #define/#undef directives,
// and fold #if/#else chains. Stop on #elif/#else/#endif. Return false on
// failure. Takes a booleanean flag for whether or not control flow is live in
// this block.
scan(isParentLive: boolean): boolean {
while (!this.peek(TokenKind.END_OF_FILE) &&
!this.peek(TokenKind.PREPROCESSOR_ELIF) &&
!this.peek(TokenKind.PREPROCESSOR_ELSE) &&
!this.peek(TokenKind.PREPROCESSOR_ENDIF)) {
var previous = this.previous;
var current = this.current;
// #define or #undef
if (this.eat(TokenKind.PREPROCESSOR_DEFINE) || this.eat(TokenKind.PREPROCESSOR_UNDEF)) {
// Only process the directive if control flow is live at this point
if (this.expect(TokenKind.IDENTIFIER) && isParentLive) {
this.define(this.previous.range.toString(), current.kind == TokenKind.PREPROCESSOR_DEFINE);
}
// Help out people trying to use this like C
if (this.eat(TokenKind.FALSE) || this.eat(TokenKind.INT32) && this.previous.range.toString() == "0") {
this.log.error(this.previous.range, "Use '#undef' to turn a preprocessor flag off");
}
// Scan up to the next newline
if (!this.peek(TokenKind.END_OF_FILE) && !this.expect(TokenKind.PREPROCESSOR_NEWLINE)) {
while (!this.eat(TokenKind.PREPROCESSOR_NEWLINE) && !this.eat(TokenKind.END_OF_FILE)) {
this.advance();
}
}
// These statements are only valid at the top of the file
if (!this.isDefineAndUndefAllowed) {
this.log.error(spanRanges(current.range, this.previous.range),
"All '#define' and '#undef' directives must be at the top of the file");
}
// Remove all of these tokens
this.removeTokensFrom(previous);
}
// #warning or #error
else if (this.eat(TokenKind.PREPROCESSOR_WARNING) || this.eat(TokenKind.PREPROCESSOR_ERROR)) {
var next = this.current;
// Scan up to the next newline
while (!this.peek(TokenKind.PREPROCESSOR_NEWLINE) && !this.peek(TokenKind.END_OF_FILE)) {
this.advance();
}
// Only process the directive if control flow is live at this point
if (isParentLive) {
var range = this.current == next ? current.range : spanRanges(next.range, this.previous.range);
this.log.append(range, range.toString(), current.kind == TokenKind.PREPROCESSOR_WARNING ? DiagnosticKind.WARNING : DiagnosticKind.ERROR);
}
// Remove all of these tokens
this.eat(TokenKind.PREPROCESSOR_NEWLINE);
this.removeTokensFrom(previous);
}
// #if
else if (this.eat(TokenKind.PREPROCESSOR_IF)) {
var isLive = isParentLive;
// Scan over the entire if-else chain
while (true) {
var condition = this.parseExpression(Precedence.LOWEST);
// Reject if the condition is missing
if (condition == PreprocessorValue.ERROR || !this.expect(TokenKind.PREPROCESSOR_NEWLINE)) {
return false;
}
// Remove the #if/#elif header
this.removeTokensFrom(previous);
// Scan to the next #elif, #else, or #endif
if (!this.scan(isLive && condition == PreprocessorValue.TRUE)) {
return false;
}
// Remove these tokens?
if (!isLive || condition == PreprocessorValue.FALSE) {
this.removeTokensFrom(previous);
}
// Keep these tokens but remove all subsequent branches
else {
isLive = false;
}
// Update the previous pointer so we remove from here next
previous = this.previous;
// #elif
if (this.eat(TokenKind.PREPROCESSOR_ELIF)) {
continue;
}
// #else
if (this.eat(TokenKind.PREPROCESSOR_ELSE)) {
if (!this.expect(TokenKind.PREPROCESSOR_NEWLINE)) {
return false;
}
// Remove the #else
this.removeTokensFrom(previous);
// Scan to the #endif
if (!this.scan(isLive)) {
return false;
}
// Remove these tokens?
if (!isLive) {
this.removeTokensFrom(previous);
}
}
// #endif
break;
}
// All if-else chains end with an #endif
previous = this.previous;
if (!this.expect(TokenKind.PREPROCESSOR_ENDIF) || !this.peek(TokenKind.END_OF_FILE) && !this.expect(TokenKind.PREPROCESSOR_NEWLINE)) {
return false;
}
this.removeTokensFrom(previous);
}
// Skip normal tokens
else {
this.isDefineAndUndefAllowed = false;
this.advance();
}
}
return true;
}
parsePrefix(): PreprocessorValue {
var isDefinedOperator = false;
var start = this.current;
// true or false
if (this.eat(TokenKind.TRUE)) return PreprocessorValue.TRUE;
if (this.eat(TokenKind.FALSE)) return PreprocessorValue.FALSE;
// Identifier
if (this.eat(TokenKind.IDENTIFIER)) {
var name = this.previous.range.toString();
// Recover from a C-style define operator
if (this.peek(TokenKind.LEFT_PARENTHESIS) && name == "defined") {
isDefinedOperator = true;
}
else {
var isTrue = this.isDefined(name);
return isTrue ? PreprocessorValue.TRUE : PreprocessorValue.FALSE;
}
}
// !
if (this.eat(TokenKind.NOT)) {
var value = this.parseExpression(Precedence.UNARY_PREFIX);
if (value == PreprocessorValue.ERROR) return PreprocessorValue.ERROR;
return value == PreprocessorValue.TRUE ? PreprocessorValue.FALSE : PreprocessorValue.TRUE;
}
// Group
if (this.eat(TokenKind.LEFT_PARENTHESIS)) {
let first = this.current;
let value = this.parseExpression(Precedence.LOWEST);
if (value == PreprocessorValue.ERROR || !this.expect(TokenKind.RIGHT_PARENTHESIS)) {
return PreprocessorValue.ERROR;
}
// Recover from a C-style define operator
if (isDefinedOperator) {
let errorMessage = "There is no 'defined' operator";
if (first.kind == TokenKind.IDENTIFIER && this.previous == first.next) {
errorMessage += " (just use '" + first.range.toString() + "' instead)";
}
this.log.error(spanRanges(start.range, this.previous.range), errorMessage);
}
return value;
}
// Recover from a C-style boolean
if (this.eat(TokenKind.INT32)) {
let isTrue = this.previous.range.toString() != "0";
this.log.error(
this.previous.range,
`Unexpected integer (did you mean ' ${isTrue ? "true" : "false"}')?`
);
return isTrue ? PreprocessorValue.TRUE : PreprocessorValue.FALSE;
}
this.unexpectedToken();
return PreprocessorValue.ERROR;
}
parseInfix(precedence: Precedence, left: PreprocessorValue): PreprocessorValue {
var operator = this.current.kind;
// == or !=
if (precedence < Precedence.EQUAL && (this.eat(TokenKind.EQUAL) || this.eat(TokenKind.NOT_EQUAL))) {
var right = this.parseExpression(Precedence.EQUAL);
if (right == PreprocessorValue.ERROR) return PreprocessorValue.ERROR;
return (operator == TokenKind.EQUAL) == (left == right) ? PreprocessorValue.TRUE : PreprocessorValue.FALSE;
}
// &&
if (precedence < Precedence.LOGICAL_AND && this.eat(TokenKind.LOGICAL_AND)) {
var right = this.parseExpression(Precedence.LOGICAL_AND);
if (right == PreprocessorValue.ERROR) return PreprocessorValue.ERROR;
return (left == PreprocessorValue.TRUE && right == PreprocessorValue.TRUE) ? PreprocessorValue.TRUE : PreprocessorValue.FALSE;
}
// ||
if (precedence < Precedence.LOGICAL_OR && this.eat(TokenKind.LOGICAL_OR)) {
var right = this.parseExpression(Precedence.LOGICAL_OR);
if (right == PreprocessorValue.ERROR) return PreprocessorValue.ERROR;
return (left == PreprocessorValue.TRUE || right == PreprocessorValue.TRUE) ? PreprocessorValue.TRUE : PreprocessorValue.FALSE;
}
// Hook
if (precedence == Precedence.LOWEST && this.eat(TokenKind.QUESTION_MARK)) {
var middle = this.parseExpression(Precedence.LOWEST);
if (middle == PreprocessorValue.ERROR || !this.expect(TokenKind.COLON)) {
return PreprocessorValue.ERROR;
}
var right = this.parseExpression(Precedence.LOWEST);
if (right == PreprocessorValue.ERROR) {
return PreprocessorValue.ERROR;
}
return left == PreprocessorValue.TRUE ? middle : right;
}
return left;
}
parseExpression(precedence: Precedence): PreprocessorValue {
// Prefix
var value = this.parsePrefix();
if (value == PreprocessorValue.ERROR) {
return PreprocessorValue.ERROR;
}
// Infix
while (true) {
var current = this.current;
value = this.parseInfix(precedence, value);
if (value == PreprocessorValue.ERROR) return PreprocessorValue.ERROR;
if (this.current == current) break;
}
return value;
}
} | the_stack |
import { Injectable } from '@angular/core';
import { PaginationConfig } from './config/pagination.config';
import {
PaginationItem,
PaginationItemType,
PaginationNavigationPosition,
PaginationOptions,
} from './pagination.model';
const FALLBACK_PAGINATION_OPTIONS: PaginationOptions = {
rangeCount: 3,
dotsLabel: '...',
startLabel: '«',
previousLabel: '‹',
nextLabel: '›',
endLabel: '»',
};
/**
* Builds a pagination structures based on a pageCount and current page number.
* There are various {@link PaginationConfig} options which can be used to configure
* the behavior of the build. Alternatively, CSS can be used to further customize
* the pagination.
*
* Examples:
* The full blown pagination items contain the follow elements:
*
* `« ‹ 1 ... 4 (5) 6 ... 9 › »`
*
* This includes pagination items to the following pages:
* - start page
* - previous page
* - first page
* - page range
* - last page
* - next page
* - end page
*
* All of those links are configurable, including the size of the page range.
* The current page will always be centered in the page range to provide direct access
* to the previous and next page.
*/
@Injectable({
providedIn: 'root',
})
export class PaginationBuilder {
constructor(protected paginationConfig: PaginationConfig) {}
/**
* Builds a list of `PaginationItem`. The give pageCount and current are used
* to build out the full pagination. There are various {@link PaginationConfig} options
* which can be used to configure the behavior of the build. Alternatively, CSS
* can be used to further specialize visibility of the pagination.
*
* @param pageCount The total number of pages
* @param current The current page number, 0-index based
* @returns An array of `PaginationItem`
*/
paginate(pageCount: number, current: number): PaginationItem[] {
const pages: PaginationItem[] = [];
if (!pageCount || pageCount < 2) {
return pages;
}
this.addPages(pages, pageCount, current);
this.addDots(pages, pageCount);
this.addFirstLast(pages, pageCount);
this.addNavigation(pages, pageCount, current);
return pages;
}
/**
* Returns the current page with surrounding pages (based on the `config.rangeCount`).
* The current page is always centered to provide direct access to the previous and next page.
*
* @param pages The list of page items that is used to amend
* @param pageCount The total number of pages
* @param current The current page number, 0-index based
*/
protected addPages(
pages: PaginationItem[],
pageCount: number,
current: number
): void {
const start = this.getStartOfRange(pageCount, current);
if (this.config.rangeCount !== undefined && start !== null) {
const max = Math.min(this.config.rangeCount, pageCount);
Array.from(Array(max)).forEach((_, i) => {
pages.push({
number: i + start,
label: String(i + start + 1),
type: PaginationItemType.PAGE,
});
});
}
}
/**
* Adds dots before and after the given pages, if configured (defaults to true).
* If the dots only represent a single page, the page number is added instead of
* the dots, unless the configuration requires dots always.
*
* @param pages The list of page items that is used to amend
* @param pageCount The total number of pages
*/
protected addDots(pages: PaginationItem[], pageCount: number): void {
if (!this.config.addDots) {
return;
}
const addFirstGap = () => {
const firstItemNumber = pages[0].number;
const gapNumber = this.config.addFirst ? 1 : 0;
if (firstItemNumber !== undefined && firstItemNumber > gapNumber) {
const isGap =
!this.config.substituteDotsForSingularPage ||
firstItemNumber !== gapNumber + 1;
const isSubstituted =
this.config.addFirst &&
this.config.substituteDotsForSingularPage &&
gapNumber === 0;
const type = isGap
? PaginationItemType.GAP
: isSubstituted
? PaginationItemType.FIRST
: PaginationItemType.PAGE;
return [
Object.assign(
{
label: isGap ? this.config.dotsLabel : String(gapNumber + 1),
type,
},
isGap ? null : { number: gapNumber }
),
];
} else return [];
};
const addLastGap = () => {
const pageNumber = pages[pages.length - 1].number;
const nextPageNumber = pageNumber ? pageNumber + 1 : undefined;
const last = pageCount - (this.config.addLast ? 2 : 1);
if (nextPageNumber && nextPageNumber <= last) {
const isSubstituted =
this.config.addLast &&
this.config.substituteDotsForSingularPage &&
nextPageNumber === last;
const isGap =
nextPageNumber <
pageCount -
(this.config.substituteDotsForSingularPage ? 1 : 0) -
(this.config.addLast ? 1 : 0);
const type = isGap
? PaginationItemType.GAP
: isSubstituted
? PaginationItemType.LAST
: PaginationItemType.PAGE;
return [
Object.assign(
{
label: isGap ? this.config.dotsLabel : String(nextPageNumber + 1),
type,
},
isGap ? null : { number: nextPageNumber }
),
];
} else return [];
};
pages.unshift(...addFirstGap());
pages.push(...addLastGap());
}
/**
* Add links to the first and last page, if configured to do so.
*
* @param pages The list of page items that is used to amend
* @param pageCount The total number of pages
*
*/
protected addFirstLast(pages: PaginationItem[], pageCount: number) {
if (this.config.addFirst && pages[0].number !== 0) {
pages.unshift({
number: 0,
label: '1',
type: PaginationItemType.FIRST,
});
}
if (
this.config.addLast &&
pages[pages.length - 1].number !== pageCount - 1
) {
pages.push({
number: pageCount - 1,
label: String(pageCount),
type: PaginationItemType.LAST,
});
}
}
/**
* Add links to the start, previous, next and last page, if configured to do so.
* The order of the links can be configured by using the {@link PaginationConfig},
* using the `PaginationNavigationPosition` (`BEFORE` or `AFTER`).
* The `PaginationNavigationPosition` allows for 3 flavours:
*
* - by default the pagination starts with start and previous and ends with the next and end links
* - BEFORE – all navigation links are added in the front of the pagination list
* - AFTER – all navigation links are pushed to the end of the pagination list
*
* @param pages The list of page items that is used to amend
* @param pageCount The total number of pages
* @param current The current page number, 0-index based
*
*/
protected addNavigation(
pages: PaginationItem[],
pageCount: number,
current: number
): void {
const before = this.getBeforeLinks(current);
const after = this.getAfterLinks(pageCount, current);
const pos = this.config.navigationPosition;
if (!pos || pos === PaginationNavigationPosition.ASIDE) {
pages.unshift(...before);
pages.push(...after);
} else {
if (pos === PaginationNavigationPosition.BEFORE) {
pages.unshift(...before, ...after);
}
if (pos === PaginationNavigationPosition.AFTER) {
pages.push(...before, ...after);
}
}
}
/**
* Returns the start and previous links, if applicable.
*/
protected getBeforeLinks(current: number): PaginationItem[] {
const list = [];
if (this.config.addStart) {
const start = () => {
return Object.assign(
{
label: this.config.startLabel,
type: PaginationItemType.START,
},
current > 0 ? { number: 0 } : null
);
};
list.push(start());
}
if (this.config.addPrevious) {
const previous = () => {
return Object.assign(
{
label: this.config.previousLabel,
type: PaginationItemType.PREVIOUS,
},
current > 0 ? { number: current - 1 } : null
);
};
list.push(previous());
}
return list;
}
/**
* Returns the next and end links, if applicable.
*/
protected getAfterLinks(
pageCount: number,
current: number
): PaginationItem[] {
const list = [];
if (this.config.addNext) {
const next = () => {
return Object.assign(
{
label: this.config.nextLabel,
type: PaginationItemType.NEXT,
},
current < pageCount - 1 ? { number: current + 1 } : null
);
};
list.push(next());
}
if (this.config.addEnd) {
const end = () => {
return Object.assign(
{
label: this.config.endLabel,
type: PaginationItemType.END,
},
current < pageCount - 1 ? { number: pageCount - 1 } : null
);
};
list.push(end());
}
return list;
}
/**
* Resolves the first page of the range we need to build.
* This is the page that is leading up to the range of the
* current page.
*
* @param pageCount The total number of pages.
* @param current The current page number, 0-index based.
*/
protected getStartOfRange(pageCount: number, current: number): number | null {
if (this.config.rangeCount !== undefined) {
const count = this.config.rangeCount - 1;
// the least number of pages before and after the current
const delta = Math.round(count / 2);
// ensure that we start with at least the first page
const minStart = Math.max(0, current - delta);
// ensures that we start with at least 1 and do not pass the last range
const maxStart = Math.max(0, pageCount - count - 1);
// ensure that we get at least a full range at the end
return Math.min(maxStart, minStart);
}
return null;
}
/**
* Returns the pagination configuration. The configuration is driven by the
* (default) application configuration.
*
* The default application is limited to adding the start and end link:
* ```ts
* addStart: true,
* addEnd: true
* ```
*
* The application configuration is however merged into the following static configuration:
* ```ts
* {
* rangeCount: 3,
* dotsLabel: '...',
* startLabel: '«',
* previousLabel: '‹',
* nextLabel: '›',
* endLabel: '»'
* }
* ```
*/
protected get config(): PaginationOptions {
return Object.assign(
FALLBACK_PAGINATION_OPTIONS,
this.paginationConfig.pagination
);
}
} | the_stack |
import type * as ts from 'typescript';
import * as lazy from 'lazy.js';
import { duplex, through } from 'event-stream';
import * as File from 'vinyl';
import * as sm from 'source-map';
import * as path from 'path';
declare class FileSourceMap extends File {
public sourceMap: sm.RawSourceMap;
}
enum CollectStepResult {
Yes,
YesAndRecurse,
No,
NoAndRecurse
}
function collect(ts: typeof import('typescript'), node: ts.Node, fn: (node: ts.Node) => CollectStepResult): ts.Node[] {
const result: ts.Node[] = [];
function loop(node: ts.Node) {
const stepResult = fn(node);
if (stepResult === CollectStepResult.Yes || stepResult === CollectStepResult.YesAndRecurse) {
result.push(node);
}
if (stepResult === CollectStepResult.YesAndRecurse || stepResult === CollectStepResult.NoAndRecurse) {
ts.forEachChild(node, loop);
}
}
loop(node);
return result;
}
function clone<T extends object>(object: T): T {
const result = <T>{};
for (const id in object) {
result[id] = object[id];
}
return result;
}
function template(lines: string[]): string {
let indent = '', wrap = '';
if (lines.length > 1) {
indent = '\t';
wrap = '\n';
}
return `/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
define([], [${wrap + lines.map(l => indent + l).join(',\n') + wrap}]);`;
}
/**
* Returns a stream containing the patched JavaScript and source maps.
*/
export function nls(): NodeJS.ReadWriteStream {
const input = through();
const output = input.pipe(through(function (f: FileSourceMap) {
if (!f.sourceMap) {
return this.emit('error', new Error(`File ${f.relative} does not have sourcemaps.`));
}
let source = f.sourceMap.sources[0];
if (!source) {
return this.emit('error', new Error(`File ${f.relative} does not have a source in the source map.`));
}
const root = f.sourceMap.sourceRoot;
if (root) {
source = path.join(root, source);
}
const typescript = f.sourceMap.sourcesContent![0];
if (!typescript) {
return this.emit('error', new Error(`File ${f.relative} does not have the original content in the source map.`));
}
_nls.patchFiles(f, typescript).forEach(f => this.emit('data', f));
}));
return duplex(input, output);
}
function isImportNode(ts: typeof import('typescript'), node: ts.Node): boolean {
return node.kind === ts.SyntaxKind.ImportDeclaration || node.kind === ts.SyntaxKind.ImportEqualsDeclaration;
}
module _nls {
interface INlsStringResult {
javascript: string;
sourcemap: sm.RawSourceMap;
nls?: string;
nlsKeys?: string;
}
interface ISpan {
start: ts.LineAndCharacter;
end: ts.LineAndCharacter;
}
interface ILocalizeCall {
keySpan: ISpan;
key: string;
valueSpan: ISpan;
value: string;
}
interface ILocalizeAnalysisResult {
localizeCalls: ILocalizeCall[];
nlsExpressions: ISpan[];
}
interface IPatch {
span: ISpan;
content: string;
}
function fileFrom(file: File, contents: string, path: string = file.path) {
return new File({
contents: Buffer.from(contents),
base: file.base,
cwd: file.cwd,
path: path
});
}
function mappedPositionFrom(source: string, lc: ts.LineAndCharacter): sm.MappedPosition {
return { source, line: lc.line + 1, column: lc.character };
}
function lcFrom(position: sm.Position): ts.LineAndCharacter {
return { line: position.line - 1, character: position.column };
}
class SingleFileServiceHost implements ts.LanguageServiceHost {
private file: ts.IScriptSnapshot;
private lib: ts.IScriptSnapshot;
constructor(ts: typeof import('typescript'), private options: ts.CompilerOptions, private filename: string, contents: string) {
this.file = ts.ScriptSnapshot.fromString(contents);
this.lib = ts.ScriptSnapshot.fromString('');
}
getCompilationSettings = () => this.options;
getScriptFileNames = () => [this.filename];
getScriptVersion = () => '1';
getScriptSnapshot = (name: string) => name === this.filename ? this.file : this.lib;
getCurrentDirectory = () => '';
getDefaultLibFileName = () => 'lib.d.ts';
readFile(path: string, _encoding?: string): string | undefined {
if (path === this.filename) {
return this.file.getText(0, this.file.getLength());
}
return undefined;
}
fileExists(path: string): boolean {
return path === this.filename;
}
}
function isCallExpressionWithinTextSpanCollectStep(ts: typeof import('typescript'), textSpan: ts.TextSpan, node: ts.Node): CollectStepResult {
if (!ts.textSpanContainsTextSpan({ start: node.pos, length: node.end - node.pos }, textSpan)) {
return CollectStepResult.No;
}
return node.kind === ts.SyntaxKind.CallExpression ? CollectStepResult.YesAndRecurse : CollectStepResult.NoAndRecurse;
}
function analyze(ts: typeof import('typescript'), contents: string, options: ts.CompilerOptions = {}): ILocalizeAnalysisResult {
const filename = 'file.ts';
const serviceHost = new SingleFileServiceHost(ts, Object.assign(clone(options), { noResolve: true }), filename, contents);
const service = ts.createLanguageService(serviceHost);
const sourceFile = ts.createSourceFile(filename, contents, ts.ScriptTarget.ES5, true);
// all imports
const imports = lazy(collect(ts, sourceFile, n => isImportNode(ts, n) ? CollectStepResult.YesAndRecurse : CollectStepResult.NoAndRecurse));
// import nls = require('vs/nls');
const importEqualsDeclarations = imports
.filter(n => n.kind === ts.SyntaxKind.ImportEqualsDeclaration)
.map(n => <ts.ImportEqualsDeclaration>n)
.filter(d => d.moduleReference.kind === ts.SyntaxKind.ExternalModuleReference)
.filter(d => (<ts.ExternalModuleReference>d.moduleReference).expression.getText() === '\'vs/nls\'');
// import ... from 'vs/nls';
const importDeclarations = imports
.filter(n => n.kind === ts.SyntaxKind.ImportDeclaration)
.map(n => <ts.ImportDeclaration>n)
.filter(d => d.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral)
.filter(d => d.moduleSpecifier.getText() === '\'vs/nls\'')
.filter(d => !!d.importClause && !!d.importClause.namedBindings);
const nlsExpressions = importEqualsDeclarations
.map(d => (<ts.ExternalModuleReference>d.moduleReference).expression)
.concat(importDeclarations.map(d => d.moduleSpecifier))
.map<ISpan>(d => ({
start: ts.getLineAndCharacterOfPosition(sourceFile, d.getStart()),
end: ts.getLineAndCharacterOfPosition(sourceFile, d.getEnd())
}));
// `nls.localize(...)` calls
const nlsLocalizeCallExpressions = importDeclarations
.filter(d => !!(d.importClause && d.importClause.namedBindings && d.importClause.namedBindings.kind === ts.SyntaxKind.NamespaceImport))
.map(d => (<ts.NamespaceImport>d.importClause!.namedBindings).name)
.concat(importEqualsDeclarations.map(d => d.name))
// find read-only references to `nls`
.map(n => service.getReferencesAtPosition(filename, n.pos + 1))
.flatten()
.filter(r => !r.isWriteAccess)
// find the deepest call expressions AST nodes that contain those references
.map(r => collect(ts, sourceFile, n => isCallExpressionWithinTextSpanCollectStep(ts, r.textSpan, n)))
.map(a => lazy(a).last())
.filter(n => !!n)
.map(n => <ts.CallExpression>n)
// only `localize` calls
.filter(n => n.expression.kind === ts.SyntaxKind.PropertyAccessExpression && (<ts.PropertyAccessExpression>n.expression).name.getText() === 'localize');
// `localize` named imports
const allLocalizeImportDeclarations = importDeclarations
.filter(d => !!(d.importClause && d.importClause.namedBindings && d.importClause.namedBindings.kind === ts.SyntaxKind.NamedImports))
.map(d => ([] as any[]).concat((<ts.NamedImports>d.importClause!.namedBindings!).elements))
.flatten();
// `localize` read-only references
const localizeReferences = allLocalizeImportDeclarations
.filter(d => d.name.getText() === 'localize')
.map(n => service.getReferencesAtPosition(filename, n.pos + 1))
.flatten()
.filter(r => !r.isWriteAccess);
// custom named `localize` read-only references
const namedLocalizeReferences = allLocalizeImportDeclarations
.filter(d => d.propertyName && d.propertyName.getText() === 'localize')
.map(n => service.getReferencesAtPosition(filename, n.name.pos + 1))
.flatten()
.filter(r => !r.isWriteAccess);
// find the deepest call expressions AST nodes that contain those references
const localizeCallExpressions = localizeReferences
.concat(namedLocalizeReferences)
.map(r => collect(ts, sourceFile, n => isCallExpressionWithinTextSpanCollectStep(ts, r.textSpan, n)))
.map(a => lazy(a).last())
.filter(n => !!n)
.map(n => <ts.CallExpression>n);
// collect everything
const localizeCalls = nlsLocalizeCallExpressions
.concat(localizeCallExpressions)
.map(e => e.arguments)
.filter(a => a.length > 1)
.sort((a, b) => a[0].getStart() - b[0].getStart())
.map<ILocalizeCall>(a => ({
keySpan: { start: ts.getLineAndCharacterOfPosition(sourceFile, a[0].getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, a[0].getEnd()) },
key: a[0].getText(),
valueSpan: { start: ts.getLineAndCharacterOfPosition(sourceFile, a[1].getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, a[1].getEnd()) },
value: a[1].getText()
}));
return {
localizeCalls: localizeCalls.toArray(),
nlsExpressions: nlsExpressions.toArray()
};
}
class TextModel {
private lines: string[];
private lineEndings: string[];
constructor(contents: string) {
const regex = /\r\n|\r|\n/g;
let index = 0;
let match: RegExpExecArray | null;
this.lines = [];
this.lineEndings = [];
while (match = regex.exec(contents)) {
this.lines.push(contents.substring(index, match.index));
this.lineEndings.push(match[0]);
index = regex.lastIndex;
}
if (contents.length > 0) {
this.lines.push(contents.substring(index, contents.length));
this.lineEndings.push('');
}
}
public get(index: number): string {
return this.lines[index];
}
public set(index: number, line: string): void {
this.lines[index] = line;
}
public get lineCount(): number {
return this.lines.length;
}
/**
* Applies patch(es) to the model.
* Multiple patches must be ordered.
* Does not support patches spanning multiple lines.
*/
public apply(patch: IPatch): void {
const startLineNumber = patch.span.start.line;
const endLineNumber = patch.span.end.line;
const startLine = this.lines[startLineNumber] || '';
const endLine = this.lines[endLineNumber] || '';
this.lines[startLineNumber] = [
startLine.substring(0, patch.span.start.character),
patch.content,
endLine.substring(patch.span.end.character)
].join('');
for (let i = startLineNumber + 1; i <= endLineNumber; i++) {
this.lines[i] = '';
}
}
public toString(): string {
return lazy(this.lines).zip(this.lineEndings)
.flatten().toArray().join('');
}
}
function patchJavascript(patches: IPatch[], contents: string, moduleId: string): string {
const model = new TextModel(contents);
// patch the localize calls
lazy(patches).reverse().each(p => model.apply(p));
// patch the 'vs/nls' imports
const firstLine = model.get(0);
const patchedFirstLine = firstLine.replace(/(['"])vs\/nls\1/g, `$1vs/nls!${moduleId}$1`);
model.set(0, patchedFirstLine);
return model.toString();
}
function patchSourcemap(patches: IPatch[], rsm: sm.RawSourceMap, smc: sm.SourceMapConsumer): sm.RawSourceMap {
const smg = new sm.SourceMapGenerator({
file: rsm.file,
sourceRoot: rsm.sourceRoot
});
patches = patches.reverse();
let currentLine = -1;
let currentLineDiff = 0;
let source: string | null = null;
smc.eachMapping(m => {
const patch = patches[patches.length - 1];
const original = { line: m.originalLine, column: m.originalColumn };
const generated = { line: m.generatedLine, column: m.generatedColumn };
if (currentLine !== generated.line) {
currentLineDiff = 0;
}
currentLine = generated.line;
generated.column += currentLineDiff;
if (patch && m.generatedLine - 1 === patch.span.end.line && m.generatedColumn === patch.span.end.character) {
const originalLength = patch.span.end.character - patch.span.start.character;
const modifiedLength = patch.content.length;
const lengthDiff = modifiedLength - originalLength;
currentLineDiff += lengthDiff;
generated.column += lengthDiff;
patches.pop();
}
source = rsm.sourceRoot ? path.relative(rsm.sourceRoot, m.source) : m.source;
source = source.replace(/\\/g, '/');
smg.addMapping({ source, name: m.name, original, generated });
}, null, sm.SourceMapConsumer.GENERATED_ORDER);
if (source) {
smg.setSourceContent(source, smc.sourceContentFor(source));
}
return JSON.parse(smg.toString());
}
function patch(ts: typeof import('typescript'), moduleId: string, typescript: string, javascript: string, sourcemap: sm.RawSourceMap): INlsStringResult {
const { localizeCalls, nlsExpressions } = analyze(ts, typescript);
if (localizeCalls.length === 0) {
return { javascript, sourcemap };
}
const nlsKeys = template(localizeCalls.map(lc => lc.key));
const nls = template(localizeCalls.map(lc => lc.value));
const smc = new sm.SourceMapConsumer(sourcemap);
const positionFrom = mappedPositionFrom.bind(null, sourcemap.sources[0]);
let i = 0;
// build patches
const patches = lazy(localizeCalls)
.map(lc => ([
{ range: lc.keySpan, content: '' + (i++) },
{ range: lc.valueSpan, content: 'null' }
]))
.flatten()
.map<IPatch>(c => {
const start = lcFrom(smc.generatedPositionFor(positionFrom(c.range.start)));
const end = lcFrom(smc.generatedPositionFor(positionFrom(c.range.end)));
return { span: { start, end }, content: c.content };
})
.toArray();
javascript = patchJavascript(patches, javascript, moduleId);
// since imports are not within the sourcemap information,
// we must do this MacGyver style
if (nlsExpressions.length) {
javascript = javascript.replace(/^define\(.*$/m, line => {
return line.replace(/(['"])vs\/nls\1/g, `$1vs/nls!${moduleId}$1`);
});
}
sourcemap = patchSourcemap(patches, sourcemap, smc);
return { javascript, sourcemap, nlsKeys, nls };
}
export function patchFiles(javascriptFile: File, typescript: string): File[] {
const ts = require('typescript') as typeof import('typescript');
// hack?
const moduleId = javascriptFile.relative
.replace(/\.js$/, '')
.replace(/\\/g, '/');
const { javascript, sourcemap, nlsKeys, nls } = patch(
ts,
moduleId,
typescript,
javascriptFile.contents.toString(),
(<any>javascriptFile).sourceMap
);
const result: File[] = [fileFrom(javascriptFile, javascript)];
(<any>result[0]).sourceMap = sourcemap;
if (nlsKeys) {
result.push(fileFrom(javascriptFile, nlsKeys, javascriptFile.path.replace(/\.js$/, '.nls.keys.js')));
}
if (nls) {
result.push(fileFrom(javascriptFile, nls, javascriptFile.path.replace(/\.js$/, '.nls.js')));
}
return result;
}
} | the_stack |
import { Vector3, TmpVectors } from "../Maths/math.vector";
import { Scalar } from '../Maths/math.scalar';
import { PHI } from '../Maths/math.constants';
import { _IsoVector } from '../Maths/math.isovector';
/**
* Class representing data for one face OAB of an equilateral icosahedron
* When O is the isovector (0, 0), A is isovector (m, n)
* @hidden
*/
export class _PrimaryIsoTriangle {
//properties
public m: number;
public n: number;
public cartesian: Vector3[] = [];
public vertices: _IsoVector[] = [];
public max: number[] = [];
public min: number[] = [];
public vecToIdx: {[key: string]: number};
public vertByDist: {[key: string]: number[]};
public closestTo: number[][] = [];
public innerFacets: string[][] = [];
public isoVecsABOB: _IsoVector[][] = [];
public isoVecsOBOA: _IsoVector[][] = [];
public isoVecsBAOA: _IsoVector[][] = [];
public vertexTypes: number[][] = [];
public coau: number;
public cobu: number;
public coav: number;
public cobv: number;
public IDATA: PolyhedronData = new PolyhedronData("icosahedron",
"Regular",
[ [0, PHI, -1], [-PHI, 1, 0], [-1, 0, -PHI], [1, 0, -PHI], [PHI, 1, 0], [0, PHI, 1], [-1, 0, PHI], [-PHI, -1, 0], [0, -PHI, -1], [PHI, -1, 0], [1, 0, PHI], [0, -PHI, 1]],
[
[ 0, 2, 1 ], [ 0, 3, 2 ], [ 0, 4, 3 ], [ 0, 5, 4 ], [ 0, 1, 5 ],
[ 7, 6, 1 ], [ 8, 7, 2 ], [ 9, 8, 3 ], [ 10, 9, 4 ], [ 6, 10, 5 ],
[ 2, 7, 1 ], [ 3, 8, 2 ], [ 4, 9, 3 ], [ 5, 10, 4 ], [ 1, 6, 5 ],
[ 11, 6, 7 ], [ 11, 7, 8 ], [ 11, 8, 9 ], [ 11, 9, 10 ], [ 11, 10, 6 ]
]
);
/**
* Creates the PrimaryIsoTriangle Triangle OAB
* @param m an integer
* @param n an integer
*/
//operators
public setIndices() {
let indexCount = 12; // 12 vertices already assigned
const vecToIdx: {[key: string]: number} = {}; //maps iso-vectors to indexCount;
const m = this.m;
const n = this.n;
let g = m; // hcf of m, n when n != 0
let m1 = 1;
let n1 = 0;
if (n !== 0) {
g = Scalar.HCF(m, n);
}
m1 = m / g;
n1 = n / g;
let fr: number | string; //face to the right of current face
let rot: number | string; //rotation about which vertex for fr
let O: number;
let A: number;
let B: number;
const Ovec: _IsoVector = _IsoVector.Zero();
const Avec = new _IsoVector(m, n);
const Bvec = new _IsoVector(-n, m + n);
let OAvec: _IsoVector = _IsoVector.Zero();
let ABvec: _IsoVector = _IsoVector.Zero();
let OBvec: _IsoVector = _IsoVector.Zero();
let verts: number[] = [];
let idx: string;
let idxR: string;
let isoId: string;
let isoIdR: string;
const closestTo: number[][] = [];
const vDist = this.vertByDist;
this.IDATA.edgematch = [ [1, "B"], [2, "B"], [3, "B"], [4, "B"], [0, "B"], [10, "O", 14, "A"], [11, "O", 10, "A"], [12, "O", 11, "A"], [13, "O", 12, "A"], [14, "O", 13, "A"], [0, "O"], [1, "O"], [2, "O"], [3, "O"], [4, "O"], [19, "B", 5, "A"], [15, "B", 6, "A"], [16, "B", 7, "A"], [17, "B", 8, "A"], [18, "B", 9, "A"] ];
/***edges AB to OB***** rotation about B*/
for (let f = 0; f < 20; f++) { //f current face
verts = this.IDATA.face[f];
O = verts[2];
A = verts[1];
B = verts[0];
isoId = Ovec.x + "|" + Ovec.y;
idx = f + "|" + isoId;
if (!(idx in vecToIdx)) {
vecToIdx[idx] = O;
closestTo[O] = [verts[vDist[isoId][0]], vDist[isoId][1]];
}
isoId = Avec.x + "|" + Avec.y;
idx = f + "|" + isoId;
if (!(idx in vecToIdx)) {
vecToIdx[idx] = A;
closestTo[A] = [verts[vDist[isoId][0]], vDist[isoId][1]];
}
isoId = Bvec.x + "|" + Bvec.y;
idx = f + "|" + isoId;
if (!(idx in vecToIdx)) {
vecToIdx[idx] = B;
closestTo[B] = [verts[vDist[isoId][0]], vDist[isoId][1]];
}
//for edge vertices
fr = <number>this.IDATA.edgematch[f][0];
rot = <string>this.IDATA.edgematch[f][1];
if (rot === "B") {
for (let i = 1; i < g; i++) {
ABvec.x = m - i * (m1 + n1);
ABvec.y = n + i * m1;
OBvec.x = -i * n1;
OBvec.y = i * (m1 + n1);
isoId = ABvec.x + "|" + ABvec.y;
isoIdR = OBvec.x + "|" + OBvec.y;
matchIdx(f, fr, isoId, isoIdR);
}
}
if (rot === "O") {
for (let i = 1; i < g; i++) {
OBvec.x = -i * n1;
OBvec.y = i * (m1 + n1);
OAvec.x = i * m1;
OAvec.y = i * n1;
isoId = OBvec.x + "|" + OBvec.y;
isoIdR = OAvec.x + "|" + OAvec.y;
matchIdx(f, fr, isoId, isoIdR);
}
}
fr = <number>this.IDATA.edgematch[f][2];
rot = <string>this.IDATA.edgematch[f][3];
if (rot && rot === "A") {
for (let i = 1; i < g; i++) {
OAvec.x = i * m1;
OAvec.y = i * n1;
ABvec.x = m - (g - i) * (m1 + n1); //reversed for BA
ABvec.y = n + (g - i) * m1; //reversed for BA
isoId = OAvec.x + "|" + OAvec.y;
isoIdR = ABvec.x + "|" + ABvec.y;
matchIdx(f, fr, isoId, isoIdR);
}
}
for (let i = 0; i < this.vertices.length; i++) {
isoId = this.vertices[i].x + "|" + this.vertices[i].y;
idx = f + "|" + isoId;
if (!(idx in vecToIdx)) {
vecToIdx[idx] = indexCount++;
if (vDist[isoId][0] > 2) {
closestTo[vecToIdx[idx]] = [-vDist[isoId][0], vDist[isoId][1], vecToIdx[idx]];
}
else {
closestTo[vecToIdx[idx]] = [verts[vDist[isoId][0]], vDist[isoId][1], vecToIdx[idx]];
}
}
}
}
function matchIdx(f: number, fr: number, isoId: string, isoIdR: string) {
idx = f + "|" + isoId;
idxR = fr + "|" + isoIdR;
if (!(idx in vecToIdx || idxR in vecToIdx)) {
vecToIdx[idx] = indexCount;
vecToIdx[idxR] = indexCount;
indexCount++;
}
else if ((idx in vecToIdx) && !(idxR in vecToIdx)) {
vecToIdx[idxR] = vecToIdx[idx];
}
else if ((idxR in vecToIdx) && !(idx in vecToIdx)) {
vecToIdx[idx] = vecToIdx[idxR];
}
if (vDist[isoId][0] > 2) {
closestTo[vecToIdx[idx]] = [-vDist[isoId][0], vDist[isoId][1], vecToIdx[idx]];
}
else {
closestTo[vecToIdx[idx]] = [verts[vDist[isoId][0]], vDist[isoId][1], vecToIdx[idx]];
}
}
this.closestTo = closestTo;
this.vecToIdx = vecToIdx;
}
public calcCoeffs() {
const m = this.m;
const n = this.n;
const thirdR3 = Math.sqrt(3) / 3;
const LSQD = m * m + n * n + m * n;
this.coau = (m + n) / LSQD;
this.cobu = -n / LSQD;
this.coav = -thirdR3 * (m - n) / LSQD;
this.cobv = thirdR3 * (2 * m + n) / LSQD;
}
public createInnerFacets() {
const m = this.m;
const n = this.n;
for (let y = 0; y < n + m + 1; y++) {
for (let x = this.min[y]; x < this.max[y] + 1; x++) {
if (x < this.max[y] && x < this.max[y + 1] + 1) {
this.innerFacets.push(["|" + x + "|" + y, "|" + x + "|" + (y + 1), "|" + (x + 1) + "|" + y]);
}
if (y > 0 && x < this.max[y - 1] && x + 1 < this.max[y] + 1) {
this.innerFacets.push(["|" + x + "|" + y, "|" + (x + 1) + "|" + y, "|" + (x + 1) + "|" + (y - 1)]);
}
}
}
}
public edgeVecsABOB() {
let m = this.m;
let n = this.n;
const B = new _IsoVector(-n, m + n);
for (let y = 1; y < m + n; y++) {
const point = new _IsoVector(this.min[y], y);
const prev = new _IsoVector(this.min[y - 1], y - 1);
const next = new _IsoVector(this.min[y + 1], y + 1);
const pointR = point.clone();
const prevR = prev.clone();
const nextR = next.clone();
pointR.rotate60About(B);
prevR.rotate60About(B);
nextR.rotate60About(B);
const maxPoint = new _IsoVector(this.max[pointR.y], pointR.y);
const maxPrev = new _IsoVector(this.max[pointR.y - 1], pointR.y - 1);
const maxLeftPrev = new _IsoVector(this.max[pointR.y - 1] - 1, pointR.y - 1);
if ((pointR.x !== maxPoint.x) || (pointR.y !== maxPoint.y)) {
if (pointR.x !== maxPrev.x) { // type2
//up
this.vertexTypes.push([1, 0, 0]);
this.isoVecsABOB.push([point, maxPrev, maxLeftPrev]);
//down
this.vertexTypes.push([1, 0, 0]);
this.isoVecsABOB.push([point, maxLeftPrev, maxPoint]);
}
else if (pointR.y === nextR.y) { // type1
//up
this.vertexTypes.push([1, 1, 0]);
this.isoVecsABOB.push([point, prev, maxPrev]);
//down
this.vertexTypes.push([1, 0, 1]);
this.isoVecsABOB.push([point, maxPrev, next]);
}
else { // type 0
//up
this.vertexTypes.push([1, 1, 0]);
this.isoVecsABOB.push([point, prev, maxPrev]);
//down
this.vertexTypes.push([1, 0, 0]);
this.isoVecsABOB.push([point, maxPrev, maxPoint]);
}
}
}
}
public mapABOBtoOBOA() {
const point = new _IsoVector(0, 0);
for (let i = 0; i < this.isoVecsABOB.length; i++) {
const temp = [];
for (let j = 0; j < 3; j++) {
point.x = this.isoVecsABOB[i][j].x;
point.y = this.isoVecsABOB[i][j].y;
if (this.vertexTypes[i][j] === 0) {
point.rotateNeg120(this.m, this.n);
}
temp.push(point.clone());
}
this.isoVecsOBOA.push(temp);
}
}
public mapABOBtoBAOA() {
const point = new _IsoVector(0, 0);
for (let i = 0; i < this.isoVecsABOB.length; i++) {
const temp = [];
for (let j = 0; j < 3; j++) {
point.x = this.isoVecsABOB[i][j].x;
point.y = this.isoVecsABOB[i][j].y;
if (this.vertexTypes[i][j] === 1) {
point.rotate120(this.m, this.n);
}
temp.push(point.clone());
}
this.isoVecsBAOA.push(temp);
}
}
public MapToFace(faceNb: number, geodesicData: PolyhedronData) {
const F = this.IDATA.face[faceNb];
const Oidx = F[2];
const Aidx = F[1];
const Bidx = F[0];
const O = Vector3.FromArray(this.IDATA.vertex[Oidx]);
const A = Vector3.FromArray(this.IDATA.vertex[Aidx]);
const B = Vector3.FromArray(this.IDATA.vertex[Bidx]);
const OA = A.subtract(O);
const OB = B.subtract(O);
let x: Vector3 = OA.scale(this.coau).add(OB.scale(this.cobu));
let y: Vector3 = OA.scale(this.coav).add(OB.scale(this.cobv));
const mapped = [];
let idx: string;
let tempVec: Vector3 = TmpVectors.Vector3[0];
for (var i = 0; i < this.cartesian.length; i++) {
tempVec = x.scale(this.cartesian[i].x).add(y.scale(this.cartesian[i].y)).add(O);
mapped[i] = [tempVec.x, tempVec.y, tempVec.z];
idx = faceNb + "|" + this.vertices[i].x + "|" + this.vertices[i].y;
geodesicData.vertex[this.vecToIdx[idx]] = [tempVec.x, tempVec.y, tempVec.z];
}
}
//statics
/**Creates a primary triangle
* @param m
* @param n
* @hidden
*/
public build(m: number, n: number) {
const vertices = new Array<_IsoVector>();
const O: _IsoVector = _IsoVector.Zero();
const A: _IsoVector = new _IsoVector(m, n);
const B: _IsoVector = new _IsoVector(-n, m + n);
vertices.push(O, A, B);
//max internal isoceles triangle vertices
for (let y = n; y < m + 1 ; y++) {
for (let x = 0; x < m + 1 - y; x++) {
vertices.push(new _IsoVector(x, y));
}
}
//shared vertices along edges when needed
if (n > 0) {
const g = Scalar.HCF(m, n);
const m1 = m / g;
const n1 = n / g;
for (let i = 1; i < g; i++) {
vertices.push(new _IsoVector(i * m1, i * n1)); //OA
vertices.push(new _IsoVector(-i * n1, i * (m1 + n1))); //OB
vertices.push(new _IsoVector(m - i * (m1 + n1), n + i * m1)); // AB
}
//lower rows vertices and their rotations
const ratio = m / n;
for (let y = 1; y < n; y++) {
for (let x = 0; x < y * ratio; x++) {
vertices.push(new _IsoVector(x, y));
vertices.push(new _IsoVector(x, y).rotate120(m , n));
vertices.push(new _IsoVector(x, y).rotateNeg120(m , n));
}
}
}
//order vertices by x and then y
vertices.sort((a, b) => {
return a.x - b.x;
});
vertices.sort((a, b) => {
return a.y - b.y;
});
let min = new Array<number>(m + n + 1);
let max = new Array<number>(m + n + 1);
for (let i = 0; i < min.length; i++) {
min[i] = Infinity;
max[i] = -Infinity;
}
let y: number = 0;
let x: number = 0;
let len: number = vertices.length;
for (let i = 0; i < len; i++) {
x = vertices[i].x;
y = vertices[i].y;
min[y] = Math.min(x, min[y]);
max[y] = Math.max(x, max[y]);
}
//calculates the distance of a vertex from a given primary vertex
const distFrom = (vert: _IsoVector, primVert: string) => {
const v = vert.clone();
if (primVert === "A") {
v.rotateNeg120(m, n);
}
if (primVert === "B") {
v.rotate120(m, n);
}
if (v.x < 0) {
return v.y;
}
return v.x + v.y;
};
const cartesian: Vector3[] = [];
const distFromO: number[] = [];
const distFromA: number[] = [];
const distFromB: number[] = [];
const vertByDist: {[key: string]: number[]} = {};
const vertData: number[][] = [];
let closest: number = -1;
let dist: number = -1;
for (let i = 0; i < len; i++) {
cartesian[i] = vertices[i].toCartesianOrigin(new _IsoVector(0, 0), 0.5);
distFromO[i] = distFrom(vertices[i], "O");
distFromA[i] = distFrom(vertices[i], "A");
distFromB[i] = distFrom(vertices[i], "B");
if ((distFromO[i] === distFromA[i]) && (distFromA[i] === distFromB[i])) {
closest = 3;
dist = distFromO[i];
}
else if (distFromO[i] === distFromA[i]) {
closest = 4;
dist = distFromO[i];
}
else if (distFromA[i] === distFromB[i]) {
closest = 5;
dist = distFromA[i];
}
else if (distFromB[i] === distFromO[i]) {
closest = 6;
dist = distFromO[i];
}
if (distFromO[i] < distFromA[i] && distFromO[i] < distFromB[i]) {
closest = 2;
dist = distFromO[i];
}
if (distFromA[i] < distFromO[i] && distFromA[i] < distFromB[i]) {
closest = 1;
dist = distFromA[i];
}
if (distFromB[i] < distFromA[i] && distFromB[i] < distFromO[i]) {
closest = 0;
dist = distFromB[i];
}
vertData.push([closest, dist, vertices[i].x, vertices[i].y]);
}
vertData.sort((a, b) => {
return a[2] - b[2];
});
vertData.sort((a, b) => {
return a[3] - b[3];
});
vertData.sort((a, b) => {
return a[1] - b[1];
});
vertData.sort((a, b) => {
return a[0] - b[0];
});
for (let v = 0; v < vertData.length; v++) {
vertByDist[vertData[v][2] + "|" + vertData[v][3]] = [vertData[v][0], vertData[v][1], v];
}
this.m = m;
this.n = n;
this.vertices = vertices;
this.vertByDist = vertByDist;
this.cartesian = cartesian;
this.min = min;
this.max = max;
return this;
}
}
/** Builds Polyhedron Data
* @hidden
*/
export class PolyhedronData {
public edgematch: (number | string)[][];
constructor (
public name: string,
public category : string,
public vertex: number[][],
public face: number[][]
) {
}
}
/**
* This class Extends the PolyhedronData Class to provide measures for a Geodesic Polyhedron
*/
export class GeodesicData extends PolyhedronData{
/**
* @hidden
*/
public edgematch: (number | string)[][];
/**
* @hidden
*/
public adjacentFaces: number[][];
/**
* @hidden
*/
public sharedNodes: number;
/**
* @hidden
*/
public poleNodes: number;
/**
* @hidden
*/
public innerToData(face : number, primTri: _PrimaryIsoTriangle) {
for (let i = 0; i < primTri.innerFacets.length; i++) {
this.face.push(primTri.innerFacets[i].map((el) => primTri.vecToIdx[face + el]));
}
}
/**
* @hidden
*/
public mapABOBtoDATA(faceNb: number, primTri: _PrimaryIsoTriangle) {
const fr = primTri.IDATA.edgematch[faceNb][0];
for (let i = 0; i < primTri.isoVecsABOB.length; i++) {
const temp = [];
for (let j = 0; j < 3; j++) {
if (primTri.vertexTypes[i][j] === 0) {
temp.push(faceNb + "|" + primTri.isoVecsABOB[i][j].x + "|" + primTri.isoVecsABOB[i][j].y);
}
else {
temp.push(fr + "|" + primTri.isoVecsABOB[i][j].x + "|" + primTri.isoVecsABOB[i][j].y);
}
}
this.face.push([primTri.vecToIdx[temp[0]], primTri.vecToIdx[temp[1]], primTri.vecToIdx[temp[2]]]);
}
}
/**
* @hidden
*/
public mapOBOAtoDATA(faceNb: number, primTri: _PrimaryIsoTriangle) {
const fr = primTri.IDATA.edgematch[faceNb][0];
for (let i = 0; i < primTri.isoVecsOBOA.length; i++) {
const temp = [];
for (let j = 0; j < 3; j++) {
if (primTri.vertexTypes[i][j] === 1) {
temp.push(faceNb + "|" + primTri.isoVecsOBOA[i][j].x + "|" + primTri.isoVecsOBOA[i][j].y);
}
else {
temp.push(fr + "|" + primTri.isoVecsOBOA[i][j].x + "|" + primTri.isoVecsOBOA[i][j].y);
}
}
this.face.push([primTri.vecToIdx[temp[0]], primTri.vecToIdx[temp[1]], primTri.vecToIdx[temp[2]]]);
}
}
/**
* @hidden
*/
public mapBAOAtoDATA(faceNb: number, primTri: _PrimaryIsoTriangle) {
const fr = primTri.IDATA.edgematch[faceNb][2];
for (let i = 0; i < primTri.isoVecsBAOA.length; i++) {
const temp = [];
for (let j = 0; j < 3; j++) {
if (primTri.vertexTypes[i][j] === 1) {
temp.push(faceNb + "|" + primTri.isoVecsBAOA[i][j].x + "|" + primTri.isoVecsBAOA[i][j].y);
}
else {
temp.push(fr + "|" + primTri.isoVecsBAOA[i][j].x + "|" + primTri.isoVecsBAOA[i][j].y);
}
}
this.face.push([primTri.vecToIdx[temp[0]], primTri.vecToIdx[temp[1]], primTri.vecToIdx[temp[2]]]);
}
}
/**
* @hidden
*/
public orderData(primTri: _PrimaryIsoTriangle) {
const nearTo: number[][][] = [];
for (let i = 0; i < 13; i++) {
nearTo[i] = [];
}
const close: number[][] = primTri.closestTo;
for (let i = 0; i < close.length; i++) {
if (close[i][0] > -1) {
if (close[i][1] > 0) {
nearTo[close[i][0]].push([i, close[i][1]]);
}
}
else {
nearTo[12].push([i, close[i][0]]);
}
}
const near: number[] = [];
for (let i = 0; i < 12; i++) {
near[i] = i;
}
let nearIndex = 12;
for (let i = 0; i < 12; i++) {
nearTo[i].sort((a: number[], b: number[]) => {
return a[1] - b[1];
});
for (let j = 0; j < nearTo[i].length; j++) {
near[nearTo[i][j][0]] = nearIndex++;
}
}
for (let j = 0; j < nearTo[12].length; j++) {
near[nearTo[12][j][0]] = nearIndex++;
}
for (let i = 0; i < this.vertex.length; i++) {
this.vertex[i].push(near[i]);
}
this.vertex.sort((a, b) => {
return a[3] - b[3];
});
for (let i = 0; i < this.vertex.length; i++) {
this.vertex[i].pop();
}
for (let i = 0; i < this.face.length; i++) {
for (let j = 0; j < this.face[i].length; j++) {
this.face[i][j] = near[this.face[i][j]];
}
}
this.sharedNodes = nearTo[12].length;
this.poleNodes = this.vertex.length - this.sharedNodes;
}
/**
* @hidden
*/
public setOrder(m: number, faces: number[]) {
const adjVerts: number[] = [];
const dualFaces: number[] = [];
let face: number = <number>faces.pop();
dualFaces.push(face);
let index = this.face[face].indexOf(m);
index = (index + 2) % 3;
let v = this.face[face][index];
adjVerts.push(v);
let f = 0;
while (faces.length > 0) {
face = faces[f];
if (this.face[face].indexOf(v) > -1) { // v is a vertex of face f
index = (this.face[face].indexOf(v) + 1) % 3;
v = this.face[face][index];
adjVerts.push(v);
dualFaces.push(face);
faces.splice(f, 1);
f = 0;
}
else {
f++;
}
}
this.adjacentFaces.push(adjVerts);
return dualFaces;
}
/**
* @hidden
*/
public toGoldbergData(): PolyhedronData {
const goldbergData: PolyhedronData = new PolyhedronData("GeoDual", "Goldberg", [], []);
goldbergData.name = "GD dual";
const verticesNb: number = this.vertex.length;
const map = new Array(verticesNb);
for (let v = 0; v < verticesNb; v++) {
map[v] = [];
}
for (let f = 0; f < this.face.length; f++) {
for (let i = 0; i < 3; i++) {
map[this.face[f][i]].push(f);
}
}
let cx = 0;
let cy = 0;
let cz = 0;
let face = [];
let vertex = [];
this.adjacentFaces = [];
for (let m = 0; m < map.length; m++) {
goldbergData.face[m] = this.setOrder(m, map[m].concat([]));
map[m].forEach((el: number) => {
cx = 0;
cy = 0;
cz = 0;
face = this.face[el];
for (let i = 0; i < 3; i++) {
vertex = this.vertex[face[i]];
cx += vertex[0];
cy += vertex[1];
cz += vertex[2];
}
goldbergData.vertex[el] = [cx / 3, cy / 3, cz / 3];
});
}
return goldbergData;
}
//statics
/**Builds the data for a Geodesic Polyhedron from a primary triangle
* @param primTri the primary triangle
* @hidden
*/
public static BuildGeodesicData(primTri: _PrimaryIsoTriangle) {
const geodesicData = new GeodesicData("Geodesic-m-n", "Geodesic", [ [0, PHI, -1], [-PHI, 1, 0], [-1, 0, -PHI], [1, 0, -PHI], [PHI, 1, 0], [0, PHI, 1], [-1, 0, PHI], [-PHI, -1, 0], [0, -PHI, -1], [PHI, -1, 0], [1, 0, PHI], [0, -PHI, 1]], []);
primTri.setIndices();
primTri.calcCoeffs();
primTri.createInnerFacets();
primTri.edgeVecsABOB();
primTri.mapABOBtoOBOA();
primTri.mapABOBtoBAOA();
for (let f = 0; f < primTri.IDATA.face.length; f++) {
primTri.MapToFace(f, geodesicData);
geodesicData.innerToData(f, primTri);
if (primTri.IDATA.edgematch[f][1] === "B") {
geodesicData.mapABOBtoDATA(f, primTri);
}
if (primTri.IDATA.edgematch[f][1] === "O") {
geodesicData.mapOBOAtoDATA(f, primTri);
}
if (primTri.IDATA.edgematch[f][3] === "A") {
geodesicData.mapBAOAtoDATA(f, primTri);
}
}
geodesicData.orderData(primTri);
const radius = 1;
geodesicData.vertex = geodesicData.vertex.map(function (el) {
var a = el[0];
var b = el[1];
var c = el[2];
var d = Math.sqrt(a * a + b * b + c * c);
el[0] *= radius / d;
el[1] *= radius / d;
el[2] *= radius / d;
return el;
});
return geodesicData;
}
} | the_stack |
import { Directive, ElementRef, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { Point } from './../models/point';
import { RaphaelBase } from './../raphael-base';
import { RaphaelService } from './../raphael.service';
/**
* Directive selectors without adf- prefix will be deprecated on 3.0.0
*/
@Directive({selector: 'adf-raphael-icon-alfresco-publish, raphael-icon-alfresco-publish'})
export class RaphaelIconAlfrescoPublishDirective extends RaphaelBase implements OnInit {
@Input()
paper: any;
@Input()
position: Point;
@Input()
text: string;
@Output()
error = new EventEmitter();
@Input()
strokeWidth: number;
@Input()
fillColors: any;
@Input()
stroke: any;
@Input()
fillOpacity: any;
constructor(public elementRef: ElementRef,
raphaelService: RaphaelService) {
super(elementRef, raphaelService);
}
ngOnInit() {
this.draw(this.position);
}
public draw(position: Point) {
const startX = position.x + 2;
const startY = position.y + 2;
let path1 = this.paper.path(`M4.11870968,2.12890323 L6.12954839,0.117935484 L3.10993548,0.118064516 L3.10270968,0.118064516
C1.42941935,0.118064516 0.0729032258,1.47458065 0.0729032258,3.14774194 C0.0729032258,4.82116129 1.42929032,6.17754839
3.10258065,6.17754839 C3.22967742,6.17754839 3.35470968,6.16877419 3.47767742,6.15354839 C2.8163871,4.85083871
3.02954839,3.21793548 4.11870968,2.12890323M6.57032258,3.144 L6.57032258,0.300258065 L4.43522581,2.4356129 L4.43006452,2.44064516
C3.24683871,3.62387097 3.24683871,5.54219355 4.43006452,6.72541935 C5.61329032,7.90864516 7.5316129,7.90864516
8.71483871,6.72541935 C8.80464516,6.6356129 8.88529032,6.54025806 8.96154839,6.44270968 C7.57341935,5.98864516
6.57045161,4.68387097 6.57032258,3.144`).attr({
'stroke': this.stroke,
'fill': '#87C040',
'stroke-width': this.strokeWidth
});
const startX1 = startX + 1.419355;
const startY1 = startY + 8.387097;
path1.transform('T' + startX1 + ',' + startY1);
path1 = this.paper.path(`M10.4411613,10.5153548 L8.43032258,8.50451613 L8.43032258,11.5313548 C8.43032258,13.2047742 9.78683871,
14.5611613 11.460129,14.5611613 C13.1334194,14.5611613 14.4899355,13.2047742 14.4899355,11.5314839 C14.4899355,11.4043871
14.4811613,11.2793548 14.4659355,11.1563871 C13.1632258,11.8178065 11.5303226,11.6045161 10.4411613,10.5153548M15.0376774,
5.91935484 C14.947871,5.82954839 14.8526452,5.74890323 14.7550968,5.67264516 C14.3010323,7.06064516 12.996129,8.06374194
11.4563871,8.06374194 L8.61277419,8.06374194 L10.7529032,10.204 C11.936129,11.3872258 13.8545806,11.3872258 15.0376774,10.204
C16.2209032,9.02077419 16.2209032,7.10245161 15.0376774,5.91935484`).attr({
'stroke': this.stroke,
'fill': '#87C040',
'stroke-width': this.strokeWidth
});
path1.transform('T' + startX + ',' + startY);
path1 = this.paper.path(`M5.9083871,1.5636129 C5.78129032,1.5636129 5.65625806,1.57225806 5.53329032,1.58748387
C6.19458065,2.89032258 5.98141935,4.52309677 4.89225806,5.61225806 L2.88154839,7.62309677 L5.9083871,7.62309677
C7.58154839,7.62309677 8.93806452,6.26658065 8.93806452,4.59329032 C8.93819355,2.92 7.58167742,1.5636129
5.9083871,1.5636129`).attr({
'stroke': this.stroke,
'fill': '#ED9A2D',
'stroke-width': this.strokeWidth
});
const startX2 = startX + 5.548387;
path1.transform('T' + startX2 + ',' + startY);
path1 = this.paper.path(`M4.58090323,1.0156129 C3.39767742,-0.167483871 1.47935484,-0.167483871 0.296129032,1.01574194
C0.206451613,1.10554839 0.125806452,1.20077419 0.0495483871,1.29845161 C1.43754839,1.75251613 2.44064516,3.05729032
2.44064516,4.59703226 L2.44064516,7.44077419 L4.57574194,5.30554839 L4.58090323,5.30051613 C5.76412903,4.11729032
5.76412903,2.19896774 4.58090323,1.0156129`).attr({
'stroke': this.stroke,
'fill': '#5698C6',
'stroke-width': this.strokeWidth
});
path1.transform('T' + startX2 + ',' + startY);
path1 = this.paper.path(`M5.54051613,5.61432258 L5.62670968,5.70425806 L7.54632258,7.62387097 L7.5483871,7.62387097
L7.5483871,4.604 L7.5483871,4.59677419 C7.5483871,2.92348387 6.19187097,1.56696774 4.51858065,1.56696774 C2.84529032,1.56696774
1.48877419,2.92335484 1.48890323,4.59664516 C1.48890323,4.72348387 1.49754839,4.84812903 1.51264516,4.97083871
C2.81625806,4.30993548 4.45122581,4.52503226 5.54051613,5.61432258M1.23251613,10.4292903 C1.25625806,10.3588387
1.28180645,10.2894194 1.30980645,10.2210323 C1.31329032,10.2123871 1.3163871,10.2036129 1.32,10.1952258 C1.35070968,10.1216774
1.38451613,10.0500645 1.42,9.97935484 C1.42774194,9.96374194 1.43574194,9.9483871 1.44387097,9.93277419 C1.4803871,9.86258065
1.51883871,9.79354839 1.55987097,9.72632258 C1.56425806,9.71909677 1.56903226,9.71225806 1.57341935,9.70529032
C1.6123871,9.64245161 1.65354839,9.58141935 1.6963871,9.52141935 C1.70516129,9.50903226 1.71380645,9.49651613
1.72283871,9.48425806 C1.76890323,9.42154839 1.81690323,9.36064516 1.86683871,9.30129032 C1.87703226,9.28916129
1.88735484,9.27741935 1.89780645,9.26567742 C1.94658065,9.20916129 1.99690323,9.15406452 2.04916129,9.10090323
C2.05380645,9.09625806 2.05806452,9.09135484 2.06270968,9.08670968 C2.11832258,9.03083871 2.17625806,8.97741935
2.23548387,8.92554839 C2.2483871,8.91419355 2.26129032,8.90296774 2.27432258,8.89187097 C2.33393548,8.84103226
2.39496774,8.79212903 2.45780645,8.74529032 C2.46606452,8.73922581 2.47470968,8.73354839 2.48296774,8.7276129
C2.54167742,8.68490323 2.60180645,8.64412903 2.66322581,8.60503226 C2.67535484,8.59729032 2.68735484,8.58929032
2.6996129,8.58167742 C2.76593548,8.54064516 2.83380645,8.50206452 2.90296774,8.46541935 C2.91754839,8.45780645
2.93225806,8.45045161 2.94696774,8.44296774 C3.016,8.40774194 3.08593548,8.37406452 3.15741935,8.34348387 C3.16090323,8.34206452
3.16425806,8.3403871 3.16774194,8.33883871 C3.24167742,8.30748387 3.31729032,8.27948387 3.39380645,8.25316129
C3.41032258,8.24748387 3.42670968,8.24180645 3.44335484,8.2363871 C3.51909677,8.21174194 3.59587097,8.18903226
3.67380645,8.16929032 C3.68567742,8.16645161 3.69793548,8.16387097 3.70980645,8.16116129 C3.78206452,8.14374194
3.85509677,8.12877419 3.92890323,8.116 C3.94270968,8.11367742 3.9563871,8.11083871 3.97019355,8.10877419 C4.05032258,8.09587097
4.13148387,8.08619355 4.21329032,8.07896774 C4.23096774,8.07741935 4.24877419,8.07625806 4.26645161,8.07483871
C4.35109677,8.06877419 4.43612903,8.06451613 4.52232258,8.06451613 L7.36606452,8.0643871 L5.22580645,5.92412903
C4.04258065,4.74103226 2.12412903,4.74090323 0.941032258,5.92412903 C-0.242193548,7.10735484 -0.242193548,9.02567742
0.941032258,10.2089032 C1.03070968,10.2985806 1.12464516,10.3814194 1.22206452,10.4575484 C1.22529032,10.448 1.22929032,10.4388387
1.23251613,10.4292903`).attr({
'stroke': this.stroke,
'fill': '#5698C6',
'stroke-width': this.strokeWidth
});
path1.transform('T' + startX + ',' + startY);
path1 = this.paper.path(`M5.23290323,5.92412903 L6.92748387,7.61870968 L4.64980645,7.61870968 L4.52064516,7.62141935
C3.13354839,7.62141935 1.96425806,6.68929032 1.60477419,5.41729032 C2.75870968,4.77019355 4.24619355,4.93754839
5.22787097,5.91909677 L5.23290323,5.92412903M7.54722581,4.59612903 L7.54722581,6.99264516 L5.93664516,5.38206452
L5.84348387,5.29264516 C4.86258065,4.31187097 4.69483871,2.82580645 5.34012903,1.67225806 C6.61367742,2.03070968
7.54722581,3.20090323 7.54722581,4.58890323 L7.54722581,4.59612903M10.1385806,5.29819355 L8.444,6.99290323 L8.444,4.71522581
L8.44129032,4.58606452 C8.44129032,3.19896774 9.37341935,2.02954839 10.6454194,1.67019355 C11.2925161,2.82412903
11.1251613,4.3116129 10.1436129,5.29316129 L10.1385806,5.29819355`).attr({
'stroke': this.stroke,
'fill': '#446BA5',
'stroke-width': this.strokeWidth
});
path1.transform('T' + startX + ',' + startY);
path1 = this.paper.path(`M11.4548387,7.61677419 L9.05832258,7.61677419 L10.6689032,6.00619355 L10.7583226,5.91303226
C11.7390968,4.93212903 13.2251613,4.7643871 14.3787097,5.40967742 C14.0202581,6.68322581 12.8500645,7.61677419
11.4620645,7.61677419 L11.4548387,7.61677419`).attr({
'stroke': this.stroke,
'fill': '#FFF101',
'stroke-width': this.strokeWidth
});
path1.transform('T' + startX + ',' + startY);
path1 = this.paper.path(`M10.7470968,10.192 L9.05251613,8.49741935 L11.3301935,8.49741935 L11.4593548,8.49470968
C12.8464516,8.49483871 14.0157419,9.42696774 14.3752258,10.6989677 C13.2211613,11.3459355 11.7338065,11.1787097
10.752129,10.1970323 L10.7470968,10.192M8.43729032,11.5174194 L8.43729032,9.12090323 L10.047871,10.7314839 L10.1411613,10.8209032
C11.1219355,11.8018065 11.2896774,13.2876129 10.6443871,14.4412903 C9.37083871,14.0828387 8.43729032,12.9127742
8.43729032,11.5245161 L8.43729032,11.5174194M5.86193548,10.8296774 L7.55651613,9.13496774 L7.55651613,11.4126452
L7.55922581,11.5418065 C7.55922581,12.9289032 6.62709677,14.0983226 5.35509677,14.4578065 C4.708,13.3036129 4.87535484,11.8162581
5.85690323,10.8347097 L5.86193548,10.8296774M4.53251613,8.50993548 L6.92903226,8.50993548 L5.31845161,10.1205161
L5.22903226,10.2136774 C4.24812903,11.1945806 2.76219355,11.3623226 1.60851613,10.7170323 C1.96709677,9.44335484
3.13716129,8.50993548 4.52529032,8.50993548 L4.53251613,8.50993548`).attr({
'stroke': this.stroke,
'fill': '#45AB47',
'stroke-width': this.strokeWidth
});
path1.transform('T' + startX + ',' + startY);
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.