text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import Vue from "vue";
import { ActionTree, Store, StoreOptions, MutationTree } from "vuex";
import Vuex from "vuex";
import {
IdfMirror,
IEspIdfLink,
IEspIdfTool,
IDownload,
SetupMode,
StatusType,
} from "../types";
export interface IState {
areToolsValid: boolean;
espIdf: string;
espIdfContainer: string;
espIdfErrorStatus: string;
espIdfVersionList: IEspIdfLink[];
exportedToolsPaths: string;
exportedVars: string;
gitVersion: string;
hasPrerequisites: boolean;
idfDownloadStatus: IDownload;
idfGitDownloadStatus: IDownload;
idfPythonDownloadStatus: IDownload;
idfVersion: string;
isEspIdfValid: boolean;
isIdfInstalling: boolean;
isIdfInstalled: boolean;
manualPythonPath: string;
openOCDRulesPath: string;
pathSep: string;
platform: string;
pyExecErrorStatus: string;
pyReqsLog: string;
pyVersionsList: string[];
selectedEspIdfVersion: IEspIdfLink;
selectedIdfMirror: IdfMirror;
selectedSysPython: string;
setupMode: SetupMode;
statusIdfGit: StatusType;
statusIdfPython: StatusType;
statusEspIdf: StatusType;
statusEspIdfTools: StatusType;
statusPyVEnv: StatusType;
toolsFolder: string;
toolsResults: IEspIdfTool[];
}
export const setupState: IState = {
areToolsValid: false,
espIdf: "",
espIdfContainer: "",
espIdfErrorStatus: "",
espIdfVersionList: [],
exportedToolsPaths: "",
exportedVars: "",
gitVersion: "",
hasPrerequisites: false,
idfDownloadStatus: {
id: "",
progress: "",
progressDetail: "",
},
idfGitDownloadStatus: {
id: "",
progress: "",
progressDetail: "",
},
idfPythonDownloadStatus: {
id: "",
progress: "",
progressDetail: "",
},
idfVersion: "",
isEspIdfValid: false,
isIdfInstalling: false,
isIdfInstalled: false,
manualPythonPath: "",
openOCDRulesPath: "",
pathSep: "/",
platform: "",
pyExecErrorStatus: "",
pyReqsLog: "",
pyVersionsList: [],
selectedEspIdfVersion: {
filename: "",
mirror: "",
name: "",
url: "",
},
selectedIdfMirror: IdfMirror.Github,
selectedSysPython: "",
setupMode: SetupMode.express,
statusEspIdf: StatusType.started,
statusEspIdfTools: StatusType.pending,
statusIdfGit: StatusType.pending,
statusIdfPython: StatusType.pending,
statusPyVEnv: StatusType.pending,
toolsFolder: "",
toolsResults: [],
};
declare var acquireVsCodeApi: any;
let vscode: any;
try {
vscode = acquireVsCodeApi();
} catch (error) {
// tslint:disable-next-line: no-console
console.error(error);
}
export const actions: ActionTree<IState, any> = {
checkEspIdfTools(context) {
const pyPath =
context.state.selectedSysPython ===
context.state.pyVersionsList[context.state.pyVersionsList.length - 1]
? context.state.manualPythonPath
: context.state.selectedSysPython;
vscode.postMessage({
command: "checkEspIdfTools",
espIdf: context.state.espIdf,
pyPath,
toolsPath: context.state.toolsResults,
});
},
installEspIdf(context) {
const pyPath =
context.state.selectedSysPython ===
context.state.pyVersionsList[context.state.pyVersionsList.length - 1]
? context.state.manualPythonPath
: context.state.selectedSysPython;
vscode.postMessage({
command: "installEspIdf",
espIdfContainer: context.state.espIdfContainer,
manualEspIdfPath: context.state.espIdf,
mirror: context.state.selectedIdfMirror,
selectedEspIdfVersion: context.state.selectedEspIdfVersion,
selectedPyPath: pyPath,
setupMode: context.state.setupMode,
toolsPath: context.state.toolsFolder,
});
},
installEspIdfTools(context) {
const pyPath =
context.state.selectedSysPython ===
context.state.pyVersionsList[context.state.pyVersionsList.length - 1]
? context.state.manualPythonPath
: context.state.selectedSysPython;
vscode.postMessage({
command: "installEspIdfTools",
espIdf: context.state.espIdf,
mirror: context.state.selectedIdfMirror,
pyPath,
toolsPath: context.state.toolsFolder,
});
},
openEspIdfFolder() {
vscode.postMessage({
command: "openEspIdfFolder",
});
},
openEspIdfContainerFolder() {
vscode.postMessage({
command: "openEspIdfContainerFolder",
});
},
openEspIdfToolsFolder() {
vscode.postMessage({
command: "openEspIdfToolsFolder",
});
},
openPythonPath() {
vscode.postMessage({
command: "openPythonPath",
});
},
requestInitialValues() {
vscode.postMessage({
command: "requestInitialValues",
});
},
saveCustomSettings(context) {
const pyPath =
context.state.selectedSysPython ===
context.state.pyVersionsList[context.state.pyVersionsList.length - 1]
? context.state.manualPythonPath
: context.state.selectedSysPython;
vscode.postMessage({
command: "saveCustomSettings",
espIdfPath: context.state.espIdf,
pyBinPath: pyPath,
tools: context.state.toolsResults,
toolsPath: context.state.toolsFolder,
});
},
useDefaultSettings() {
vscode.postMessage({
command: "usePreviousSettings",
});
},
};
export const mutations: MutationTree<IState> = {
setEspIdfPath(state, espIdf: string) {
const newState = state;
newState.espIdf = espIdf;
Object.assign(state, newState);
},
setEspIdfContainerPath(state, espIdfContainer: string) {
const newState = state;
newState.espIdfContainer = espIdfContainer;
Object.assign(state, newState);
},
setEspIdfErrorStatus(state, errorStatus: string) {
const newState = state;
newState.espIdfErrorStatus = errorStatus;
Object.assign(state, newState);
},
setEspIdfVersionList(state, espIdfVersionList: IEspIdfLink[]) {
const newState = state;
newState.espIdfVersionList = espIdfVersionList;
if (espIdfVersionList && espIdfVersionList.length > 0) {
newState.selectedEspIdfVersion = espIdfVersionList[0];
}
Object.assign(state, newState);
},
setGitVersion(state, gitVersion) {
const newState = state;
newState.gitVersion = gitVersion;
Object.assign(state, newState);
},
setHasPrerequisites(state, hasRequisites: boolean) {
const newState = state;
newState.hasPrerequisites = hasRequisites;
Object.assign(state, newState);
},
setIdfMirror(state, mirrorToUse: IdfMirror) {
const newState = state;
newState.selectedIdfMirror = mirrorToUse;
Object.assign(state, mirrorToUse);
},
setIdfDownloadStatusId(state, id: string) {
const newState = state;
newState.idfDownloadStatus.id = id;
Object.assign(state, newState);
},
setIdfDownloadStatusPercentage(state, progress: string) {
const newState = state;
newState.idfDownloadStatus.progress = progress;
Object.assign(state, newState);
},
setIdfDownloadStatusDetail(state, progressDetail: string) {
const newState = state;
newState.idfDownloadStatus.progressDetail = progressDetail;
Object.assign(state, newState);
},
setIdfVersion(state, idfVersion) {
const newState = state;
newState.idfVersion = idfVersion;
Object.assign(state, newState);
},
setIsIdfInstalled(state, isInstalled: boolean) {
const newState = state;
newState.isIdfInstalled = isInstalled;
Object.assign(state, newState);
},
setIsIdfInstalling(state, isInstalled: boolean) {
const newState = state;
newState.isIdfInstalling = isInstalled;
Object.assign(state, newState);
},
setManualPyPath(state, manualPyPath) {
const newState = state;
newState.manualPythonPath = manualPyPath;
Object.assign(state, newState);
},
setOpenOcdRulesPath(state, openOCDRulesPath: string) {
const newState = state;
newState.openOCDRulesPath = openOCDRulesPath;
Object.assign(state, newState);
},
setPathSep(state, pathSep: string) {
const newState = state;
newState.pathSep = pathSep;
Object.assign(state, newState);
},
setPlatform(state, platform: string) {
const newState = state;
newState.platform = platform;
Object.assign(state, newState);
},
setPyExecErrorStatus(state, errorStatus: string) {
const newState = state;
newState.pyExecErrorStatus = errorStatus;
Object.assign(state, newState);
},
setPyReqsLog(state, pyReqsLog: string) {
const newState = state;
newState.pyReqsLog = pyReqsLog;
Object.assign(state, newState);
},
setPyVersionsList(state, pyVersionsList: string[]) {
const newState = state;
newState.pyVersionsList = pyVersionsList;
if (pyVersionsList && pyVersionsList.length > 0) {
newState.selectedSysPython = pyVersionsList[0];
}
Object.assign(state, newState);
},
setSelectedEspIdfVersion(state, selectedEspIdfVersion: IEspIdfLink) {
const newState = state;
newState.selectedEspIdfVersion = selectedEspIdfVersion;
newState.idfDownloadStatus.id = selectedEspIdfVersion.name;
Object.assign(state, newState);
},
setSelectedSysPython(state, selectedSysPython: string) {
const newState = state;
newState.selectedSysPython = selectedSysPython;
Object.assign(state, newState);
},
setSetupMode(state, setupMode: SetupMode) {
const newState = state;
newState.setupMode = setupMode;
Object.assign(state, newState);
},
setToolsFolder(state, toolsFolder: string) {
const newState = state;
newState.toolsFolder = toolsFolder;
Object.assign(state, newState);
},
setToolChecksum(state, toolData: { name: string; checksum: boolean }) {
const newState = state;
for (let i = 0; i < newState.toolsResults.length; i++) {
if (newState.toolsResults[i].name === toolData.name) {
newState.toolsResults[i].hashResult = toolData.checksum;
break;
}
}
Object.assign(state, newState);
},
setToolDetail(state, toolData: { name: string; detail: string }) {
const newState = state;
for (let i = 0; i < newState.toolsResults.length; i++) {
if (newState.toolsResults[i].name === toolData.name) {
newState.toolsResults[i].progressDetail = toolData.detail;
break;
}
}
Object.assign(state, newState);
},
setToolFailed(state, toolData: { name: string; hasFailed: boolean }) {
const newState = state;
for (let i = 0; i < newState.toolsResults.length; i++) {
if (newState.toolsResults[i].name === toolData.name) {
newState.toolsResults[i].hasFailed = toolData.hasFailed;
break;
}
}
Object.assign(state, newState);
},
setToolPercentage(state, toolData: { name: string; percentage: string }) {
const newState = state;
for (let i = 0; i < newState.toolsResults.length; i++) {
if (newState.toolsResults[i].name === toolData.name) {
newState.toolsResults[i].progress = toolData.percentage;
break;
}
}
Object.assign(state, newState);
},
setToolsResult(state, toolsResults: IEspIdfTool[]) {
const newState = state;
newState.toolsResults = toolsResults;
Object.assign(state, newState);
},
setStatusEspIdf(state, status: StatusType) {
const newState = state;
newState.statusEspIdf = status;
if (status === StatusType.installed) {
newState.idfDownloadStatus.progress = "100.00%";
}
Object.assign(state, newState);
},
setStatusEspIdfTools(state, status: StatusType) {
const newState = state;
newState.statusEspIdfTools = status;
if (status === StatusType.installed) {
for (let i = 0; i < newState.toolsResults.length; i++) {
newState.toolsResults[i].progress = "100.00%";
}
}
Object.assign(state, newState);
},
setStatusPyVEnv(state, status: StatusType) {
const newState = state;
newState.statusPyVEnv = status;
Object.assign(state, newState);
},
setIdfGitPercentage(state, statusData: { name: string; percentage: string }) {
const newState = state;
newState.idfGitDownloadStatus.id = statusData.name;
newState.idfGitDownloadStatus.progress = statusData.percentage;
Object.assign(state, newState);
},
setIdfGitDetail(state, statusData: { name: string; detail: string }) {
const newState = state;
newState.idfGitDownloadStatus.progressDetail = statusData.detail;
Object.assign(state, newState);
},
setStatusIdfPython(state, status: StatusType) {
const newState = state;
newState.statusIdfPython = status;
if (status === StatusType.installed) {
newState.idfPythonDownloadStatus.progress = "100.00%";
}
Object.assign(state, newState);
},
setIdfPythonPercentage(
state,
statusData: { name: string; percentage: string }
) {
const newState = state;
newState.idfPythonDownloadStatus.id = statusData.name;
newState.idfPythonDownloadStatus.progress = statusData.percentage;
Object.assign(state, newState);
},
setIdfPythonDetail(state, statusData: { name: string; detail: string }) {
const newState = state;
newState.idfPythonDownloadStatus.progressDetail = statusData.detail;
Object.assign(state, newState);
},
setStatusIdfGit(state, status: StatusType) {
const newState = state;
newState.statusIdfGit = status;
if (status === StatusType.installed) {
newState.idfGitDownloadStatus.progress = "100.00%";
}
Object.assign(state, newState);
},
};
export const setupStore: StoreOptions<IState> = {
actions,
mutations,
state: setupState,
};
Vue.use(Vuex);
export const store = new Store(setupStore); | the_stack |
import {
ConduitSchema,
GrpcError,
GrpcRequest,
GrpcResponse,
HealthCheckStatus,
ManagedModule,
} from '@conduitplatform/grpc-sdk';
import { AdminHandlers } from './admin/admin';
import { DatabaseRoutes } from './routes/routes';
import * as models from './models';
import {
CreateSchemaRequest,
DropCollectionRequest,
DropCollectionResponse,
FindOneRequest,
FindRequest,
GetSchemaRequest,
GetSchemasRequest,
QueryRequest,
QueryResponse,
UpdateManyRequest,
UpdateRequest,
} from './protoTypes/database';
import { CreateSchemaExtensionRequest, SchemaResponse, SchemasResponse } from './types';
import { DatabaseAdapter } from './adapters/DatabaseAdapter';
import { MongooseAdapter } from './adapters/mongoose-adapter';
import { SequelizeAdapter } from './adapters/sequelize-adapter';
import { MongooseSchema } from './adapters/mongoose-adapter/MongooseSchema';
import { SequelizeSchema } from './adapters/sequelize-adapter/SequelizeSchema';
import { Schema } from './interfaces';
import { canCreate, canDelete, canModify } from './permissions';
import { runMigrations } from './migrations';
import { SchemaController } from './controllers/cms/schema.controller';
import { CustomEndpointController } from './controllers/customEndpoints/customEndpoint.controller';
import { status } from '@grpc/grpc-js';
import path from 'path';
export default class DatabaseModule extends ManagedModule<void> {
config = undefined;
service = {
protoPath: path.resolve(__dirname, 'database.proto'),
protoDescription: 'database.DatabaseProvider',
functions: {
createSchemaFromAdapter: this.createSchemaFromAdapter.bind(this),
getSchema: this.getSchema.bind(this),
getSchemas: this.getSchemas.bind(this),
deleteSchema: this.deleteSchema.bind(this),
setSchemaExtension: this.setSchemaExtension.bind(this),
findOne: this.findOne.bind(this),
findMany: this.findMany.bind(this),
create: this.create.bind(this),
createMany: this.createMany.bind(this),
findByIdAndUpdate: this.findByIdAndUpdate.bind(this),
updateMany: this.updateMany.bind(this),
deleteOne: this.deleteOne.bind(this),
deleteMany: this.deleteMany.bind(this),
countDocuments: this.countDocuments.bind(this),
},
};
private adminRouter: AdminHandlers;
private userRouter: DatabaseRoutes;
private readonly _activeAdapter: DatabaseAdapter<MongooseSchema | SequelizeSchema>;
constructor(dbType: string, dbUri: string) {
super('database');
this.updateHealth(HealthCheckStatus.UNKNOWN, true);
if (dbType === 'mongodb') {
this._activeAdapter = new MongooseAdapter(dbUri);
} else if (dbType === 'postgres' || dbType === 'sql') {
// Compat (<=0.12.2): sql
this._activeAdapter = new SequelizeAdapter(dbUri);
} else {
throw new Error('Database type not supported');
}
}
async preServerStart() {
this._activeAdapter.connect();
await this._activeAdapter.ensureConnected();
}
async onServerStart() {
await this._activeAdapter.createSchemaFromAdapter(models.DeclaredSchema);
await this._activeAdapter.retrieveForeignSchemas();
this.updateHealth(HealthCheckStatus.SERVING);
const modelPromises = Object.values(models).flatMap((model: ConduitSchema) => {
if (model.name === '_DeclaredSchema') return [];
return this._activeAdapter.createSchemaFromAdapter(model);
});
await Promise.all(modelPromises);
await runMigrations(this._activeAdapter);
await this._activeAdapter.recoverSchemasFromDatabase();
}
async onRegister() {
const self = this;
self.grpcSdk.bus?.subscribe('database', (message: string) => {
if (message === 'request') {
self._activeAdapter.registeredSchemas.forEach(k => {
this.grpcSdk.bus!.publish('database', JSON.stringify(k));
});
return;
}
try {
let receivedSchema = JSON.parse(message);
if (receivedSchema.name) {
let schema = new ConduitSchema(
receivedSchema.name,
receivedSchema.modelSchema,
receivedSchema.modelOptions,
receivedSchema.collectionName,
);
schema.ownerModule = receivedSchema.ownerModule;
self._activeAdapter.createSchemaFromAdapter(schema).catch(() => {
console.log('Failed to create/update schema');
});
}
} catch (err) {
console.error('Something was wrong with the message');
}
});
const coreHealth = ((await this.grpcSdk.core.check()) as unknown) as HealthCheckStatus;
this.onCoreHealthChange(coreHealth);
await this.grpcSdk.core.watch('');
}
private onCoreHealthChange(state: HealthCheckStatus) {
const boundFunctionRef = this.onCoreHealthChange.bind(this);
if (state === HealthCheckStatus.SERVING) {
this.userRouter = new DatabaseRoutes(
this.grpcServer,
this._activeAdapter,
this.grpcSdk,
);
const schemaController = new SchemaController(
this.grpcSdk,
this._activeAdapter,
this.userRouter,
);
const customEndpointController = new CustomEndpointController(
this.grpcSdk,
this._activeAdapter,
this.userRouter,
);
this.adminRouter = new AdminHandlers(
this.grpcServer,
this.grpcSdk,
this._activeAdapter,
schemaController,
customEndpointController,
);
} else {
this.grpcSdk.core.healthCheckWatcher.once(
'grpc-health-change:Core',
boundFunctionRef,
);
}
}
publishSchema(schema: any) {
const sendingSchema = JSON.stringify(schema);
this.grpcSdk.bus!.publish('database', sendingSchema);
console.log('Updated state');
}
// gRPC Service
/**
* Should accept a JSON schema and output a .ts interface for the adapter
* @param call
* @param callback
*/
async createSchemaFromAdapter(
call: GrpcRequest<CreateSchemaRequest>,
callback: SchemaResponse,
) {
let schema = new ConduitSchema(
call.request.schema!.name,
JSON.parse(call.request.schema!.modelSchema),
JSON.parse(call.request.schema!.modelOptions),
call.request.schema!.collectionName,
);
if (schema.name.indexOf('-') >= 0 || schema.name.indexOf(' ') >= 0) {
return callback({
code: status.INVALID_ARGUMENT,
message: 'Names cannot include spaces and - characters',
});
}
schema.ownerModule = call.metadata!.get('module-name')![0] as string;
await this._activeAdapter
.createSchemaFromAdapter(schema)
.then((schemaAdapter: Schema) => {
const originalSchema = {
name: schemaAdapter.originalSchema.name,
modelSchema: JSON.stringify(schemaAdapter.originalSchema.modelSchema),
modelOptions: JSON.stringify(schemaAdapter.originalSchema.schemaOptions),
collectionName: schemaAdapter.originalSchema.collectionName,
};
this.publishSchema({
name: call.request.schema!.name,
modelSchema: JSON.parse(call.request.schema!.modelSchema),
modelOptions: JSON.parse(call.request.schema!.modelOptions),
collectionName: call.request.schema!.collectionName,
owner: schema.ownerModule,
});
callback(null, {
schema: originalSchema,
});
})
.catch(err => {
callback({
code: status.INTERNAL,
message: err.message,
});
});
}
/**
* Given a schema name, returns the schema adapter assigned
* @param call
* @param callback
*/
getSchema(call: GrpcRequest<GetSchemaRequest>, callback: SchemaResponse) {
try {
const schemaAdapter = this._activeAdapter.getSchema(call.request.schemaName);
callback(null, {
schema: {
name: schemaAdapter.name,
modelSchema: JSON.stringify(schemaAdapter.modelSchema),
modelOptions: JSON.stringify(schemaAdapter.schemaOptions),
collectionName: schemaAdapter.collectionName,
},
});
} catch (err) {
callback({
code: status.INTERNAL,
message: err.message,
});
}
}
getSchemas(call: GrpcRequest<GetSchemasRequest>, callback: SchemasResponse) {
try {
const schemas = this._activeAdapter.getSchemas();
callback(null, {
schemas: schemas.map(schema => {
return {
name: schema.name,
modelSchema: JSON.stringify(schema.modelSchema),
modelOptions: JSON.stringify(schema.schemaOptions),
collectionName: schema.collectionName,
};
}),
});
} catch (err) {
callback({
code: status.INTERNAL,
message: err.message,
});
}
}
async deleteSchema(
call: GrpcRequest<DropCollectionRequest>,
callback: GrpcResponse<DropCollectionResponse>,
) {
try {
const schemas = await this._activeAdapter.deleteSchema(
call.request.schemaName,
call.request.deleteData,
(call.metadata!.get('module-name')![0] as string) as string,
);
callback(null, { result: schemas });
} catch (err) {
callback({
code: status.INTERNAL,
message: err.message,
});
}
}
/**
* Create, update or delete caller module's extension for target schema
* @param call
* @param callback
*/
async setSchemaExtension(call: CreateSchemaExtensionRequest, callback: SchemaResponse) {
try {
const schemaName = call.request.extension.name;
const extOwner = (call.metadata!.get('module-name')![0] as string) as string;
const extModel = JSON.parse(call.request.extension.modelSchema);
const schema = await this._activeAdapter.getBaseSchema(schemaName);
if (!schema) {
throw new GrpcError(status.NOT_FOUND, 'Schema does not exist');
}
await this._activeAdapter
.setSchemaExtension(schema, extOwner, extModel)
.then((schemaAdapter: Schema) => {
const originalSchema = {
name: schemaAdapter.originalSchema.name,
modelSchema: JSON.stringify(schemaAdapter.originalSchema.modelSchema),
modelOptions: JSON.stringify(schemaAdapter.originalSchema.schemaOptions),
collectionName: schemaAdapter.originalSchema.collectionName,
};
this.publishSchema({
name: call.request.extension.name,
modelSchema: schemaAdapter.model,
modelOptions: schemaAdapter.originalSchema.schemaOptions,
collectionName: schemaAdapter.originalSchema.collectionName,
owner: schemaAdapter.originalSchema.ownerModule,
});
callback(null, {
schema: originalSchema,
});
})
.catch(err => {
callback({
code: status.INTERNAL,
message: err.message,
});
});
} catch (err) {
callback({
code: status.INTERNAL,
message: err.message,
});
}
}
async findOne(
call: GrpcRequest<FindOneRequest>,
callback: GrpcResponse<QueryResponse>,
) {
try {
const schemaAdapter = this._activeAdapter.getSchemaModel(call.request.schemaName);
const doc = await schemaAdapter.model.findOne(
call.request.query,
call.request.select,
call.request.populate,
schemaAdapter.relations,
);
callback(null, { result: JSON.stringify(doc) });
} catch (err) {
callback({
code: status.INTERNAL,
message: err.message,
});
}
}
async findMany(call: GrpcRequest<FindRequest>, callback: GrpcResponse<QueryResponse>) {
try {
const skip = call.request.skip;
const limit = call.request.limit;
const select = call.request.select;
const sort = call.request.sort ? JSON.parse(call.request.sort) : null;
const populate = call.request.populate;
const schemaAdapter = this._activeAdapter.getSchemaModel(call.request.schemaName);
const docs = await schemaAdapter.model.findMany(
call.request.query,
skip,
limit,
select,
sort,
populate,
schemaAdapter.relations,
);
callback(null, { result: JSON.stringify(docs) });
} catch (err) {
callback({
code: status.INTERNAL,
message: err.message,
});
}
}
async create(call: GrpcRequest<QueryRequest>, callback: GrpcResponse<QueryResponse>) {
const moduleName = call.metadata!.get('module-name')![0] as string;
const schemaName = call.request.schemaName;
try {
const schemaAdapter = this._activeAdapter.getSchemaModel(schemaName);
if (!(await canCreate(moduleName, schemaAdapter.model))) {
return callback({
code: status.PERMISSION_DENIED,
message: `Module ${moduleName} is not authorized to create ${schemaName} entries!`,
});
}
const doc = await schemaAdapter.model.create(call.request.query);
const docString = JSON.stringify(doc);
this.grpcSdk.bus?.publish(`${this.name}:create:${schemaName}`, docString);
callback(null, { result: docString });
} catch (err) {
callback({
code: status.INTERNAL,
message: err.message,
});
}
}
async createMany(
call: GrpcRequest<QueryRequest>,
callback: GrpcResponse<QueryResponse>,
) {
const moduleName = call.metadata!.get('module-name')![0] as string;
const schemaName = call.request.schemaName;
try {
const schemaAdapter = this._activeAdapter.getSchemaModel(schemaName);
if (!(await canCreate(moduleName, schemaAdapter.model))) {
return callback({
code: status.PERMISSION_DENIED,
message: `Module ${moduleName} is not authorized to create ${schemaName} entries!`,
});
}
const docs = await schemaAdapter.model.createMany(call.request.query);
const docsString = JSON.stringify(docs);
this.grpcSdk.bus?.publish(`${this.name}:createMany:${schemaName}`, docsString);
callback(null, { result: docsString });
} catch (err) {
callback({
code: status.INTERNAL,
message: err.message,
});
}
}
async findByIdAndUpdate(
call: GrpcRequest<UpdateRequest>,
callback: GrpcResponse<QueryResponse>,
) {
const moduleName = call.metadata!.get('module-name')![0] as string;
const { schemaName } = call.request;
try {
const schemaAdapter = this._activeAdapter.getSchemaModel(schemaName);
if (!(await canModify(moduleName, schemaAdapter.model))) {
return callback({
code: status.PERMISSION_DENIED,
message: `Module ${moduleName} is not authorized to modify ${schemaName} entries!`,
});
}
const result = await schemaAdapter.model.findByIdAndUpdate(
call.request.id,
call.request.query,
call.request.updateProvidedOnly,
call.request.populate,
schemaAdapter.relations,
);
const resultString = JSON.stringify(result);
this.grpcSdk.bus?.publish(`${this.name}:update:${schemaName}`, resultString);
callback(null, { result: resultString });
} catch (err) {
callback({
code: status.INTERNAL,
message: err.message,
});
}
}
async updateMany(
call: GrpcRequest<UpdateManyRequest>,
callback: GrpcResponse<QueryResponse>,
) {
const moduleName = call.metadata!.get('module-name')![0] as string;
const { schemaName } = call.request;
try {
const schemaAdapter = this._activeAdapter.getSchemaModel(schemaName);
if (!(await canModify(moduleName, schemaAdapter.model))) {
return callback({
code: status.PERMISSION_DENIED,
message: `Module ${moduleName} is not authorized to modify ${schemaName} entries!`,
});
}
const result = await schemaAdapter.model.updateMany(
call.request.filterQuery,
call.request.query,
call.request.updateProvidedOnly,
);
const resultString = JSON.stringify(result);
this.grpcSdk.bus?.publish(`${this.name}:updateMany:${schemaName}`, resultString);
callback(null, { result: resultString });
} catch (err) {
callback({
code: status.INTERNAL,
message: err.message,
});
}
}
async deleteOne(
call: GrpcRequest<QueryRequest>,
callback: GrpcResponse<QueryResponse>,
) {
const moduleName = call.metadata!.get('module-name')![0] as string;
const { schemaName, query } = call.request;
try {
const schemaAdapter = this._activeAdapter.getSchemaModel(schemaName);
if (!(await canDelete(moduleName, schemaAdapter.model))) {
return callback({
code: status.PERMISSION_DENIED,
message: `Module ${moduleName} is not authorized to delete ${schemaName} entries!`,
});
}
const result = await schemaAdapter.model.deleteOne(query);
const resultString = JSON.stringify(result);
this.grpcSdk.bus?.publish(`${this.name}:delete:${schemaName}`, resultString);
callback(null, { result: resultString });
} catch (err) {
callback({
code: status.INTERNAL,
message: err.message,
});
}
}
async deleteMany(
call: GrpcRequest<QueryRequest>,
callback: GrpcResponse<QueryResponse>,
) {
const moduleName = call.metadata!.get('module-name')![0] as string;
const { schemaName, query } = call.request;
try {
const schemaAdapter = this._activeAdapter.getSchemaModel(schemaName);
if (!(await canDelete(moduleName, schemaAdapter.model))) {
return callback({
code: status.PERMISSION_DENIED,
message: `Module ${moduleName} is not authorized to delete ${schemaName} entries!`,
});
}
const result = await schemaAdapter.model.deleteMany(query);
const resultString = JSON.stringify(result);
this.grpcSdk.bus?.publish(`${this.name}:delete:${schemaName}`, resultString);
callback(null, { result: resultString });
} catch (err) {
callback({
code: status.INTERNAL,
message: err.message,
});
}
}
async countDocuments(
call: GrpcRequest<QueryRequest>,
callback: GrpcResponse<QueryResponse>,
) {
try {
const schemaAdapter = this._activeAdapter.getSchemaModel(call.request.schemaName);
const result = await schemaAdapter.model.countDocuments(call.request.query);
callback(null, { result: JSON.stringify(result) });
} catch (err) {
callback({
code: status.INTERNAL,
message: err.message,
});
}
}
} | the_stack |
import {
IconChecklistStroked,
IconDoubleChevronRight,
IconGridStroked,
} from "@douyinfe/semi-icons";
import {
Avatar,
Button,
Card,
Col,
List,
Popover,
Row,
Switch,
Table,
Tooltip,
Typography,
} from "@douyinfe/semi-ui";
import { ReplicaState } from "@src/models";
import { exec } from "@src/services";
import { getShardColor } from "@src/utils";
import * as _ from "lodash-es";
import React, { useEffect, useState } from "react";
const { Text } = Typography;
interface ReplicaViewProps {
db: string;
storage: string;
liveNodes: Node[];
}
export default function ReplicaView(props: ReplicaViewProps) {
const { db, storage, liveNodes } = props;
const [loading, setLoading] = useState(true);
const [replicaState, setReplicaState] = useState<any>({
shards: [],
nodes: [],
});
const [showShard, setShowShard] = useState(true);
const [showLag, setShowLag] = useState(true);
const [showTable, setShowTable] = useState(false);
/**
* build replica state by node.
* node=>shard list
* shard=>family list
*/
const buildReplicaState = (replicaState: ReplicaState): any[] => {
const nodes = _.keys(replicaState);
const rs: any[] = [];
_.forEach(nodes, (node) => {
const logs = _.get(replicaState, node, []);
const shards: any[] = [];
_.forEach(logs, (log) => {
const shardIdx = _.findIndex(shards, { shardId: log.shardId });
const families = _.get(log, "replicators", []);
let totalPending = 0;
let replicators: any[] = [];
_.forEach(families || [], (r) => {
replicators.push(_.merge(r, log));
totalPending += r.pending;
});
_.orderBy(
replicators,
["replicator", "replicatorType"],
["desc", "desc"]
);
log.replicators = replicators;
if (shardIdx < 0) {
shards.push({
shardId: log.shardId,
pending: totalPending,
channels: [log],
});
} else {
const shard = shards[shardIdx];
shard.pending += totalPending;
shard.channels.push(log);
}
});
rs.push({ node: node, shards: shards });
});
return rs;
};
/**
* build replica state by shard id
* shard => family list
* family => leader->follower
*/
const buildReplicaStateByShard = (replicaState: ReplicaState): any[] => {
const rs: any[] = [];
const nodes = _.keys(replicaState);
const shardMap = new Map();
_.forEach(nodes, (node) => {
const familyList = _.get(replicaState, node, []);
_.forEach(familyList, (family) => {
const shardId = family.shardId;
const familyTime = family.familyTime;
_.set(family, "sourceNode", node);
let replicators: any[] = [];
_.forEach(family.replicators || [], (r) => {
replicators.push(_.merge(r, family));
});
_.orderBy(
replicators,
["replicator", "replicatorType"],
["desc", "desc"]
);
if (shardMap.has(shardId)) {
const shard = shardMap.get(shardId);
const channels = _.find(shard.channels, { familyTime: familyTime });
if (channels) {
// add family into exist family channel
channels.replicators.push(...replicators);
} else {
// add family into exist shard as new channel
shard.channels.push({
familyTime: familyTime,
replicators: replicators,
});
}
} else {
const shard = {
shardId: shardId,
channels: [{ familyTime: familyTime, replicators: replicators }],
};
shardMap.set(shardId, shard);
rs.push(shard);
}
});
});
return rs;
};
useEffect(() => {
const fetchReplicaState = async (sql: string) => {
try {
setLoading(true);
const state = await exec<ReplicaState>({ sql: sql });
const shards = buildReplicaStateByShard(state);
const nodes = buildReplicaState(state);
setReplicaState({ shards: shards || [], nodes: nodes || [] });
} catch (err) {
console.log(err);
} finally {
setLoading(false);
}
};
fetchReplicaState(
`show replication where storage='${storage}' and database='${db}'`
);
}, [storage, db]);
const renderReplicatorState = (r: any) => {
let color = "warning";
switch (r.state) {
case "Ready":
color = "success";
break;
case "Init":
color = "secondary";
break;
case "Failure":
color = "danger";
break;
}
return (
<Tooltip content={r.stateErrMsg || "Ready"}>
<div
style={{
borderRadius: "var(--semi-border-radius-circle)",
width: 12,
height: 12,
marginTop: 4,
backgroundColor: `var(--semi-color-${color})`,
}}
></div>
</Tooltip>
);
};
const getNode = (id: string) => {
const follower = _.find(liveNodes, {
id: parseInt(id),
});
return `${_.get(follower, "hostIp", "unkonw")}:${_.get(
follower,
"grpcPort",
"unkonw"
)}`;
};
const renderChannel = (shard: any, shardIdx: any) => {
return _.orderBy(shard.channels || [], ["familyTime"], ["desc"]).map(
(channel: any, idx: any) => {
return (
<div
key={idx}
style={{
display: "flex",
}}
>
<Typography.Text
style={{
borderLeft: "1px solid var(--semi-color-border)",
borderRight: "1px solid var(--semi-color-border)",
borderBottom: "1px solid var(--semi-color-border)",
minWidth: 180,
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
{channel.familyTime}
</Typography.Text>
<Table
size="small"
pagination={false}
dataSource={channel.replicators}
showHeader={idx == 0 && shardIdx == 0}
columns={[
{
title: "Type",
dataIndex: "replicatorType",
width: 100,
render: (text, record, _index) => {
return (
<div style={{ display: "flex" }}>
{renderReplicatorState(record)}
<span style={{ marginLeft: 4 }}>{text}</span>
</div>
);
},
},
{
title: "Peer",
dataIndex: "replicator",
render: (_text, record, _index) => {
return (
<div
style={{
display: "flex",
alignItems: "center",
}}
>
<span style={{ display: "flex" }}>
<Avatar
color="amber"
size="extra-extra-small"
style={{ margin: 4 }}
>
L
</Avatar>
<span style={{ marginTop: 4 }}>
{getNode(record.leader)}
</span>
</span>
<IconDoubleChevronRight
style={{
marginLeft: 4,
color: "var(--semi-color-success)",
}}
/>
<span style={{ display: "flex" }}>
<Avatar
color={
`${record.leader}` === record.replicator
? "amber"
: "light-blue"
}
size="extra-extra-small"
style={{ margin: 4 }}
>
{`${record.leader}` === record.replicator
? "L"
: "F"}
</Avatar>
<span style={{ marginTop: 4 }}>
{getNode(record.replicator)}
</span>
</span>
</div>
);
},
},
{
title: "Append",
dataIndex: "append",
width: 100,
},
{
title: "Consume",
dataIndex: "consume",
width: 100,
},
{
title: "Ack",
dataIndex: "ack",
width: 100,
},
{
title: "Lag",
dataIndex: "pending",
width: 100,
},
]}
/>
</div>
);
}
);
};
const renderShards = () => {
return (
<Row
type="flex"
gutter={8}
style={{ display: !showTable ? "block" : "none" }}
>
{replicaState.nodes.map((item: any) => {
return (
<Col span={8} key={item.node}>
<Card bodyStyle={{ padding: 12 }}>
<div style={{ marginBottom: 2, textAlign: "center" }}>
{item.node}
</div>
{_.get(item, "shards", []).map((shard: any) => {
return (
<Popover
showArrow
key={shard.shardId}
content={renderChannel(shard, 0)}
>
<Button
style={{
minWidth: 50,
margin: "0px 4px 4px 0px",
color: "var(--semi-color-text-0)",
backgroundColor: getShardColor(shard.shardId),
}}
size="small"
>
{showShard ? <span>S:{shard.shardId}</span> : ""}
{showShard && showLag ? " " : ""}
{showLag ? <span>L:{shard.pending}</span> : ""}
</Button>
</Popover>
);
})}
</Card>
</Col>
);
})}
</Row>
);
};
const renderShardsAsTable = () => {
const shards = replicaState.shards;
return (
<List
style={{ display: showTable ? "block" : "none" }}
dataSource={_.orderBy(shards, ["shardId"])}
renderItem={(item: any, shardIdx: any) => (
<List.Item
style={{ display: "block", padding: "0", borderBottom: 0 }}
>
<div style={{ display: "flex" }}>
<div
style={{
borderLeft: "1px solid var(--semi-color-border)",
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: "0 8px 0 8px",
borderBottom: "1px solid var(--semi-color-border)",
}}
>
<Avatar
size="default"
style={{
margin: 4,
backgroundColor: getShardColor(item.shardId),
}}
>
{item.shardId}
</Avatar>
</div>
<div
style={{
width: "100%",
borderRight: "1px solid var(--semi-color-border)",
}}
>
{renderChannel(item, shardIdx)}
</div>
</div>
</List.Item>
)}
/>
);
};
return (
<Card
title="Replication Status"
headerExtraContent={
<>
<div style={{ display: "flex", alignItems: "center" }}>
{!showTable && (
<>
<Text style={{ margin: 4 }}>Shard</Text>
<Switch
checked={showShard}
onChange={setShowShard}
size="small"
/>
<Text style={{ margin: 4 }}>Lag</Text>
<Switch checked={showLag} onChange={setShowLag} size="small" />
</>
)}
<Button
style={{ marginLeft: 8 }}
icon={showTable ? <IconChecklistStroked /> : <IconGridStroked />}
onClick={() => setShowTable(!showTable)}
/>
</div>
</>
}
headerStyle={{ padding: 12 }}
bodyStyle={{ padding: 12 }}
loading={loading}
>
{renderShardsAsTable()}
{renderShards()}
</Card>
);
} | the_stack |
import assert from 'assert';
import { r } from '../src';
import config from './config';
describe('dates and times', () => {
before(async () => {
await r.connectPool(config);
});
after(async () => {
await r.getPoolMaster().drain();
});
it('`r.now` should return a date', async () => {
const result1 = await r.now().run();
assert(result1 instanceof Date);
const result2 = await r.expr({ a: r.now() }).run();
assert(result2.a instanceof Date);
const result3 = await r.expr([r.now()]).run();
assert(result3[0] instanceof Date);
const result4 = await r.expr([{}, { a: r.now() }]).run();
assert(result4[1].a instanceof Date);
const result5 = await r.expr({ b: [{}, { a: r.now() }] }).run();
assert(result5.b[1].a instanceof Date);
});
it('`now` is not defined after a term', async () => {
try {
await r
.expr(1)
// @ts-ignore
.now('foo')
.run();
assert.fail('should throw');
} catch (e) {
assert(e.message.endsWith('.now is not a function'));
}
});
it('`r.time` should return a date -- with date and time', async () => {
const result1 = await r.time(1986, 11, 3, 12, 0, 0, 'Z').run();
assert.equal(result1 instanceof Date, true);
const result2 = await r
.time(1986, 11, 3, 12, 20, 0, 'Z')
.minutes()
.run();
assert.equal(result2, 20);
});
it('`r.time` should work with r.args', async () => {
// @ts-ignore
const result = await r.time(r.args([1986, 11, 3, 12, 0, 0, 'Z'])).run();
assert.equal(result instanceof Date, true);
});
it('`r.time` should return a date -- just with a date', async () => {
let result = await r.time(1986, 11, 3, 'Z').run();
assert.equal(result instanceof Date, true);
result = await r.time(1986, 11, 3, 0, 0, 0, 'Z').run();
assert.equal(result instanceof Date, true);
});
it('`r.time` should throw if no argument has been given', async () => {
try {
// @ts-ignore
await r.time().run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`r.time` takes at least 4 arguments, 0 provided.'
);
}
});
it('`r.time` should throw if no 5 arguments', async () => {
try {
// @ts-ignore
await r.time(1, 1, 1, 1, 1).run();
assert.fail('should throw');
} catch (e) {
assert(
e.message.startsWith('Got 5 arguments to TIME (expected 4 or 7) in:')
);
}
});
it('`time` is not defined after a term', async () => {
try {
await r
.expr(1)
// @ts-ignore
.time(1, 2, 3, 'Z')
.run();
assert.fail('should throw');
} catch (e) {
assert(e.message.endsWith('.time is not a function'));
}
});
it('`epochTime` should work', async () => {
const now = new Date();
const result = await r.epochTime(now.getTime() / 1000).run();
assert.deepEqual(now, result);
});
it('`r.epochTime` should throw if no argument has been given', async () => {
try {
// @ts-ignore
await r.epochTime().run();
assert.fail('should throw');
} catch (e) {
assert.equal(e.message, '`r.epochTime` takes 1 argument, 0 provided.');
}
});
it('`epochTime` is not defined after a term', async () => {
try {
await r
.expr(1)
// @ts-ignore
.epochTime(Date.now())
.run();
assert.fail('should throw');
} catch (e) {
assert(e.message.endsWith('.epochTime is not a function'));
}
});
it('`ISO8601` should work', async () => {
const result = await r.ISO8601('1986-11-03T08:30:00-08:00').run();
assert.equal(result.getTime(), Date.UTC(1986, 10, 3, 8 + 8, 30, 0));
});
it('`ISO8601` should work with a timezone', async () => {
const result = await r
.ISO8601('1986-11-03T08:30:00', { defaultTimezone: '-08:00' })
.run();
assert.equal(result.getTime(), Date.UTC(1986, 10, 3, 8 + 8, 30, 0));
});
it('`r.ISO8601` should throw if no argument has been given', async () => {
try {
// @ts-ignore
await r.ISO8601().run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`r.ISO8601` takes at least 1 argument, 0 provided.'
);
}
});
it('`r.ISO8601` should throw if too many arguments', async () => {
try {
// @ts-ignore
await r.ISO8601(1, 1, 1).run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`r.ISO8601` takes at most 2 arguments, 3 provided.'
);
}
});
it('`ISO8601` is not defined after a term', async () => {
try {
await r
.expr(1)
// @ts-ignore
.ISO8601('validISOstring')
.run();
assert.fail('should throw');
} catch (e) {
assert(e.message.endsWith('.ISO8601 is not a function'));
}
});
it('`inTimezone` should work', async () => {
const result = await r
.now()
.inTimezone('-08:00')
.hours()
.do(h => {
return r.branch(
h.eq(0),
r.expr(23).eq(
r
.now()
.inTimezone('-09:00')
.hours()
),
h.eq(
r
.now()
.inTimezone('-09:00')
.hours()
.add(1)
)
);
})
.run();
assert.equal(result, true);
});
it('`inTimezone` should throw if no argument has been given', async () => {
try {
// @ts-ignore
await r
.now()
.inTimezone()
.run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`inTimezone` takes 1 argument, 0 provided after:\nr.now()\n'
);
}
});
it('`timezone` should work', async () => {
const result = await r
.ISO8601('1986-11-03T08:30:00-08:00')
.timezone()
.run();
assert.equal(result, '-08:00');
});
it('`during` should work', async () => {
let result = await r
.now()
.during(r.time(2013, 12, 1, 'Z'), r.now().add(1000))
.run();
assert.equal(result, true);
result = await r
.now()
.during(r.time(2013, 12, 1, 'Z'), r.now(), {
leftBound: 'closed',
rightBound: 'closed'
})
.run();
assert.equal(result, true);
result = await r
.now()
.during(r.time(2013, 12, 1, 'Z'), r.now(), {
leftBound: 'closed',
rightBound: 'open'
})
.run();
assert.equal(result, false);
});
it('`during` should throw if no argument has been given', async () => {
try {
// @ts-ignore
await r
.now()
.during()
.run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`during` takes at least 2 arguments, 0 provided after:\nr.now()\n'
);
}
});
it('`during` should throw if just one argument has been given', async () => {
try {
// @ts-ignore
await r
.now()
.during(1)
.run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`during` takes at least 2 arguments, 1 provided after:\nr.now()\n'
);
}
});
it('`during` should throw if too many arguments', async () => {
try {
// @ts-ignore
await r
.now()
.during(1, 1, 1, 1, 1)
.run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`during` takes at most 3 arguments, 5 provided after:\nr.now()\n'
);
}
});
it('`date` should work', async () => {
let result = await r
.now()
.date()
.hours()
.run();
assert.equal(result, 0);
result = await r
.now()
.date()
.minutes()
.run();
assert.equal(result, 0);
result = await r
.now()
.date()
.seconds()
.run();
assert.equal(result, 0);
});
it('`timeOfDay` should work', async () => {
const result = await r
.now()
.timeOfDay()
.run();
assert(result >= 0);
});
it('`year` should work', async () => {
const result = await r
.now()
.inTimezone(new Date().toString().match(' GMT([^ ]*)')[1])
.year()
.run();
assert.equal(result, new Date().getFullYear());
});
it('`month` should work', async () => {
const result = await r
.now()
.inTimezone(new Date().toString().match(' GMT([^ ]*)')[1])
.month()
.run();
assert.equal(result, new Date().getMonth() + 1);
});
it('`day` should work', async () => {
const result = await r
.now()
.inTimezone(new Date().toString().match(' GMT([^ ]*)')[1])
.day()
.run();
assert.equal(result, new Date().getDate());
});
it('`dayOfYear` should work', async () => {
const result = await r
.now()
.inTimezone(new Date().toString().match(' GMT([^ ]*)')[1])
.dayOfYear()
.run();
assert(result > new Date().getMonth() * 28 + new Date().getDate() - 1);
});
it('`dayOfWeek` should work', async () => {
let result = await r
.now()
.inTimezone(new Date().toString().match(' GMT([^ ]*)')[1])
.dayOfWeek()
.run();
if (result === 7) {
result = 0;
}
assert.equal(result, new Date().getDay());
});
it('`toISO8601` should work', async () => {
const result = await r
.now()
.toISO8601()
.run();
assert.equal(typeof result, 'string');
});
it('`toEpochTime` should work', async () => {
const result = await r
.now()
.toEpochTime()
.run();
assert.equal(typeof result, 'number');
});
it('Constant terms should work', async () => {
let result = await r.monday.run();
assert.equal(result, 1);
result = await r
.expr([
r.monday,
r.tuesday,
r.wednesday,
r.thursday,
r.friday,
r.saturday,
r.sunday,
r.january,
r.february,
r.march,
r.april,
r.may,
r.june,
r.july,
r.august,
r.september,
r.october,
r.november,
r.december
])
.run();
assert.deepEqual(result, [
1,
2,
3,
4,
5,
6,
7,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12
]);
});
it('`epochTime` should work', async () => {
const now = new Date();
const result = await r
.epochTime(now.getTime() / 1000)
.run({ timeFormat: 'raw' });
// @ts-ignore
assert.equal(result.$reql_type$, 'TIME');
});
it('`ISO8601` run parameter should work', async () => {
const result = await r
.time(2018, 5, 2, 13, 0, 0, '-03:00')
.run({ timeFormat: 'ISO8601' });
assert.equal(typeof result, 'string');
assert.equal(result, '2018-05-02T13:00:00.000-03:00');
});
it('Date should be parsed correctly', async () => {
const date = new Date();
const result = await r.expr({ date }).run();
assert.equal(result.date.getTime(), date.getTime());
});
}); | the_stack |
import * as assert from 'assert';
import {afterEach, before, beforeEach, describe, it} from 'mocha';
import * as proxyquire from 'proxyquire';
import * as sinon from 'sinon';
import * as fr from '../src/filter';
import {Row} from '../src/row';
const sandbox = sinon.createSandbox();
const FakeMutation = {
convertToBytes: sandbox.spy(value => {
return value;
}),
createTimeRange: sandbox.stub(),
};
describe('Bigtable/Filter', () => {
let Filter: typeof fr.Filter;
let FilterError: typeof fr.FilterError;
let filter: fr.Filter;
before(() => {
const Fake = proxyquire('../src/filter', {
'./mutation.js': {Mutation: FakeMutation},
});
Filter = Fake.Filter;
FilterError = Fake.FilterError;
});
beforeEach(() => {
filter = new Filter();
});
afterEach(() => {
sandbox.restore();
});
describe('instantiation', () => {
it('should create an empty array of filters', () => {
assert.deepStrictEqual(filter.filters_, []);
});
});
describe('convertToRegExpString', () => {
it('should convert a RegExp to a string', () => {
const str = Filter.convertToRegExpString(/\d+/);
assert.strictEqual(str, '\\d+');
});
it('should convert an Array of strings to a single string', () => {
const things = ['a', 'b', 'c'];
const str = Filter.convertToRegExpString(things);
assert.strictEqual(str, '(a|b|c)');
});
it('should convert an Array of buffers to a single string', () => {
const faces = [Buffer.from('.|.'), Buffer.from('=|=')];
const str = Filter.convertToRegExpString(faces);
assert.strictEqual(str, '(\\.\\|\\.|=\\|=)');
});
it('should not do anything to a string', () => {
const str1 = 'hello';
const str2 = Filter.convertToRegExpString(str1);
assert.strictEqual(str1, str2);
});
it('should convert a number to a string', () => {
const str = Filter.convertToRegExpString(1);
assert.strictEqual(str, '1');
});
it('should not do anything to a buffer', () => {
const str1 = 'hello';
const buffer = Buffer.from(str1);
const str2 = Filter.convertToRegExpString(buffer);
assert.deepStrictEqual(buffer, str2);
});
it('should use a binary encoding on a non utf8 buffer', () => {
const str1 = 'æ';
const buffer = Buffer.from('æ', 'binary');
const str2 = Filter.convertToRegExpString(buffer).toString('binary');
assert.strictEqual(str1, str2);
});
it('should throw an error for unknown types', () => {
const errorReg = /Can't convert to RegExp String from unknown type\./;
assert.throws(() => {
Filter.convertToRegExpString(true as {} as string);
}, errorReg);
});
});
describe('createRange', () => {
it('should create a range object', () => {
const start = 'a' as fr.BoundData;
const end = 'b' as fr.BoundData;
const key = 'Key';
const range = Filter.createRange(start, end, key);
assert.deepStrictEqual(range, {
startKeyClosed: start,
endKeyClosed: end,
});
});
it('should only create start bound', () => {
const start = 'a' as fr.BoundData;
const key = 'Key';
const range = Filter.createRange(start, null, key);
assert(FakeMutation.convertToBytes.calledWithExactly(start));
assert.deepStrictEqual(range, {
startKeyClosed: start,
});
});
it('should only create an end bound', () => {
const end = 'b' as fr.BoundData;
const key = 'Key';
const range = Filter.createRange(null, end, key);
assert(FakeMutation.convertToBytes.calledWithExactly(end));
assert.deepStrictEqual(range, {
endKeyClosed: end,
});
});
it('should optionally accept inclusive flags', () => {
const start = {
value: 'a',
inclusive: false,
};
const end = {
value: 'b',
inclusive: false,
};
const key = 'Key';
const range = Filter.createRange(start, end, key);
assert.deepStrictEqual(range, {
startKeyOpen: start.value,
endKeyOpen: end.value,
});
});
});
describe('parse', () => {
it('should call each individual filter method', () => {
sandbox.spy(Filter.prototype, 'row');
sandbox.spy(Filter.prototype, 'value');
const fakeFilter = [
{
row: 'a',
},
{
value: 'b',
},
];
Filter.parse(fakeFilter);
assert.strictEqual((Filter.prototype.row as sinon.SinonSpy).callCount, 1);
assert((Filter.prototype.row as sinon.SinonSpy).calledWithExactly('a'));
assert.strictEqual(
(Filter.prototype.value as sinon.SinonSpy).callCount,
1
);
assert((Filter.prototype.value as sinon.SinonSpy).calledWithExactly('b'));
});
it('should throw an error for unknown filters', () => {
const fakeFilter = [
{
wat: 'a',
},
];
assert.throws(Filter.parse.bind(null, fakeFilter), FilterError);
});
it('should return the filter in JSON form', () => {
const fakeProto = {a: 'a'};
const fakeFilter = [
{
column: 'a',
},
];
const stub = sandbox.stub(Filter.prototype, 'toProto').returns(fakeProto);
const parsedFilter = Filter.parse(fakeFilter);
assert.strictEqual(parsedFilter, fakeProto);
assert.strictEqual(
(Filter.prototype.toProto as sinon.SinonSpy).callCount,
1
);
stub.restore();
});
});
describe('all', () => {
it('should create a pass all filter when set to true', done => {
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'passAllFilter');
assert.strictEqual(value, true);
done();
};
filter.all(true);
});
it('should create a block all filter when set to false', done => {
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'blockAllFilter');
assert.strictEqual(value, true);
done();
};
filter.all(false);
});
});
describe('column', () => {
it('should set the column qualifier regex filter', done => {
const column = {
name: 'fake-column',
};
const spy = sandbox.stub(Filter, 'convertToRegExpString').returnsArg(0);
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'columnQualifierRegexFilter');
assert.strictEqual(value, column.name);
assert(spy.calledWithExactly(column.name));
assert(FakeMutation.convertToBytes.calledWithExactly(column.name));
spy.restore();
done();
};
filter.column(column);
});
it('should handle a binary encoded buffer regex filter', done => {
const column = {
name: Buffer.from('æ', 'binary'),
};
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'columnQualifierRegexFilter');
assert.deepStrictEqual(value, column.name);
assert(FakeMutation.convertToBytes.calledWithExactly(column.name));
done();
};
filter.column(column);
});
it('should accept the short-hand version of column', done => {
const column = 'fake-column';
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'columnQualifierRegexFilter');
assert.strictEqual(value, column);
done();
};
filter.column(column);
});
it('should accept the cells per column limit filter', done => {
const column = {
cellLimit: 10,
};
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'cellsPerColumnLimitFilter');
assert.strictEqual(value, column.cellLimit);
done();
};
filter.column(column);
});
it('should accept the column range filter', done => {
const fakeRange = {
a: 'a',
b: 'b',
};
const column = {
start: 'a' as fr.BoundData,
end: 'b' as fr.BoundData,
};
const spy = sandbox.stub(Filter, 'createRange').returns(fakeRange);
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'columnRangeFilter');
assert.strictEqual(value, fakeRange);
assert(spy.calledWithExactly(column.start, column.end, 'Qualifier'));
spy.restore();
done();
};
filter.column(column);
});
});
describe('condition', () => {
it('should create a condition filter', done => {
const condition = {
test: {a: 'a'},
pass: {b: 'b'},
fail: {c: 'c'},
};
const spy = sandbox.stub(Filter, 'parse').returnsArg(0);
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'condition');
assert.deepStrictEqual(value, {
predicateFilter: condition.test,
trueFilter: condition.pass,
falseFilter: condition.fail,
});
assert.strictEqual(spy.getCall(0).args[0], condition.test);
assert.strictEqual(spy.getCall(1).args[0], condition.pass);
assert.strictEqual(spy.getCall(2).args[0], condition.fail);
spy.restore();
done();
};
filter.condition(condition);
});
});
describe('family', () => {
it('should create a family name regex filter', done => {
const familyName = 'fake-family';
const spy = sandbox.stub(Filter, 'convertToRegExpString').returnsArg(0);
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'familyNameRegexFilter');
assert.strictEqual(value, familyName);
assert(spy.calledWithExactly(familyName));
spy.restore();
done();
};
filter.family(familyName);
});
});
describe('interleave', () => {
it('should create an interleave filter', done => {
const fakeFilters = [{}, {}, {}];
const spy = sandbox.stub(Filter, 'parse').returnsArg(0);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
filter.set = (filterName, value: any) => {
assert.strictEqual(filterName, 'interleave');
assert.strictEqual(value.filters[0], fakeFilters[0]);
assert.strictEqual(value.filters[1], fakeFilters[1]);
assert.strictEqual(value.filters[2], fakeFilters[2]);
assert.strictEqual(spy.getCall(0).args[0], fakeFilters[0]);
assert.strictEqual(spy.getCall(1).args[0], fakeFilters[1]);
assert.strictEqual(spy.getCall(2).args[0], fakeFilters[2]);
spy.restore();
done();
};
filter.interleave(fakeFilters);
});
});
describe('label', () => {
it('should apply the label transformer', done => {
const label = 'label';
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'applyLabelTransformer');
assert.strictEqual(value, label);
done();
};
filter.label(label);
});
});
describe('row', () => {
it('should apply the row key regex filter', done => {
const row = {
key: 'gwashinton',
};
const convertedKey = 'abcd';
const spy = sandbox
.stub(Filter, 'convertToRegExpString')
.returns(convertedKey);
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'rowKeyRegexFilter');
assert.strictEqual(value, convertedKey);
assert(spy.calledWithExactly(row.key));
assert(FakeMutation.convertToBytes.calledWithExactly(convertedKey));
spy.restore();
done();
};
filter.row(row);
});
it('should accept the short-hand version of row key', done => {
const rowKey = 'gwashington';
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'rowKeyRegexFilter');
assert.strictEqual(value, rowKey);
done();
};
filter.row(rowKey);
});
it('should set the row sample filter', done => {
const row = {
sample: 10,
};
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'rowSampleFilter');
assert.strictEqual(value, row.sample);
done();
};
filter.row(row as {} as Row);
});
it('should set the cells per row offset filter', done => {
const row = {
cellOffset: 10,
};
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'cellsPerRowOffsetFilter');
assert.strictEqual(value, row.cellOffset);
done();
};
filter.row(row);
});
it('should set the cells per row limit filter', done => {
const row = {
cellLimit: 10,
};
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'cellsPerRowLimitFilter');
assert.strictEqual(value, row.cellLimit);
done();
};
filter.row(row);
});
});
describe('set', () => {
it('should create a filter object', () => {
const key = 'notARealFilter';
const value = {a: 'b'};
filter.set(key, value);
assert.strictEqual(filter.filters_[0][key], value);
});
});
describe('sink', () => {
it('should set the sink filter', done => {
const sink = true;
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'sink');
assert.strictEqual(value, sink);
done();
};
filter.sink(sink);
});
});
describe('time', () => {
it('should set the timestamp range filter', done => {
const fakeTimeRange = {
start: 10,
end: 10,
};
const spy = FakeMutation.createTimeRange.returns(fakeTimeRange);
filter.set = (filterName, value) => {
assert.strictEqual(filterName, 'timestampRangeFilter');
assert.strictEqual(value, fakeTimeRange);
assert(spy.calledWithExactly(fakeTimeRange.start, fakeTimeRange.end));
done();
};
filter.time(fakeTimeRange);
});
});
describe('toProto', () => {
it('should return null when no filters are present', () => {
const filter = new Filter();
const filterProto = filter.toProto();
assert.strictEqual(filterProto, null);
});
it('should return a plain filter if there is only 1', () => {
filter.filters_ = [{}];
const filterProto = filter.toProto();
assert.strictEqual(filterProto, filter.filters_[0]);
});
it('should create a chain filter if there are multiple', () => {
filter.filters_ = [{}, {}];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const filterProto = filter.toProto() as any;
assert.strictEqual(filterProto!.chain.filters, filter.filters_);
});
});
describe('value', () => {
it('should set the value regex filter', done => {
const value = {
value: 'fake-value',
};
const fakeRegExValue = 'abcd';
const fakeConvertedValue = 'dcba';
const regSpy = sandbox
.stub(Filter, 'convertToRegExpString')
.returns(fakeRegExValue);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const bytesSpy = ((FakeMutation as any).convertToBytes = sandbox.spy(
() => {
return fakeConvertedValue;
}
));
filter.set = (filterName, val) => {
assert.strictEqual(filterName, 'valueRegexFilter');
assert.strictEqual(fakeConvertedValue, val);
assert(regSpy.calledWithExactly(value.value));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assert((bytesSpy as any).calledWithExactly(fakeRegExValue));
regSpy.restore();
done();
};
filter.value(value);
});
it('should accept the short-hand version of value', done => {
const value = 'fake-value';
const fakeRegExValue = 'abcd';
const fakeConvertedValue = 'dcba';
const regSpy = sandbox
.stub(Filter, 'convertToRegExpString')
.returns(fakeRegExValue);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const bytesSpy = ((FakeMutation.convertToBytes as any) = sandbox.spy(
() => {
return fakeConvertedValue;
}
));
filter.set = (filterName, val) => {
assert.strictEqual(filterName, 'valueRegexFilter');
assert.strictEqual(fakeConvertedValue, val);
assert(regSpy.calledWithExactly(value));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assert((bytesSpy as any).calledWithExactly(fakeRegExValue));
regSpy.restore();
done();
};
filter.value(value);
});
it('should accept the value range filter', done => {
const fakeRange = {
a: 'a',
b: 'b',
};
const value = {
start: 'a' as fr.BoundData,
end: 'b' as fr.BoundData,
};
const spy = sandbox.stub(Filter, 'createRange').returns(fakeRange);
filter.set = (filterName, val) => {
assert.strictEqual(filterName, 'valueRangeFilter');
assert.strictEqual(val, fakeRange);
assert(spy.calledWithExactly(value.start, value.end, 'Value'));
spy.restore();
done();
};
filter.value(value);
});
it('should apply the strip label transformer', done => {
const value = {
strip: true,
};
filter.set = (filterName, val) => {
assert.strictEqual(filterName, 'stripValueTransformer');
assert.strictEqual(val, value.strip);
done();
};
filter.value(value);
});
});
describe('FilterError', () => {
it('should set the correct message', () => {
const err = new FilterError('test');
assert.strictEqual(err.message, 'Unknown filter: test.');
});
it('should set the correct name', () => {
const err = new FilterError('test');
assert.strictEqual(err.name, 'FilterError');
});
});
}); | the_stack |
import { toArray, truncate } from 'lodash';
import { DriverState } from 'omnisharp-client';
import { CompositeDisposable } from 'ts-disposables';
import { ProjectViewModel } from '../server/project-view-model';
import { ViewModel } from '../server/view-model';
const $: JQueryStatic = require('jquery');
import { basename } from 'path';
function truncateStringReverse(str: string, maxLength = 55) {
const reversedString = toArray(str).reverse().join('');
return toArray(truncate(reversedString, maxLength)).reverse().join('');
}
export interface ProjectDisplayElement extends HTMLDivElement {
project: ProjectViewModel<any>;
key: string;
}
const getMessageElement = (function () {
const projectProps = {
get: function project() { return this._project; },
set: function project(project: ProjectViewModel<any>) {
this._project = project;
this._key = project.path;
const path = truncateStringReverse(project.path.replace(this.project.solutionPath, ''), 24);
this.title = `${path} [${project.frameworks.filter(z => z.Name !== 'all').map(x => x.FriendlyName)}]`;
this.innerText = project.name;
}
};
const keyProps = {
get: function key() { return this._key; }
};
return function getMessageElement(): ProjectDisplayElement {
const element: ProjectDisplayElement = <any>document.createElement('div');
element.classList.add('project', 'name');
Object.defineProperty(element, 'project', projectProps);
Object.defineProperty(element, 'key', keyProps);
return element;
};
})();
export class SolutionStatusCard extends HTMLDivElement implements WebComponent {
public displayName = 'Card';
private modelDisposable: CompositeDisposable;
public attachTo: string;
private _name: HTMLSpanElement;
private _projects: HTMLDivElement;
private _buttons: HTMLDivElement;
private _body: HTMLElement;
private _stopBtn: HTMLButtonElement;
private _startBtn: HTMLButtonElement;
private _restartBtn: HTMLButtonElement;
private _statusItem: HTMLSpanElement;
private _statusText: HTMLSpanElement;
private _runtimeText: HTMLSpanElement;
private _count: number;
public get count() { return this._count; }
public set count(count) {
if (this._count !== count) {
this._count = count;
}
if (this._count > 1) {
this._body.parentElement.insertBefore(this._buttons, this._body);
} else {
this._buttons.remove();
}
}
private _model: ViewModel;
public get model() { return this._model; }
public set model(model) {
this._model = model;
this.modelDisposable.dispose();
this.modelDisposable = new CompositeDisposable();
this.modelDisposable.add(this._model.observe.state.delay(10).subscribe(({index, path, /*runtime,*/ state, isReady, isOff, isOn}) => {
const name = `${basename(path)} (${index})`;
if (this._name.innerText !== name) {
this._name.innerText = name;
}
if (state === DriverState.Connected) {
this._statusText.innerText = 'Online';
} else if (state === DriverState.Connecting) {
this._statusText.innerText = 'Loading';
} else if (state === DriverState.Disconnected) {
this._statusText.innerText = 'Offline';
} else {
this._statusText.innerText = DriverState[state];
}
if (isReady) {
this._startBtn.style.display = 'none';
this._stopBtn.style.display = '';
} else if (isOff) {
this._startBtn.style.display = '';
this._stopBtn.style.display = 'none';
} else {
this._startBtn.style.display = 'none';
this._stopBtn.style.display = 'none';
}
if (isOn) {
this._restartBtn.style.display = '';
} else {
this._restartBtn.style.display = 'none';
}
if (isOff) {
this._projects.style.display = 'none';
} else {
this._projects.style.display = '';
}
//this._statusText.innerText = DriverState[state];
this._statusItem.className = 'pull-left stats-item';
this._statusItem.classList.add(DriverState[state].toLowerCase());
this.verifyPosition();
/*if (runtime) {
this._runtimeText.style.display = "";
this._runtimeText.innerText = runtime;
} else {*/
this._runtimeText.style.display = 'none';
this._runtimeText.innerText = '';
/*}*/
}));
this.modelDisposable.add(this._model.observe.projects.subscribe(projects => {
for (let i = 0, len = this._projects.children.length > projects.length ? this._projects.children.length : projects.length; i < len; i++) {
const item = projects[i];
let child: ProjectDisplayElement = <any>this._projects.children[i];
if (!item && child) {
child.remove();
continue;
} else if (item && !child) {
child = getMessageElement();
this._projects.appendChild(child);
}
if (child && child.key !== item.path) {
child.project = item;
}
}
this.verifyPosition();
}));
}
private _getMetaControls() {
this._stopBtn = document.createElement('button');
this._stopBtn.classList.add('btn', 'btn-xs', 'btn-error');
this._stopBtn.onclick = () => atom.commands.dispatch(atom.views.getView(atom.workspace), 'omnisharp-atom:stop-server');
let span = document.createElement('span');
span.classList.add('fa', 'fa-stop');
this._stopBtn.appendChild(span);
this._stopBtn.innerHTML += ' Stop';
this._startBtn = document.createElement('button');
this._startBtn.classList.add('btn', 'btn-xs', 'btn-success');
this._startBtn.onclick = () => atom.commands.dispatch(atom.views.getView(atom.workspace), 'omnisharp-atom:start-server');
span = document.createElement('span');
span.classList.add('fa', 'fa-play');
this._startBtn.appendChild(span);
this._startBtn.innerHTML += ' Start';
this._restartBtn = document.createElement('button');
this._restartBtn.classList.add('btn', 'btn-xs', 'btn-info');
this._restartBtn.onclick = () => atom.commands.dispatch(atom.views.getView(atom.workspace), 'omnisharp-atom:restart-server');
span = document.createElement('span');
span.classList.add('fa', 'fa-refresh');
this._restartBtn.appendChild(span);
this._restartBtn.innerHTML += ' Restart';
const metaControls = document.createElement('div');
metaControls.classList.add('meta-controls');
const buttonGroup = document.createElement('div');
buttonGroup.classList.add('btn-group');
metaControls.appendChild(buttonGroup);
buttonGroup.appendChild(this._startBtn);
buttonGroup.appendChild(this._stopBtn);
buttonGroup.appendChild(this._restartBtn);
return metaControls;
}
private _getStatusItem() {
this._statusItem = document.createElement('span');
this._statusItem.classList.add('pull-left', 'stats-item');
const statusContainer = document.createElement('span');
this._statusItem.appendChild(statusContainer);
const icon = document.createElement('span');
statusContainer.appendChild(icon);
icon.classList.add('icon', 'icon-zap');
this._statusText = document.createElement('span');
statusContainer.appendChild(this._statusText);
return this._statusItem;
}
private _getVersions() {
const versions = document.createElement('span');
versions.classList.add('pull-right', 'stats-item');
const spans = document.createElement('span');
spans.classList.add('icon', 'icon-versions');
versions.appendChild(spans);
this._runtimeText = document.createElement('span');
versions.appendChild(this._runtimeText);
return versions;
}
private _getBody() {
const body = document.createElement('div');
this._body = body;
body.classList.add('body');
const header = document.createElement('h4');
header.classList.add('name');
body.appendChild(header);
this._name = document.createElement('span');
header.appendChild(this._name);
const versions = this._getVersions();
body.appendChild(versions);
const statusItem = this._getStatusItem();
body.appendChild(statusItem);
const metaControls = this._getMetaControls();
body.appendChild(metaControls);
return body;
}
private _getProjects() {
this._projects = document.createElement('div');
this._projects.classList.add('meta', 'meta-projects');
const header = document.createElement('div');
header.classList.add('header');
header.innerText = 'Projects';
return this._projects;
}
private _getButtons() {
this._buttons = document.createElement('div');
this._buttons.classList.add('selector', 'btn-group', 'btn-group-xs');
const left = document.createElement('div');
left.classList.add('btn', 'btn-xs', 'icon', 'icon-triangle-left');
left.onclick = e => atom.commands.dispatch(atom.views.getView(atom.workspace), 'omnisharp-atom:previous-solution-status');
this._buttons.appendChild(left);
const right = document.createElement('div');
right.classList.add('btn', 'btn-xs', 'icon', 'icon-triangle-right');
right.onclick = e => atom.commands.dispatch(atom.views.getView(atom.workspace), 'omnisharp-atom:next-solution-status');
this._buttons.appendChild(right);
return this._buttons;
}
public createdCallback() {
this.modelDisposable = new CompositeDisposable();
this.classList.add('omnisharp-card');
this._getButtons();
const body = this._getBody();
this.appendChild(body);
const projects = this._getProjects();
this.appendChild(projects);
}
public attachedCallback() {
this.verifyPosition();
}
public updateCard(model: ViewModel, count: number) {
this.model = model;
this.count = count;
}
private verifyPosition() {
const offset = $(document.querySelectorAll(this.attachTo)).offset();
if (offset) {
$(this).css({
position: 'fixed',
top: offset.top - this.clientHeight,
left: offset.left
});
}
}
}
(<any>exports).SolutionStatusCard = (<any>document).registerElement('omnisharp-solution-card', { prototype: SolutionStatusCard.prototype }); | the_stack |
import * as coreClient from "@azure/core-client";
/** A load balancer configuration for an availability group listener. */
export interface LoadBalancerConfiguration {
/** Private IP address. */
privateIpAddress?: PrivateIPAddress;
/** Resource id of the public IP. */
publicIpAddressResourceId?: string;
/** Resource id of the load balancer. */
loadBalancerResourceId?: string;
/** Probe port. */
probePort?: number;
/** List of the SQL virtual machine instance resource id's that are enrolled into the availability group listener. */
sqlVirtualMachineInstances?: string[];
}
/** A private IP address bound to the availability group listener. */
export interface PrivateIPAddress {
/** Private IP address bound to the availability group listener. */
ipAddress?: string;
/** Subnet used to include private IP. */
subnetResourceId?: string;
}
/** ARM resource. */
export interface Resource {
/**
* Resource ID.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* Resource name.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* Resource type.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
}
/** A list of availability group listeners. */
export interface AvailabilityGroupListenerListResult {
/**
* Array of results.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: AvailabilityGroupListener[];
/**
* Link to retrieve next page of results.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** Result of the request to list SQL operations. */
export interface OperationListResult {
/**
* Array of results.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: Operation[];
/**
* Link to retrieve next page of results.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** SQL REST API operation definition. */
export interface Operation {
/**
* The name of the operation being performed on this particular object.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* The localized display information for this particular operation / action.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly display?: OperationDisplay;
/**
* The intended executor of the operation.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly origin?: OperationOrigin;
/**
* Additional descriptions for the operation.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly properties?: { [propertyName: string]: Record<string, unknown> };
}
/** Display metadata associated with the operation. */
export interface OperationDisplay {
/**
* The localized friendly form of the resource provider name.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provider?: string;
/**
* The localized friendly form of the resource type related to this action/operation.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly resource?: string;
/**
* The localized friendly name for the operation.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly operation?: string;
/**
* The localized friendly description for the operation.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly description?: string;
}
/** Active Directory account details to operate Windows Server Failover Cluster. */
export interface WsfcDomainProfile {
/** Fully qualified name of the domain. */
domainFqdn?: string;
/** Organizational Unit path in which the nodes and cluster will be present. */
ouPath?: string;
/** Account name used for creating cluster (at minimum needs permissions to 'Create Computer Objects' in domain). */
clusterBootstrapAccount?: string;
/** Account name used for operating cluster i.e. will be part of administrators group on all the participating virtual machines in the cluster. */
clusterOperatorAccount?: string;
/** Account name under which SQL service will run on all participating SQL virtual machines in the cluster. */
sqlServiceAccount?: string;
/** Optional path for fileshare witness. */
fileShareWitnessPath?: string;
/** Fully qualified ARM resource id of the witness storage account. */
storageAccountUrl?: string;
/** Primary key of the witness storage account. */
storageAccountPrimaryKey?: string;
}
/** An update to a SQL virtual machine group. */
export interface SqlVirtualMachineGroupUpdate {
/** Resource tags. */
tags?: { [propertyName: string]: string };
}
/** A list of SQL virtual machine groups. */
export interface SqlVirtualMachineGroupListResult {
/**
* Array of results.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: SqlVirtualMachineGroup[];
/**
* Link to retrieve next page of results.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** A list of SQL virtual machines. */
export interface SqlVirtualMachineListResult {
/**
* Array of results.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: SqlVirtualMachine[];
/**
* Link to retrieve next page of results.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** Azure Active Directory identity configuration for a resource. */
export interface ResourceIdentity {
/**
* The Azure Active Directory principal id.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly principalId?: string;
/** The identity type. Set this to 'SystemAssigned' in order to automatically create and assign an Azure Active Directory principal for the resource. */
type?: IdentityType;
/**
* The Azure Active Directory tenant id.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly tenantId?: string;
}
/** Domain credentials for setting up Windows Server Failover Cluster for SQL availability group. */
export interface WsfcDomainCredentials {
/** Cluster bootstrap account password. */
clusterBootstrapAccountPassword?: string;
/** Cluster operator account password. */
clusterOperatorAccountPassword?: string;
/** SQL service account password. */
sqlServiceAccountPassword?: string;
}
/** Set a patching window during which Windows and SQL patches will be applied. */
export interface AutoPatchingSettings {
/** Enable or disable autopatching on SQL virtual machine. */
enable?: boolean;
/** Day of week to apply the patch on. */
dayOfWeek?: DayOfWeek;
/** Hour of the day when patching is initiated. Local VM time. */
maintenanceWindowStartingHour?: number;
/** Duration of patching. */
maintenanceWindowDuration?: number;
}
/** Configure backups for databases in your SQL virtual machine. */
export interface AutoBackupSettings {
/** Enable or disable autobackup on SQL virtual machine. */
enable?: boolean;
/** Enable or disable encryption for backup on SQL virtual machine. */
enableEncryption?: boolean;
/** Retention period of backup: 1-30 days. */
retentionPeriod?: number;
/** Storage account url where backup will be taken to. */
storageAccountUrl?: string;
/** Storage account key where backup will be taken to. */
storageAccessKey?: string;
/** Password for encryption on backup. */
password?: string;
/** Include or exclude system databases from auto backup. */
backupSystemDbs?: boolean;
/** Backup schedule type. */
backupScheduleType?: BackupScheduleType;
/** Frequency of full backups. In both cases, full backups begin during the next scheduled time window. */
fullBackupFrequency?: FullBackupFrequencyType;
/** Start time of a given day during which full backups can take place. 0-23 hours. */
fullBackupStartTime?: number;
/** Duration of the time window of a given day during which full backups can take place. 1-23 hours. */
fullBackupWindowHours?: number;
/** Frequency of log backups. 5-60 minutes. */
logBackupFrequency?: number;
}
/** Configure your SQL virtual machine to be able to connect to the Azure Key Vault service. */
export interface KeyVaultCredentialSettings {
/** Enable or disable key vault credential setting. */
enable?: boolean;
/** Credential name. */
credentialName?: string;
/** Azure Key Vault url. */
azureKeyVaultUrl?: string;
/** Service principal name to access key vault. */
servicePrincipalName?: string;
/** Service principal name secret to access key vault. */
servicePrincipalSecret?: string;
}
/** Set the connectivity, storage and workload settings. */
export interface ServerConfigurationsManagementSettings {
/** SQL connectivity type settings. */
sqlConnectivityUpdateSettings?: SqlConnectivityUpdateSettings;
/** SQL workload type settings. */
sqlWorkloadTypeUpdateSettings?: SqlWorkloadTypeUpdateSettings;
/** SQL storage update settings. */
sqlStorageUpdateSettings?: SqlStorageUpdateSettings;
/** Additional SQL feature settings. */
additionalFeaturesServerConfigurations?: AdditionalFeaturesServerConfigurations;
}
/** Set the access level and network port settings for SQL Server. */
export interface SqlConnectivityUpdateSettings {
/** SQL Server connectivity option. */
connectivityType?: ConnectivityType;
/** SQL Server port. */
port?: number;
/** SQL Server sysadmin login to create. */
sqlAuthUpdateUserName?: string;
/** SQL Server sysadmin login password. */
sqlAuthUpdatePassword?: string;
}
/** Set workload type to optimize storage for SQL Server. */
export interface SqlWorkloadTypeUpdateSettings {
/** SQL Server workload type. */
sqlWorkloadType?: SqlWorkloadType;
}
/** Set disk storage settings for SQL Server. */
export interface SqlStorageUpdateSettings {
/** Virtual machine disk count. */
diskCount?: number;
/** Device id of the first disk to be updated. */
startingDeviceId?: number;
/** Disk configuration to apply to SQL Server. */
diskConfigurationType?: DiskConfigurationType;
}
/** Additional SQL Server feature settings. */
export interface AdditionalFeaturesServerConfigurations {
/** Enable or disable R services (SQL 2016 onwards). */
isRServicesEnabled?: boolean;
}
/** Storage Configurations for SQL Data, Log and TempDb. */
export interface StorageConfigurationSettings {
/** SQL Server Data Storage Settings. */
sqlDataSettings?: SQLStorageSettings;
/** SQL Server Log Storage Settings. */
sqlLogSettings?: SQLStorageSettings;
/** SQL Server TempDb Storage Settings. */
sqlTempDbSettings?: SQLStorageSettings;
/** Disk configuration to apply to SQL Server. */
diskConfigurationType?: DiskConfigurationType;
/** Storage workload type. */
storageWorkloadType?: StorageWorkloadType;
}
/** Set disk storage settings for SQL Server. */
export interface SQLStorageSettings {
/** Logical Unit Numbers for the disks. */
luns?: number[];
/** SQL Server default file path */
defaultFilePath?: string;
}
/** An update to a SQL virtual machine. */
export interface SqlVirtualMachineUpdate {
/** Resource tags. */
tags?: { [propertyName: string]: string };
}
/** ARM proxy resource. */
export type ProxyResource = Resource & {};
/** ARM tracked top level resource. */
export type TrackedResource = Resource & {
/** Resource location. */
location: string;
/** Resource tags. */
tags?: { [propertyName: string]: string };
};
/** A SQL Server availability group listener. */
export type AvailabilityGroupListener = ProxyResource & {
/**
* Provisioning state to track the async operation status.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: string;
/** Name of the availability group. */
availabilityGroupName?: string;
/** List of load balancer configurations for an availability group listener. */
loadBalancerConfigurations?: LoadBalancerConfiguration[];
/** Create a default availability group if it does not exist. */
createDefaultAvailabilityGroupIfNotExist?: boolean;
/** Listener port. */
port?: number;
};
/** A SQL virtual machine group. */
export type SqlVirtualMachineGroup = TrackedResource & {
/**
* Provisioning state to track the async operation status.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: string;
/** SQL image offer. Examples may include SQL2016-WS2016, SQL2017-WS2016. */
sqlImageOffer?: string;
/** SQL image sku. */
sqlImageSku?: SqlVmGroupImageSku;
/**
* Scale type.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly scaleType?: ScaleType;
/**
* Type of cluster manager: Windows Server Failover Cluster (WSFC), implied by the scale type of the group and the OS type.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly clusterManagerType?: ClusterManagerType;
/**
* Cluster type.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly clusterConfiguration?: ClusterConfiguration;
/** Cluster Active Directory domain profile. */
wsfcDomainProfile?: WsfcDomainProfile;
};
/** A SQL virtual machine. */
export type SqlVirtualMachine = TrackedResource & {
/** Azure Active Directory identity of the server. */
identity?: ResourceIdentity;
/** ARM Resource id of underlying virtual machine created from SQL marketplace image. */
virtualMachineResourceId?: string;
/**
* Provisioning state to track the async operation status.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: string;
/** SQL image offer. Examples include SQL2016-WS2016, SQL2017-WS2016. */
sqlImageOffer?: string;
/** SQL Server license type. */
sqlServerLicenseType?: SqlServerLicenseType;
/** SQL Server Management type. */
sqlManagement?: SqlManagementMode;
/** SQL Server edition type. */
sqlImageSku?: SqlImageSku;
/** ARM resource id of the SQL virtual machine group this SQL virtual machine is or will be part of. */
sqlVirtualMachineGroupResourceId?: string;
/** Domain credentials for setting up Windows Server Failover Cluster for SQL availability group. */
wsfcDomainCredentials?: WsfcDomainCredentials;
/** Auto patching settings for applying critical security updates to SQL virtual machine. */
autoPatchingSettings?: AutoPatchingSettings;
/** Auto backup settings for SQL Server. */
autoBackupSettings?: AutoBackupSettings;
/** Key vault credential settings. */
keyVaultCredentialSettings?: KeyVaultCredentialSettings;
/** SQL Server configuration management settings. */
serverConfigurationsManagementSettings?: ServerConfigurationsManagementSettings;
/** Storage Configuration Settings. */
storageConfigurationSettings?: StorageConfigurationSettings;
};
/** Known values of {@link OperationOrigin} that the service accepts. */
export enum KnownOperationOrigin {
User = "user",
System = "system"
}
/**
* Defines values for OperationOrigin. \
* {@link KnownOperationOrigin} can be used interchangeably with OperationOrigin,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **user** \
* **system**
*/
export type OperationOrigin = string;
/** Known values of {@link SqlVmGroupImageSku} that the service accepts. */
export enum KnownSqlVmGroupImageSku {
Developer = "Developer",
Enterprise = "Enterprise"
}
/**
* Defines values for SqlVmGroupImageSku. \
* {@link KnownSqlVmGroupImageSku} can be used interchangeably with SqlVmGroupImageSku,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Developer** \
* **Enterprise**
*/
export type SqlVmGroupImageSku = string;
/** Known values of {@link ScaleType} that the service accepts. */
export enum KnownScaleType {
HA = "HA"
}
/**
* Defines values for ScaleType. \
* {@link KnownScaleType} can be used interchangeably with ScaleType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **HA**
*/
export type ScaleType = string;
/** Known values of {@link ClusterManagerType} that the service accepts. */
export enum KnownClusterManagerType {
Wsfc = "WSFC"
}
/**
* Defines values for ClusterManagerType. \
* {@link KnownClusterManagerType} can be used interchangeably with ClusterManagerType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **WSFC**
*/
export type ClusterManagerType = string;
/** Known values of {@link ClusterConfiguration} that the service accepts. */
export enum KnownClusterConfiguration {
Domainful = "Domainful"
}
/**
* Defines values for ClusterConfiguration. \
* {@link KnownClusterConfiguration} can be used interchangeably with ClusterConfiguration,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Domainful**
*/
export type ClusterConfiguration = string;
/** Known values of {@link IdentityType} that the service accepts. */
export enum KnownIdentityType {
SystemAssigned = "SystemAssigned"
}
/**
* Defines values for IdentityType. \
* {@link KnownIdentityType} can be used interchangeably with IdentityType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **SystemAssigned**
*/
export type IdentityType = string;
/** Known values of {@link SqlServerLicenseType} that the service accepts. */
export enum KnownSqlServerLicenseType {
Payg = "PAYG",
Ahub = "AHUB",
DR = "DR"
}
/**
* Defines values for SqlServerLicenseType. \
* {@link KnownSqlServerLicenseType} can be used interchangeably with SqlServerLicenseType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **PAYG** \
* **AHUB** \
* **DR**
*/
export type SqlServerLicenseType = string;
/** Known values of {@link SqlManagementMode} that the service accepts. */
export enum KnownSqlManagementMode {
Full = "Full",
LightWeight = "LightWeight",
NoAgent = "NoAgent"
}
/**
* Defines values for SqlManagementMode. \
* {@link KnownSqlManagementMode} can be used interchangeably with SqlManagementMode,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Full** \
* **LightWeight** \
* **NoAgent**
*/
export type SqlManagementMode = string;
/** Known values of {@link SqlImageSku} that the service accepts. */
export enum KnownSqlImageSku {
Developer = "Developer",
Express = "Express",
Standard = "Standard",
Enterprise = "Enterprise",
Web = "Web"
}
/**
* Defines values for SqlImageSku. \
* {@link KnownSqlImageSku} can be used interchangeably with SqlImageSku,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Developer** \
* **Express** \
* **Standard** \
* **Enterprise** \
* **Web**
*/
export type SqlImageSku = string;
/** Known values of {@link BackupScheduleType} that the service accepts. */
export enum KnownBackupScheduleType {
Manual = "Manual",
Automated = "Automated"
}
/**
* Defines values for BackupScheduleType. \
* {@link KnownBackupScheduleType} can be used interchangeably with BackupScheduleType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Manual** \
* **Automated**
*/
export type BackupScheduleType = string;
/** Known values of {@link FullBackupFrequencyType} that the service accepts. */
export enum KnownFullBackupFrequencyType {
Daily = "Daily",
Weekly = "Weekly"
}
/**
* Defines values for FullBackupFrequencyType. \
* {@link KnownFullBackupFrequencyType} can be used interchangeably with FullBackupFrequencyType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Daily** \
* **Weekly**
*/
export type FullBackupFrequencyType = string;
/** Known values of {@link ConnectivityType} that the service accepts. */
export enum KnownConnectivityType {
Local = "LOCAL",
Private = "PRIVATE",
Public = "PUBLIC"
}
/**
* Defines values for ConnectivityType. \
* {@link KnownConnectivityType} can be used interchangeably with ConnectivityType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **LOCAL** \
* **PRIVATE** \
* **PUBLIC**
*/
export type ConnectivityType = string;
/** Known values of {@link SqlWorkloadType} that the service accepts. */
export enum KnownSqlWorkloadType {
General = "GENERAL",
Oltp = "OLTP",
DW = "DW"
}
/**
* Defines values for SqlWorkloadType. \
* {@link KnownSqlWorkloadType} can be used interchangeably with SqlWorkloadType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **GENERAL** \
* **OLTP** \
* **DW**
*/
export type SqlWorkloadType = string;
/** Known values of {@link DiskConfigurationType} that the service accepts. */
export enum KnownDiskConfigurationType {
NEW = "NEW",
Extend = "EXTEND",
ADD = "ADD"
}
/**
* Defines values for DiskConfigurationType. \
* {@link KnownDiskConfigurationType} can be used interchangeably with DiskConfigurationType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **NEW** \
* **EXTEND** \
* **ADD**
*/
export type DiskConfigurationType = string;
/** Known values of {@link StorageWorkloadType} that the service accepts. */
export enum KnownStorageWorkloadType {
General = "GENERAL",
Oltp = "OLTP",
DW = "DW"
}
/**
* Defines values for StorageWorkloadType. \
* {@link KnownStorageWorkloadType} can be used interchangeably with StorageWorkloadType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **GENERAL** \
* **OLTP** \
* **DW**
*/
export type StorageWorkloadType = string;
/** Defines values for DayOfWeek. */
export type DayOfWeek =
| "Monday"
| "Tuesday"
| "Wednesday"
| "Thursday"
| "Friday"
| "Saturday"
| "Sunday";
/** Optional parameters. */
export interface AvailabilityGroupListenersGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type AvailabilityGroupListenersGetResponse = AvailabilityGroupListener;
/** Optional parameters. */
export interface AvailabilityGroupListenersCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the createOrUpdate operation. */
export type AvailabilityGroupListenersCreateOrUpdateResponse = AvailabilityGroupListener;
/** Optional parameters. */
export interface AvailabilityGroupListenersDeleteOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Optional parameters. */
export interface AvailabilityGroupListenersListByGroupOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listByGroup operation. */
export type AvailabilityGroupListenersListByGroupResponse = AvailabilityGroupListenerListResult;
/** Optional parameters. */
export interface AvailabilityGroupListenersListByGroupNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listByGroupNext operation. */
export type AvailabilityGroupListenersListByGroupNextResponse = AvailabilityGroupListenerListResult;
/** Optional parameters. */
export interface OperationsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type OperationsListResponse = OperationListResult;
/** Optional parameters. */
export interface OperationsListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type OperationsListNextResponse = OperationListResult;
/** Optional parameters. */
export interface SqlVirtualMachineGroupsGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type SqlVirtualMachineGroupsGetResponse = SqlVirtualMachineGroup;
/** Optional parameters. */
export interface SqlVirtualMachineGroupsCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the createOrUpdate operation. */
export type SqlVirtualMachineGroupsCreateOrUpdateResponse = SqlVirtualMachineGroup;
/** Optional parameters. */
export interface SqlVirtualMachineGroupsDeleteOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Optional parameters. */
export interface SqlVirtualMachineGroupsUpdateOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the update operation. */
export type SqlVirtualMachineGroupsUpdateResponse = SqlVirtualMachineGroup;
/** Optional parameters. */
export interface SqlVirtualMachineGroupsListByResourceGroupOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listByResourceGroup operation. */
export type SqlVirtualMachineGroupsListByResourceGroupResponse = SqlVirtualMachineGroupListResult;
/** Optional parameters. */
export interface SqlVirtualMachineGroupsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type SqlVirtualMachineGroupsListResponse = SqlVirtualMachineGroupListResult;
/** Optional parameters. */
export interface SqlVirtualMachineGroupsListByResourceGroupNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listByResourceGroupNext operation. */
export type SqlVirtualMachineGroupsListByResourceGroupNextResponse = SqlVirtualMachineGroupListResult;
/** Optional parameters. */
export interface SqlVirtualMachineGroupsListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type SqlVirtualMachineGroupsListNextResponse = SqlVirtualMachineGroupListResult;
/** Optional parameters. */
export interface SqlVirtualMachinesListBySqlVmGroupOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listBySqlVmGroup operation. */
export type SqlVirtualMachinesListBySqlVmGroupResponse = SqlVirtualMachineListResult;
/** Optional parameters. */
export interface SqlVirtualMachinesListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type SqlVirtualMachinesListResponse = SqlVirtualMachineListResult;
/** Optional parameters. */
export interface SqlVirtualMachinesGetOptionalParams
extends coreClient.OperationOptions {
/** The child resources to include in the response. */
expand?: string;
}
/** Contains response data for the get operation. */
export type SqlVirtualMachinesGetResponse = SqlVirtualMachine;
/** Optional parameters. */
export interface SqlVirtualMachinesCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the createOrUpdate operation. */
export type SqlVirtualMachinesCreateOrUpdateResponse = SqlVirtualMachine;
/** Optional parameters. */
export interface SqlVirtualMachinesDeleteOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Optional parameters. */
export interface SqlVirtualMachinesUpdateOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the update operation. */
export type SqlVirtualMachinesUpdateResponse = SqlVirtualMachine;
/** Optional parameters. */
export interface SqlVirtualMachinesListByResourceGroupOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listByResourceGroup operation. */
export type SqlVirtualMachinesListByResourceGroupResponse = SqlVirtualMachineListResult;
/** Optional parameters. */
export interface SqlVirtualMachinesListBySqlVmGroupNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listBySqlVmGroupNext operation. */
export type SqlVirtualMachinesListBySqlVmGroupNextResponse = SqlVirtualMachineListResult;
/** Optional parameters. */
export interface SqlVirtualMachinesListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type SqlVirtualMachinesListNextResponse = SqlVirtualMachineListResult;
/** Optional parameters. */
export interface SqlVirtualMachinesListByResourceGroupNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listByResourceGroupNext operation. */
export type SqlVirtualMachinesListByResourceGroupNextResponse = SqlVirtualMachineListResult;
/** Optional parameters. */
export interface SqlVirtualMachineManagementClientOptionalParams
extends coreClient.ServiceClientOptions {
/** server parameter */
$host?: string;
/** Api Version */
apiVersion?: string;
/** Overrides client endpoint. */
endpoint?: string;
} | the_stack |
// TODO - better do the checks outside of shader
export default `\
#if defined(USE_TEX_LOD) && !defined(FEATURE_GLSL_TEXTURE_LOD)
# error PBR fragment shader: Texture LOD is not available
#endif
#if !defined(HAS_TANGENTS) && !defined(FEATURE_GLSL_DERIVATIVES)
# error PBR fragment shader: Derivatives are not available
#endif
// WebGL 1.0 does not support non-constant in for loops
// This provides an easy way to handle these cases
// and still take advantage of WebGL 2.0
#if (__VERSION__ < 300)
#define SMART_FOR(INIT, WEBGL1COND, WEBGL2COND, INCR) for (INIT; WEBGL1COND; INCR)
#else
#define SMART_FOR(INIT, WEBGL1COND, WEBGL2COND, INCR) for (INIT; WEBGL2COND; INCR)
#endif
precision highp float;
uniform bool pbr_uUnlit;
#ifdef USE_IBL
uniform samplerCube u_DiffuseEnvSampler;
uniform samplerCube u_SpecularEnvSampler;
uniform sampler2D u_brdfLUT;
uniform vec2 u_ScaleIBLAmbient;
#endif
#ifdef HAS_BASECOLORMAP
uniform sampler2D u_BaseColorSampler;
#endif
#ifdef HAS_NORMALMAP
uniform sampler2D u_NormalSampler;
uniform float u_NormalScale;
#endif
#ifdef HAS_EMISSIVEMAP
uniform sampler2D u_EmissiveSampler;
uniform vec3 u_EmissiveFactor;
#endif
#ifdef HAS_METALROUGHNESSMAP
uniform sampler2D u_MetallicRoughnessSampler;
#endif
#ifdef HAS_OCCLUSIONMAP
uniform sampler2D u_OcclusionSampler;
uniform float u_OcclusionStrength;
#endif
#ifdef ALPHA_CUTOFF
uniform float u_AlphaCutoff;
#endif
uniform vec2 u_MetallicRoughnessValues;
uniform vec4 u_BaseColorFactor;
uniform vec3 u_Camera;
// debugging flags used for shader output of intermediate PBR variables
#ifdef PBR_DEBUG
uniform vec4 u_ScaleDiffBaseMR;
uniform vec4 u_ScaleFGDSpec;
#endif
varying vec3 pbr_vPosition;
varying vec2 pbr_vUV;
#ifdef HAS_NORMALS
#ifdef HAS_TANGENTS
varying mat3 pbr_vTBN;
#else
varying vec3 pbr_vNormal;
#endif
#endif
// Encapsulate the various inputs used by the various functions in the shading equation
// We store values in this struct to simplify the integration of alternative implementations
// of the shading terms, outlined in the Readme.MD Appendix.
struct PBRInfo
{
float NdotL; // cos angle between normal and light direction
float NdotV; // cos angle between normal and view direction
float NdotH; // cos angle between normal and half vector
float LdotH; // cos angle between light direction and half vector
float VdotH; // cos angle between view direction and half vector
float perceptualRoughness; // roughness value, as authored by the model creator (input to shader)
float metalness; // metallic value at the surface
vec3 reflectance0; // full reflectance color (normal incidence angle)
vec3 reflectance90; // reflectance color at grazing angle
float alphaRoughness; // roughness mapped to a more linear change in the roughness (proposed by [2])
vec3 diffuseColor; // color contribution from diffuse lighting
vec3 specularColor; // color contribution from specular lighting
vec3 n; // normal at surface point
vec3 v; // vector from surface point to camera
};
const float M_PI = 3.141592653589793;
const float c_MinRoughness = 0.04;
vec4 SRGBtoLINEAR(vec4 srgbIn)
{
#ifdef MANUAL_SRGB
#ifdef SRGB_FAST_APPROXIMATION
vec3 linOut = pow(srgbIn.xyz,vec3(2.2));
#else //SRGB_FAST_APPROXIMATION
vec3 bLess = step(vec3(0.04045),srgbIn.xyz);
vec3 linOut = mix( srgbIn.xyz/vec3(12.92), pow((srgbIn.xyz+vec3(0.055))/vec3(1.055),vec3(2.4)), bLess );
#endif //SRGB_FAST_APPROXIMATION
return vec4(linOut,srgbIn.w);;
#else //MANUAL_SRGB
return srgbIn;
#endif //MANUAL_SRGB
}
// Find the normal for this fragment, pulling either from a predefined normal map
// or from the interpolated mesh normal and tangent attributes.
vec3 getNormal()
{
// Retrieve the tangent space matrix
#ifndef HAS_TANGENTS
vec3 pos_dx = dFdx(pbr_vPosition);
vec3 pos_dy = dFdy(pbr_vPosition);
vec3 tex_dx = dFdx(vec3(pbr_vUV, 0.0));
vec3 tex_dy = dFdy(vec3(pbr_vUV, 0.0));
vec3 t = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t);
#ifdef HAS_NORMALS
vec3 ng = normalize(pbr_vNormal);
#else
vec3 ng = cross(pos_dx, pos_dy);
#endif
t = normalize(t - ng * dot(ng, t));
vec3 b = normalize(cross(ng, t));
mat3 tbn = mat3(t, b, ng);
#else // HAS_TANGENTS
mat3 tbn = pbr_vTBN;
#endif
#ifdef HAS_NORMALMAP
vec3 n = texture2D(u_NormalSampler, pbr_vUV).rgb;
n = normalize(tbn * ((2.0 * n - 1.0) * vec3(u_NormalScale, u_NormalScale, 1.0)));
#else
// The tbn matrix is linearly interpolated, so we need to re-normalize
vec3 n = normalize(tbn[2].xyz);
#endif
return n;
}
// Calculation of the lighting contribution from an optional Image Based Light source.
// Precomputed Environment Maps are required uniform inputs and are computed as outlined in [1].
// See our README.md on Environment Maps [3] for additional discussion.
#ifdef USE_IBL
vec3 getIBLContribution(PBRInfo pbrInputs, vec3 n, vec3 reflection)
{
float mipCount = 9.0; // resolution of 512x512
float lod = (pbrInputs.perceptualRoughness * mipCount);
// retrieve a scale and bias to F0. See [1], Figure 3
vec3 brdf = SRGBtoLINEAR(texture2D(u_brdfLUT,
vec2(pbrInputs.NdotV, 1.0 - pbrInputs.perceptualRoughness))).rgb;
vec3 diffuseLight = SRGBtoLINEAR(textureCube(u_DiffuseEnvSampler, n)).rgb;
#ifdef USE_TEX_LOD
vec3 specularLight = SRGBtoLINEAR(textureCubeLod(u_SpecularEnvSampler, reflection, lod)).rgb;
#else
vec3 specularLight = SRGBtoLINEAR(textureCube(u_SpecularEnvSampler, reflection)).rgb;
#endif
vec3 diffuse = diffuseLight * pbrInputs.diffuseColor;
vec3 specular = specularLight * (pbrInputs.specularColor * brdf.x + brdf.y);
// For presentation, this allows us to disable IBL terms
diffuse *= u_ScaleIBLAmbient.x;
specular *= u_ScaleIBLAmbient.y;
return diffuse + specular;
}
#endif
// Basic Lambertian diffuse
// Implementation from Lambert's Photometria https://archive.org/details/lambertsphotome00lambgoog
// See also [1], Equation 1
vec3 diffuse(PBRInfo pbrInputs)
{
return pbrInputs.diffuseColor / M_PI;
}
// The following equation models the Fresnel reflectance term of the spec equation (aka F())
// Implementation of fresnel from [4], Equation 15
vec3 specularReflection(PBRInfo pbrInputs)
{
return pbrInputs.reflectance0 +
(pbrInputs.reflectance90 - pbrInputs.reflectance0) *
pow(clamp(1.0 - pbrInputs.VdotH, 0.0, 1.0), 5.0);
}
// This calculates the specular geometric attenuation (aka G()),
// where rougher material will reflect less light back to the viewer.
// This implementation is based on [1] Equation 4, and we adopt their modifications to
// alphaRoughness as input as originally proposed in [2].
float geometricOcclusion(PBRInfo pbrInputs)
{
float NdotL = pbrInputs.NdotL;
float NdotV = pbrInputs.NdotV;
float r = pbrInputs.alphaRoughness;
float attenuationL = 2.0 * NdotL / (NdotL + sqrt(r * r + (1.0 - r * r) * (NdotL * NdotL)));
float attenuationV = 2.0 * NdotV / (NdotV + sqrt(r * r + (1.0 - r * r) * (NdotV * NdotV)));
return attenuationL * attenuationV;
}
// The following equation(s) model the distribution of microfacet normals across
// the area being drawn (aka D())
// Implementation from "Average Irregularity Representation of a Roughened Surface
// for Ray Reflection" by T. S. Trowbridge, and K. P. Reitz
// Follows the distribution function recommended in the SIGGRAPH 2013 course notes
// from EPIC Games [1], Equation 3.
float microfacetDistribution(PBRInfo pbrInputs)
{
float roughnessSq = pbrInputs.alphaRoughness * pbrInputs.alphaRoughness;
float f = (pbrInputs.NdotH * roughnessSq - pbrInputs.NdotH) * pbrInputs.NdotH + 1.0;
return roughnessSq / (M_PI * f * f);
}
void PBRInfo_setAmbientLight(inout PBRInfo pbrInputs) {
pbrInputs.NdotL = 1.0;
pbrInputs.NdotH = 0.0;
pbrInputs.LdotH = 0.0;
pbrInputs.VdotH = 1.0;
}
void PBRInfo_setDirectionalLight(inout PBRInfo pbrInputs, vec3 lightDirection) {
vec3 n = pbrInputs.n;
vec3 v = pbrInputs.v;
vec3 l = normalize(lightDirection); // Vector from surface point to light
vec3 h = normalize(l+v); // Half vector between both l and v
pbrInputs.NdotL = clamp(dot(n, l), 0.001, 1.0);
pbrInputs.NdotH = clamp(dot(n, h), 0.0, 1.0);
pbrInputs.LdotH = clamp(dot(l, h), 0.0, 1.0);
pbrInputs.VdotH = clamp(dot(v, h), 0.0, 1.0);
}
void PBRInfo_setPointLight(inout PBRInfo pbrInputs, PointLight pointLight) {
vec3 light_direction = normalize(pointLight.position - pbr_vPosition);
PBRInfo_setDirectionalLight(pbrInputs, light_direction);
}
vec3 calculateFinalColor(PBRInfo pbrInputs, vec3 lightColor) {
// Calculate the shading terms for the microfacet specular shading model
vec3 F = specularReflection(pbrInputs);
float G = geometricOcclusion(pbrInputs);
float D = microfacetDistribution(pbrInputs);
// Calculation of analytical lighting contribution
vec3 diffuseContrib = (1.0 - F) * diffuse(pbrInputs);
vec3 specContrib = F * G * D / (4.0 * pbrInputs.NdotL * pbrInputs.NdotV);
// Obtain final intensity as reflectance (BRDF) scaled by the energy of the light (cosine law)
return pbrInputs.NdotL * lightColor * (diffuseContrib + specContrib);
}
vec4 pbr_filterColor(vec4 colorUnused)
{
// The albedo may be defined from a base texture or a flat color
#ifdef HAS_BASECOLORMAP
vec4 baseColor = SRGBtoLINEAR(texture2D(u_BaseColorSampler, pbr_vUV)) * u_BaseColorFactor;
#else
vec4 baseColor = u_BaseColorFactor;
#endif
#ifdef ALPHA_CUTOFF
if (baseColor.a < u_AlphaCutoff) {
discard;
}
#endif
vec3 color = vec3(0, 0, 0);
if(pbr_uUnlit){
color.rgb = baseColor.rgb;
}
else{
// Metallic and Roughness material properties are packed together
// In glTF, these factors can be specified by fixed scalar values
// or from a metallic-roughness map
float perceptualRoughness = u_MetallicRoughnessValues.y;
float metallic = u_MetallicRoughnessValues.x;
#ifdef HAS_METALROUGHNESSMAP
// Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel.
// This layout intentionally reserves the 'r' channel for (optional) occlusion map data
vec4 mrSample = texture2D(u_MetallicRoughnessSampler, pbr_vUV);
perceptualRoughness = mrSample.g * perceptualRoughness;
metallic = mrSample.b * metallic;
#endif
perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0);
metallic = clamp(metallic, 0.0, 1.0);
// Roughness is authored as perceptual roughness; as is convention,
// convert to material roughness by squaring the perceptual roughness [2].
float alphaRoughness = perceptualRoughness * perceptualRoughness;
vec3 f0 = vec3(0.04);
vec3 diffuseColor = baseColor.rgb * (vec3(1.0) - f0);
diffuseColor *= 1.0 - metallic;
vec3 specularColor = mix(f0, baseColor.rgb, metallic);
// Compute reflectance.
float reflectance = max(max(specularColor.r, specularColor.g), specularColor.b);
// For typical incident reflectance range (between 4% to 100%) set the grazing
// reflectance to 100% for typical fresnel effect.
// For very low reflectance range on highly diffuse objects (below 4%),
// incrementally reduce grazing reflecance to 0%.
float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0);
vec3 specularEnvironmentR0 = specularColor.rgb;
vec3 specularEnvironmentR90 = vec3(1.0, 1.0, 1.0) * reflectance90;
vec3 n = getNormal(); // normal at surface point
vec3 v = normalize(u_Camera - pbr_vPosition); // Vector from surface point to camera
float NdotV = clamp(abs(dot(n, v)), 0.001, 1.0);
vec3 reflection = -normalize(reflect(v, n));
PBRInfo pbrInputs = PBRInfo(
0.0, // NdotL
NdotV,
0.0, // NdotH
0.0, // LdotH
0.0, // VdotH
perceptualRoughness,
metallic,
specularEnvironmentR0,
specularEnvironmentR90,
alphaRoughness,
diffuseColor,
specularColor,
n,
v
);
#ifdef USE_LIGHTS
// Apply ambient light
PBRInfo_setAmbientLight(pbrInputs);
color += calculateFinalColor(pbrInputs, lighting_uAmbientLight.color);
// Apply directional light
SMART_FOR(int i = 0, i < MAX_LIGHTS, i < lighting_uDirectionalLightCount, i++) {
if (i < lighting_uDirectionalLightCount) {
PBRInfo_setDirectionalLight(pbrInputs, lighting_uDirectionalLight[i].direction);
color += calculateFinalColor(pbrInputs, lighting_uDirectionalLight[i].color);
}
}
// Apply point light
SMART_FOR(int i = 0, i < MAX_LIGHTS, i < lighting_uPointLightCount, i++) {
if (i < lighting_uPointLightCount) {
PBRInfo_setPointLight(pbrInputs, lighting_uPointLight[i]);
float attenuation = getPointLightAttenuation(lighting_uPointLight[i], distance(lighting_uPointLight[i].position, pbr_vPosition));
color += calculateFinalColor(pbrInputs, lighting_uPointLight[i].color / attenuation);
}
}
#endif
// Calculate lighting contribution from image based lighting source (IBL)
#ifdef USE_IBL
color += getIBLContribution(pbrInputs, n, reflection);
#endif
// Apply optional PBR terms for additional (optional) shading
#ifdef HAS_OCCLUSIONMAP
float ao = texture2D(u_OcclusionSampler, pbr_vUV).r;
color = mix(color, color * ao, u_OcclusionStrength);
#endif
#ifdef HAS_EMISSIVEMAP
vec3 emissive = SRGBtoLINEAR(texture2D(u_EmissiveSampler, pbr_vUV)).rgb * u_EmissiveFactor;
color += emissive;
#endif
// This section uses mix to override final color for reference app visualization
// of various parameters in the lighting equation.
#ifdef PBR_DEBUG
// TODO: Figure out how to debug multiple lights
// color = mix(color, F, u_ScaleFGDSpec.x);
// color = mix(color, vec3(G), u_ScaleFGDSpec.y);
// color = mix(color, vec3(D), u_ScaleFGDSpec.z);
// color = mix(color, specContrib, u_ScaleFGDSpec.w);
// color = mix(color, diffuseContrib, u_ScaleDiffBaseMR.x);
color = mix(color, baseColor.rgb, u_ScaleDiffBaseMR.y);
color = mix(color, vec3(metallic), u_ScaleDiffBaseMR.z);
color = mix(color, vec3(perceptualRoughness), u_ScaleDiffBaseMR.w);
#endif
}
return vec4(pow(color,vec3(1.0/2.2)), baseColor.a);
}
`; | the_stack |
import {Program} from "../src/runtime/dsl2";
import {verify, createVerifier, pprint} from "./util";
import * as test from "tape";
var programs = {
"1 static": () => {
let prog = new Program("1 static branch");
prog.bind("simple block", ({find, union, record}) => {
let foo = find("input");
let [branch] = union(() => 1);
return [
record("result", {branch})
];
});
return prog;
},
"2 static": () => {
let prog = new Program("2 static branches");
prog.bind("simple block", ({find, union, record}) => {
let foo = find("input");
let [branch] = union(
() => 1,
() => 2
);
return [
record("result", {branch})
];
});
return prog;
},
"1 dynamic": () => {
let prog = new Program("1 dynamic branch");
prog.bind("simple block", ({find, union, record}) => {
let foo = find("input");
let [output] = union(() => foo.arg0);
return [
record("result", {output})
];
});
return prog;
},
"2 dynamic": () => {
let prog = new Program("2 dynamic branches");
prog.bind("simple block", ({find, union, record}) => {
let foo = find("input");
let [output] = union(
() => {foo.arg0 == 1; return ["one"]},
() => foo.arg0
);
return [
record("result", {output})
];
});
return prog;
},
};
let verifyBranches = createVerifier(programs);
// -----------------------------------------------------
// 1 Static branch
// -----------------------------------------------------
test("Union: 1 static branch +A; -A; +A", (assert) => {
verifyBranches(assert, "1 static", "+A; -A; +A", [
[[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]],
[[2, "tag", "result", 1, -1], [2, "branch", 1, 1, -1]],
[[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]]
]);
});
test("Union: 1 static branch +A; -A; +B", (assert) => {
verifyBranches(assert, "1 static", "+A; -A; +B", [
[[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]],
[[2, "tag", "result", 1, -1], [2, "branch", 1, 1, -1]],
[[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]]
]);
});
// @NOTE: Broken due to verify being too simple.
test("Union: 1 static branch +A; +A; -A", (assert) => {
verifyBranches(assert, "1 static", "+A; +A; -A", [
[[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]],
[],
[]
]);
});
// @NOTE: Broken due to verify being too simple.
test("Union: 1 static branch +A; +A; -A; -A", (assert) => {
verifyBranches(assert, "1 static", "+A; +A; -A; -A", [
[[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]],
[],
[],
[[2, "tag", "result", 1, -1], [2, "branch", 1, 1, -1]],
]);
});
test("Union: 1 static branch +A +B; -A; +A", (assert) => {
verifyBranches(assert, "1 static", "+A +B; -A; +A", [
[[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]],
[],
[]
]);
});
test("Union: 1 static branch +A +B; -A -B", (assert) => {
verifyBranches(assert, "1 static", "+A +B; -A -B", [
[[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]],
[[2, "tag", "result", 1, -1], [2, "branch", 1, 1, -1]]
]);
});
test("Union: 1 static branch +A; -A +B", (assert) => {
verifyBranches(assert, "1 static", "+A; -A +B", [
[[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]],
[]
]);
});
test("Union: 1 static branch +A, -A", (assert) => {
verifyBranches(assert, "1 static", "+A, -A", [
[[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1],
[2, "tag", "result", 2, -1], [2, "branch", 1, 2, -1]]
]);
});
test("Union: 1 static branch +A, -A +B", (assert) => {
verifyBranches(assert, "1 static", "+A, -A +B", [
[[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]]
]);
});
test("Union: 1 static branch +A, +B", (assert) => {
verifyBranches(assert, "1 static", "+A, +B", [
[[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]]
]);
});
test("Union: 1 static branch +A, +B; -A", (assert) => {
verifyBranches(assert, "1 static", "+A, +B; -A", [
[[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]],
[[2, "tag", "result", 1, -1], [2, "branch", 1, 1, -1],
[2, "tag", "result", 2, +1], [2, "branch", 1, 2, +1]]
]);
});
test("Union: 1 static branch +A; -A, +B", (assert) => {
verifyBranches(assert, "1 static", "+A; -A, +B", [
[[2, "tag", "result", 1, +1], [2, "branch", 1, 1, +1]],
[[2, "tag", "result", 1, -1], [2, "branch", 1, 1, -1],
[2, "tag", "result", 2, +1], [2, "branch", 1, 2, +1]]
]);
});
// -----------------------------------------------------
// 2 Static branches
// -----------------------------------------------------
test("Union: 2 static branches +A; -A; +A", (assert) => {
verifyBranches(assert, "2 static", "+A; -A; +A", [
[[1, "tag", "result", 1, +1], [1, "branch", 1, 1, +1],
[2, "tag", "result", 1, +1], [2, "branch", 2, 1, +1]],
[[1, "tag", "result", 1, -1], [1, "branch", 1, 1, -1],
[2, "tag", "result", 1, -1], [2, "branch", 2, 1, -1]],
[[1, "tag", "result", 1, +1], [1, "branch", 1, 1, +1],
[2, "tag", "result", 1, +1], [2, "branch", 2, 1, +1]]
]);
});
test("Union: 2 static branches +A; +B", (assert) => {
verifyBranches(assert, "2 static", "+A; +B", [
[[1, "tag", "result", 1, +1], [1, "branch", 1, 1, +1],
[2, "tag", "result", 1, +1], [2, "branch", 2, 1, +1]],
[]
]);
});
test("Union: 2 static branches +A; +B; -A", (assert) => {
verifyBranches(assert, "2 static", "+A; +B; -A", [
[[1, "tag", "result", 1, +1], [1, "branch", 1, 1, +1],
[2, "tag", "result", 1, +1], [2, "branch", 2, 1, +1]],
[],
[]
]);
});
test("Union: 2 static branches +A +B; -A; +A", (assert) => {
verifyBranches(assert, "2 static", "+A +B; -A; +A", [
[[1, "tag", "result", 1, +1], [1, "branch", 1, 1, +1],
[2, "tag", "result", 1, +1], [2, "branch", 2, 1, +1]],
[],
[]
]);
});
test("Union: 2 static branches +A; +B; -A; -B", (assert) => {
verifyBranches(assert, "2 static", "+A; +B; -A; -B", [
[[1, "tag", "result", 1, +1], [1, "branch", 1, 1, +1],
[2, "tag", "result", 1, +1], [2, "branch", 2, 1, +1]],
[],
[],
[[1, "tag", "result", 1, -1], [1, "branch", 1, 1, -1],
[2, "tag", "result", 1, -1], [2, "branch", 2, 1, -1]],
]);
});
test("Union: 2 static branches +A; +B, -A; -B", (assert) => {
verifyBranches(assert, "2 static", "+A; +B, -A; -B", [
[[1, "tag", "result", 1, +1], [1, "branch", 1, 1, +1],
[2, "tag", "result", 1, +1], [2, "branch", 2, 1, +1]],
[],
// These changes happen in round 2 because while the removal of B's results
// happen in round 1, A's results exist in round 1 and then are removed
// in round 2 as a result of A beind removed in round 1.
[[1, "tag", "result", 2, -1], [1, "branch", 1, 2, -1],
[2, "tag", "result", 2, -1], [2, "branch", 2, 2, -1]],
]);
});
// -----------------------------------------------------
// 1 dynamic branch
// -----------------------------------------------------
test("Union: 1 dynamic branch +A:1; -A:1", (assert) => {
verifyBranches(assert, "1 dynamic", "+A:1; -A:1", [
[[1, "tag", "result", 1, +1], [1, "output", 1, 1, +1]],
[[1, "tag", "result", 1, -1], [1, "output", 1, 1, -1]],
]);
});
test("Union: 1 dynamic branch +A:1; -A:1; +A:1", (assert) => {
verifyBranches(assert, "1 dynamic", "+A:1; -A:1; +A:1", [
[[1, "tag", "result", 1, +1], [1, "output", 1, 1, +1]],
[[1, "tag", "result", 1, -1], [1, "output", 1, 1, -1]],
[[1, "tag", "result", 1, +1], [1, "output", 1, 1, +1]],
]);
});
test("Union: 1 dynamic branch +A:1; -A:1; +A:2", (assert) => {
verifyBranches(assert, "1 dynamic", "+A:1; -A:1; +A:2", [
[[1, "tag", "result", 1, +1], [1, "output", 1, 1, +1]],
[[1, "tag", "result", 1, -1], [1, "output", 1, 1, -1]],
[[1, "tag", "result", 1, +1], [1, "output", 2, 1, +1]],
]);
});
test("Union: 1 dynamic branch +A:1; +A:2; -A:1", (assert) => {
verifyBranches(assert, "1 dynamic", "+A:1; +A:2; -A:1", [
[[1, "tag", "result", 1, +1], [1, "output", 1, 1, +1]],
[[1, "tag", "result", 1, +1], [1, "output", 2, 1, +1]],
[[1, "tag", "result", 1, -1], [1, "output", 1, 1, -1]],
]);
});
test("Union: 1 dynamic branch +A:1; +B:1; -A:1", (assert) => {
verifyBranches(assert, "1 dynamic", "+A:1; +B:1; -A:1", [
[[1, "tag", "result", 1, +1], [1, "output", 1, 1, +1]],
[],
[],
]);
});
test("Union: 1 dynamic branch +A:1; +B:1; -A:1, -B:1", (assert) => {
verifyBranches(assert, "1 dynamic", "+A:1; +B:1; -A:1, -B:1", [
[[1, "tag", "result", 1, +1], [1, "output", 1, 1, +1]],
[],
[[1, "tag", "result", 2, -1], [1, "output", 1, 2, -1]],
]);
});
// -----------------------------------------------------
// 2 dynamic branches
// -----------------------------------------------------
test("Union: 2 dynamic branches +A:1; -A:1", (assert) => {
verifyBranches(assert, "2 dynamic", "+A:1; -A:1", [
[[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1],
[2, "tag", "result", 1, +1], [2, "output", 1, 1, +1]],
[[1, "tag", "result", 1, -1], [1, "output", "one", 1, -1],
[2, "tag", "result", 1, -1], [2, "output", 1, 1, -1]]
]);
});
test("Union: 2 dynamic branches +A:1; +B:1", (assert) => {
verifyBranches(assert, "2 dynamic", "+A:1; +B:1", [
[[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1],
[2, "tag", "result", 1, +1], [2, "output", 1, 1, +1]],
[]
]);
});
test("Union: 2 dynamic branches +A:1, +B:1", (assert) => {
verifyBranches(assert, "2 dynamic", "+A:1, +B:1", [
[[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1],
[2, "tag", "result", 1, +1], [2, "output", 1, 1, +1]]
]);
});
test("Union: 2 dynamic branches +A:1, +B:1; -A:1", (assert) => {
verifyBranches(assert, "2 dynamic", "+A:1, +B:1; -A:1", [
[[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1],
[2, "tag", "result", 1, +1], [2, "output", 1, 1, +1]],
[[1, "tag", "result", 1, -1], [1, "output", "one", 1, -1],
[2, "tag", "result", 1, -1], [2, "output", 1, 1, -1],
[1, "tag", "result", 2, +1], [1, "output", "one", 2, +1],
[2, "tag", "result", 2, +1], [2, "output", 1, 2, +1]]
]);
});
test("Union: 2 dynamic branches +A:1 +B:2, -A:1", (assert) => {
verifyBranches(assert, "2 dynamic", "+A:1 +B:2, -A:1", [
[[1, "tag", "result", 1, +1], [1, "output", "one", 1, +1],
[2, "tag", "result", 1, +1], [2, "output", 1, 1, +1],
[3, "tag", "result", 1, +1], [3, "output", 2, 1, +1],
[1, "tag", "result", 2, -1], [1, "output", "one", 2, -1],
[2, "tag", "result", 2, -1], [2, "output", 1, 2, -1]]
]);
});
test("Union: basic", (assert) => {
let prog = new Program("test");
prog.bind("simple block", ({find, record, lib, union}) => {
let person = find("person");
let [info] = union(() => {
person.dog;
return "cool";
}, () => {
return "not cool";
});
return [
record("coolness", {info})
]
});
verify(assert, prog, [
[1, "tag", "person"],
], [
[2, "tag", "coolness", 1],
[2, "info", "not cool", 1],
])
verify(assert, prog, [
[1, "dog", "spot"],
], [
[3, "tag", "coolness", 1],
[3, "info", "cool", 1],
])
assert.end();
});
test("Union: static moves", (assert) => {
let prog = new Program("test");
prog.bind("simple block", ({find, record, lib, union}) => {
let person = find("person");
let [info] = union(() => {
return "cool";
}, () => {
return "not cool";
});
return [
record("coolness", {info})
]
});
verify(assert, prog, [
[1, "tag", "person"],
], [
[2, "tag", "coolness", 1],
[2, "info", "not cool", 1],
[3, "tag", "coolness", 1],
[3, "info", "cool", 1],
])
assert.end();
}); | the_stack |
import React, { ReactElement } from "react";
import { fireEvent, render } from "@testing-library/react";
import { IconProvider } from "@react-md/icon";
import { ErrorOutlineFontIcon } from "@react-md/material-icons";
import { TextFieldWithMessage } from "../TextFieldWithMessage";
import { TextFieldHookOptions, useTextField } from "../useTextField";
import { FormMessageProps } from "../../FormMessage";
function Test({
id = "field-id",
messageRole,
...options
}: Partial<TextFieldHookOptions> & { messageRole?: "alert" }): ReactElement {
// first arg is value, but it isn't needed for these examples
const [, fieldProps] = useTextField({
id,
...options,
});
let messageProps: FormMessageProps = fieldProps.messageProps;
if (messageRole && messageProps) {
messageProps = { ...messageProps, role: messageRole };
}
return <TextFieldWithMessage {...fieldProps} messageProps={messageProps} />;
}
describe("TextFieldWithMessage", () => {
it("should work with all the defaults when only an id is provided", () => {
const { container, getByRole } = render(<Test />);
expect(container).toMatchSnapshot();
const field = getByRole("textbox") as HTMLInputElement;
expect(() => getByRole("alert")).toThrow();
expect(field).toHaveAttribute("aria-describedby", "field-id-message");
expect(field.value).toBe("");
fireEvent.change(field, { target: { value: "a" } });
expect(field.value).toBe("a");
});
it("should apply all of the constraint props to the TextField", () => {
const { rerender, getByRole } = render(
<Test pattern="\d{5,8}" minLength={5} maxLength={8} required />
);
const field = getByRole("textbox");
expect(field).toHaveAttribute("minLength", "5");
expect(field).toHaveAttribute("maxLength", "8");
expect(field).toHaveAttribute("pattern", "\\d{5,8}");
expect(field).toHaveAttribute("required");
rerender(<Test pattern="\d{5,8}" minLength={5} maxLength={8} />);
expect(field).toHaveAttribute("minLength", "5");
expect(field).toHaveAttribute("maxLength", "8");
expect(field).toHaveAttribute("pattern", "\\d{5,8}");
expect(field).not.toHaveAttribute("required");
});
it("should render the counter parts in the message when the counter option is enabled along with the maxLength", () => {
const props = {
counter: true,
maxLength: 20,
};
const { rerender, getByRole } = render(
<Test {...props} messageRole="alert" />
);
const field = getByRole("textbox");
const message = getByRole("alert");
expect(field).toHaveAttribute("maxLength", "20");
expect(message.textContent).toBe("0 / 20");
const value = "Hello, world!";
fireEvent.change(field, { target: { value } });
expect(message.textContent).toBe(`${value.length} / 20`);
rerender(<Test {...props} counter={false} />);
expect(field).toHaveAttribute("maxLength", "20");
expect(message.textContent).toBe("");
});
it("should allow for the maxLength attribute to not be passed to the TextField", () => {
const props = {
maxLength: 20,
disableMaxLength: true,
};
const { rerender, getByRole } = render(<Test {...props} />);
const field = getByRole("textbox");
expect(field).not.toHaveAttribute("maxLength");
rerender(<Test {...props} disableMaxLength={false} />);
expect(field).toHaveAttribute("maxLength", "20");
});
it("should enable the error state if the value is greater than the maxLength", () => {
const { getByRole } = render(
<Test minLength={5} maxLength={20} messageRole="alert" />
);
const field = getByRole("textbox");
const container = field.parentElement!;
const message = getByRole("alert");
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
fireEvent.change(field, { target: { value: "1" } });
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
fireEvent.change(field, { target: { value: "Valid" } });
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
fireEvent.change(field, { target: { value: "1234567890123456789" } });
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
fireEvent.change(field, { target: { value: "12345678901234567890" } });
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
fireEvent.change(field, { target: { value: "123456789012345678901" } });
expect(container.className).toContain("--error");
expect(message.className).toContain("--error");
});
it("should not update the error state on change or update the value if the custon onChange event stopped propagation", () => {
const { getByRole } = render(
<Test
minLength={10}
onChange={(event) => event.stopPropagation()}
messageRole="alert"
/>
);
const field = getByRole("textbox");
const container = field.parentElement!;
const message = getByRole("alert");
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
fireEvent.change(field, { target: { value: "1" } });
expect(field).toHaveAttribute("value", "");
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
});
it("should not update the error state on change if `validateOnChange` is false", () => {
const { getByRole } = render(
<Test minLength={10} validateOnChange={false} messageRole="alert" />
);
const field = getByRole("textbox");
const container = field.parentElement!;
const message = getByRole("alert");
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
fireEvent.change(field, { target: { value: "1" } });
expect(field).toHaveAttribute("value", "1");
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
});
it("should not update the error state on change if `validateOnChange` is an empty array", () => {
const { getByRole } = render(
<Test minLength={10} validateOnChange={[]} messageRole="alert" />
);
const field = getByRole("textbox");
const container = field.parentElement!;
const message = getByRole("alert");
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
fireEvent.change(field, { target: { value: "1" } });
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
expect(field).toHaveAttribute("value", "1");
});
it("should render the helpText if when there is no error text", () => {
const { getByRole } = render(
<Test
helpText="Help Text"
messageRole="alert"
maxLength={5}
getErrorMessage={({ value }) =>
value.length > 0 ? "Error Message" : ""
}
/>
);
const field = getByRole("textbox");
const container = field.parentElement!;
const message = getByRole("alert");
expect(message.textContent).toBe("Help Text");
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
fireEvent.change(field, { target: { value: "Invalid" } });
expect(message.textContent).toBe("Error Message");
expect(container.className).toContain("--error");
expect(message.className).toContain("--error");
});
it("should render an icon next to the text field when there is an error by default", () => {
const { getByRole, getByText } = render(
<Test maxLength={3} errorIcon={<ErrorOutlineFontIcon />} />
);
const field = getByRole("textbox");
expect(() => getByText("error_outline")).toThrow();
fireEvent.change(field, { target: { value: "Invalid" } });
expect(() => getByText("error_outline")).not.toThrow();
});
it("should default to the icon from the IconProvider", () => {
const { getByText, getByRole } = render(
<IconProvider>
<Test maxLength={3} />
</IconProvider>
);
const field = getByRole("textbox");
expect(() => getByText("error_outline")).toThrow();
fireEvent.change(field, { target: { value: "Invalid" } });
expect(() => getByText("error_outline")).not.toThrow();
});
it("should override the IconProvider error icon when the errorIcon prop is defined", () => {
const { getByRole, getByText, rerender } = render(
<IconProvider>
<Test maxLength={3} errorIcon={null} />
</IconProvider>
);
const field = getByRole("textbox");
expect(() => getByText("error_outline")).toThrow();
fireEvent.change(field, { target: { value: "Invalid" } });
expect(() => getByText("error_outline")).toThrow();
rerender(
<IconProvider>
<Test maxLength={3} errorIcon={<span>My Icon!</span>} />
</IconProvider>
);
expect(() => getByText("My Icon!")).not.toThrow();
});
it("should correctly reset with the provided return function", () => {
function ResetTest(): ReactElement {
const [, props, { reset }] = useTextField({ id: "field-id" });
return (
<>
<button type="button" onClick={reset}>
Reset
</button>
<TextFieldWithMessage {...props} />
</>
);
}
const { getByRole } = render(<ResetTest />);
const button = getByRole("button");
const field = getByRole("textbox");
expect(field).toHaveAttribute("value", "");
fireEvent.change(field, { target: { value: "my value" } });
expect(field).toHaveAttribute("value", "my value");
fireEvent.click(button);
expect(field).toHaveAttribute("value", "");
});
it("should validate on blur", () => {
const { getByRole } = render(
<Test messageRole="alert" minLength={10} validateOnChange={false} />
);
const field = getByRole("textbox");
const container = field.parentElement!;
const message = getByRole("alert");
fireEvent.change(field, { target: { value: "invalid" } });
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
fireEvent.blur(field);
expect(container.className).toContain("--error");
expect(message.className).toContain("--error");
});
it("should not do anything if the provided onBlur function calls stopPropagation", () => {
const { getByRole } = render(
<Test
onBlur={(event) => event.stopPropagation()}
messageRole="alert"
maxLength={3}
validateOnChange={false}
/>
);
const field = getByRole("textbox");
const container = field.parentElement!;
const message = getByRole("alert");
fireEvent.change(field, { target: { value: "invalid" } });
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
fireEvent.blur(field);
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
});
it("should allow for a custom default value string", () => {
const { getByRole } = render(<Test defaultValue="Hello, world!" />);
const field = getByRole("textbox");
expect(field).toHaveAttribute("value", "Hello, world!");
});
it("should allow for a custom default value function", () => {
const { getByRole } = render(<Test defaultValue={() => "Hello, world!"} />);
const field = getByRole("textbox");
expect(field).toHaveAttribute("value", "Hello, world!");
});
it("should not render the FormMessage when the disableMessage option is true", () => {
const { container, getByRole } = render(
<Test disableMessage messageRole="alert" />
);
expect(container).toMatchSnapshot();
expect(container.firstElementChild?.className).toContain("rmd-text-field");
expect(container.firstElementChild?.className).not.toContain(
"rmd-field-message-container"
);
expect(() => getByRole("alert")).toThrow();
});
it("should allow for a custom isErrored function", () => {
const isErrored = jest.fn(() => false);
const { getByRole } = render(
<Test isErrored={isErrored} messageRole="alert" maxLength={3} />
);
expect(isErrored).not.toBeCalled();
const field = getByRole("textbox");
const container = field.parentElement!;
const message = getByRole("alert");
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
fireEvent.change(field, { target: { value: "invalid" } });
expect(container.className).not.toContain("--error");
expect(message.className).not.toContain("--error");
expect(isErrored).toBeCalledWith({
value: "invalid",
errorMessage: "",
maxLength: 3,
isBlurEvent: false,
validateOnChange: "recommended",
validationMessage: "",
validity: (field as HTMLInputElement).validity,
});
});
it("should call the onErrorChange option correctly", () => {
const onErrorChange = jest.fn();
const { getByRole } = render(
<Test onErrorChange={onErrorChange} maxLength={3} />
);
expect(onErrorChange).not.toBeCalled();
const field = getByRole("textbox");
fireEvent.change(field, { target: { value: "invalid" } });
expect(onErrorChange).toBeCalledWith("field-id", true);
fireEvent.change(field, { target: { value: "v" } });
expect(onErrorChange).toBeCalledWith("field-id", false);
expect(onErrorChange).toBeCalledTimes(2);
});
it("should allow for custom logic for displaying the error icon", () => {
const getErrorIcon = jest.fn(
(errorMessage, error, errorIcon) =>
error && <span data-testid="wrapper">{errorIcon}</span>
);
const errorIcon = <span data-testid="error-icon" />;
const { getByTestId, getByRole } = render(
<Test maxLength={3} errorIcon={errorIcon} getErrorIcon={getErrorIcon} />
);
const field = getByRole("textbox");
expect(() => getByTestId("wrapper")).toThrow();
expect(() => getByTestId("error-icon")).toThrow();
expect(getErrorIcon).toBeCalledWith("", false, errorIcon);
fireEvent.change(field, { target: { value: "invalid" } });
expect(() => getByTestId("wrapper")).not.toThrow();
expect(() => getByTestId("error-icon")).not.toThrow();
expect(getErrorIcon).toBeCalledWith("", true, errorIcon);
expect(getErrorIcon).toBeCalledTimes(2);
});
it.todo(
"should verify the constraint validation, but it requires a real browser to work"
);
}); | the_stack |
import {
Agile,
Persistent,
Storage,
createStorage,
Storages,
assignSharedStorageManager,
createStorageManager,
} from '../../../src';
import { LogMock } from '../../helper/logMock';
describe('Persistent Tests', () => {
let dummyAgile: Agile;
let storageManager: Storages;
beforeEach(() => {
LogMock.mockLogs();
dummyAgile = new Agile();
// Register Storage Manager
storageManager = createStorageManager();
assignSharedStorageManager(storageManager);
jest.spyOn(Persistent.prototype, 'instantiatePersistent');
jest.clearAllMocks();
});
it('should create Persistent (default config)', () => {
// Overwrite instantiatePersistent once to not call it
jest
.spyOn(Persistent.prototype, 'instantiatePersistent')
.mockReturnValueOnce(undefined);
const persistent = new Persistent(dummyAgile);
expect(persistent).toBeInstanceOf(Persistent);
expect(persistent.instantiatePersistent).toHaveBeenCalledWith({
storageKeys: [],
key: undefined,
defaultStorageKey: null,
});
expect(persistent._key).toBe(Persistent.placeHolderKey);
expect(persistent.ready).toBeFalsy();
expect(persistent.isPersisted).toBeFalsy();
expect(persistent.onLoad).toBeUndefined();
expect(persistent.storageKeys).toStrictEqual([]);
expect(persistent.config).toStrictEqual({ defaultStorageKey: null });
});
it('should create Persistent (specific config)', () => {
// Overwrite instantiatePersistent once to not call it
jest
.spyOn(Persistent.prototype, 'instantiatePersistent')
.mockReturnValueOnce(undefined);
const persistent = new Persistent(dummyAgile, {
storageKeys: ['test1', 'test2'],
key: 'persistentKey',
defaultStorageKey: 'test1',
});
expect(persistent).toBeInstanceOf(Persistent);
expect(persistent.instantiatePersistent).toHaveBeenCalledWith({
storageKeys: ['test1', 'test2'],
key: 'persistentKey',
defaultStorageKey: 'test1',
});
expect(persistent._key).toBe(Persistent.placeHolderKey);
expect(persistent.ready).toBeFalsy();
expect(persistent.isPersisted).toBeFalsy();
expect(persistent.onLoad).toBeUndefined();
expect(persistent.storageKeys).toStrictEqual([]);
expect(persistent.config).toStrictEqual({ defaultStorageKey: 'test1' });
});
it('should create Persistent (config.instantiate = false)', () => {
// Overwrite instantiatePersistent once to not call it
jest
.spyOn(Persistent.prototype, 'instantiatePersistent')
.mockReturnValueOnce(undefined);
const persistent = new Persistent(dummyAgile, { loadValue: false });
expect(persistent).toBeInstanceOf(Persistent);
expect(persistent.instantiatePersistent).not.toHaveBeenCalled();
expect(persistent._key).toBe(Persistent.placeHolderKey);
expect(persistent.ready).toBeFalsy();
expect(persistent.isPersisted).toBeFalsy();
expect(persistent.onLoad).toBeUndefined();
expect(persistent.storageKeys).toStrictEqual([]);
expect(persistent.config).toStrictEqual({ defaultStorageKey: null });
});
describe('Persistent Function Tests', () => {
let persistent: Persistent;
beforeEach(() => {
persistent = new Persistent(dummyAgile);
jest.clearAllMocks(); // Because creating Persistent executes some mocks
});
describe('key set function tests', () => {
it('should call setKey with passed value', () => {
persistent.setKey = jest.fn();
persistent.key = 'dummyKey';
expect(persistent.setKey).toHaveBeenCalledWith('dummyKey');
});
});
describe('ket get function tests', () => {
it('should get key property of Persistent', () => {
persistent._key = 'dummyKey';
expect(persistent.key).toBe('dummyKey');
});
});
describe('setKey function tests', () => {
beforeEach(() => {
persistent.removePersistedValue = jest.fn();
persistent.persistValue = jest.fn();
persistent.initialLoading = jest.fn();
});
it('should update key with valid key in ready Persistent', async () => {
persistent.ready = true;
persistent._key = 'dummyKey';
jest.spyOn(persistent, 'validatePersistent').mockReturnValueOnce(true);
await persistent.setKey('newKey');
expect(persistent._key).toBe('newKey');
expect(persistent.validatePersistent).toHaveBeenCalled();
expect(persistent.initialLoading).not.toHaveBeenCalled();
expect(persistent.persistValue).toHaveBeenCalledWith('newKey');
expect(persistent.removePersistedValue).toHaveBeenCalledWith(
'dummyKey'
);
});
it('should update key with not valid key in ready Persistent', async () => {
persistent.ready = true;
persistent._key = 'dummyKey';
jest.spyOn(persistent, 'validatePersistent').mockReturnValueOnce(false);
await persistent.setKey();
expect(persistent._key).toBe(Persistent.placeHolderKey);
expect(persistent.validatePersistent).toHaveBeenCalled();
expect(persistent.initialLoading).not.toHaveBeenCalled();
expect(persistent.persistValue).not.toHaveBeenCalled();
expect(persistent.removePersistedValue).toHaveBeenCalledWith(
'dummyKey'
);
});
it('should update key with valid key in not ready Persistent', async () => {
persistent.ready = false;
persistent._key = 'dummyKey';
jest.spyOn(persistent, 'validatePersistent').mockReturnValueOnce(true);
await persistent.setKey('newKey');
expect(persistent._key).toBe('newKey');
expect(persistent.validatePersistent).toHaveBeenCalled();
expect(persistent.initialLoading).toHaveBeenCalled();
expect(persistent.persistValue).not.toHaveBeenCalled();
expect(persistent.removePersistedValue).not.toHaveBeenCalled();
});
it('should update key with not valid key in not ready Persistent', async () => {
persistent.ready = false;
persistent._key = 'dummyKey';
jest.spyOn(persistent, 'validatePersistent').mockReturnValueOnce(false);
await persistent.setKey();
expect(persistent._key).toBe(Persistent.placeHolderKey);
expect(persistent.validatePersistent).toHaveBeenCalled();
expect(persistent.initialLoading).not.toHaveBeenCalled();
expect(persistent.persistValue).not.toHaveBeenCalled();
expect(persistent.removePersistedValue).not.toHaveBeenCalled();
});
});
describe('instantiatePersistent function tests', () => {
beforeEach(() => {
jest.spyOn(persistent, 'formatKey');
jest.spyOn(persistent, 'assignStorageKeys');
jest.spyOn(persistent, 'validatePersistent');
});
it(
'should call formatKey, assignStorageKeys, validatePersistent ' +
'and add Persistent to the shared Storage Manager if Persistent has a valid key',
() => {
persistent.instantiatePersistent({
key: 'persistentKey',
storageKeys: ['myName', 'is', 'jeff'],
defaultStorageKey: 'jeff',
});
expect(persistent._key).toBe('persistentKey');
expect(persistent.formatKey).toHaveBeenCalledWith('persistentKey');
expect(persistent.assignStorageKeys).toHaveBeenCalledWith(
['myName', 'is', 'jeff'],
'jeff'
);
expect(persistent.validatePersistent).toHaveBeenCalled();
expect(storageManager.persistentInstances).toHaveProperty(
'persistentKey'
);
expect(storageManager.persistentInstances['persistentKey']).toBe(
persistent
);
}
);
it(
'should call formatKey, assignStorageKeys, validatePersistent ' +
"and shouldn't add Persistent to the shared Storage Manager if Persistent has no valid key",
() => {
persistent.instantiatePersistent({
storageKeys: ['myName', 'is', 'jeff'],
defaultStorageKey: 'jeff',
});
expect(persistent._key).toBe(Persistent.placeHolderKey);
expect(persistent.formatKey).toHaveBeenCalledWith(undefined);
expect(persistent.assignStorageKeys).toHaveBeenCalledWith(
['myName', 'is', 'jeff'],
'jeff'
);
expect(persistent.validatePersistent).toHaveBeenCalled();
expect(storageManager.persistentInstances).not.toHaveProperty(
'persistentKey'
);
}
);
});
describe('validatePersistent function tests', () => {
beforeEach(() => {
persistent.key = Persistent.placeHolderKey;
persistent.config.defaultStorageKey = null;
persistent.storageKeys = [];
persistent.ready = undefined as any;
});
it('should return false and print error if no set key and no set StorageKeys', () => {
const isValid = persistent.validatePersistent();
expect(isValid).toBeFalsy();
expect(persistent.ready).toBeFalsy();
LogMock.hasLoggedCode('12:03:00');
});
it('should return false and print error if set key and no set StorageKeys', () => {
persistent._key = 'persistentKey';
const isValid = persistent.validatePersistent();
expect(isValid).toBeFalsy();
expect(persistent.ready).toBeFalsy();
LogMock.hasLoggedCode('12:03:01');
});
it('should return false and print error if no set key and set StorageKeys', () => {
persistent.config.defaultStorageKey = 'test';
persistent.storageKeys = ['test'];
const isValid = persistent.validatePersistent();
expect(isValid).toBeFalsy();
expect(persistent.ready).toBeFalsy();
LogMock.hasLoggedCode('12:03:00');
});
it('should return false and print error if set key and set StorageKeys but no existing Storage at storageKeys', () => {
persistent.config.defaultStorageKey = 'test';
persistent.storageKeys = ['test'];
const isValid = persistent.validatePersistent();
expect(isValid).toBeFalsy();
expect(persistent.ready).toBeFalsy();
LogMock.hasLoggedCode('12:03:00');
});
it('should return true if set key and set StorageKeys', () => {
storageManager.register(
createStorage({
key: 'test',
methods: {
get: () => {
/* empty */
},
set: () => {
/* empty */
},
remove: () => {
/* empty */
},
},
})
);
persistent._key = 'persistentKey';
persistent.config.defaultStorageKey = 'test';
persistent.storageKeys = ['test'];
const isValid = persistent.validatePersistent();
expect(isValid).toBeTruthy();
expect(persistent.ready).toBeTruthy();
});
});
describe('assignStorageKeys function tests', () => {
it(
'should assign specified StorageKeys and set first one as default StorageKey ' +
'if no default Storage Key was specified',
() => {
persistent.assignStorageKeys(['test1', 'test2', 'test3']);
expect(persistent.storageKeys).toStrictEqual([
'test1',
'test2',
'test3',
]);
expect(persistent.config.defaultStorageKey).toBe('test1');
}
);
it('should assign specified StorageKeys and assign specified defaultStorageKey as default StorageKey', () => {
persistent.assignStorageKeys(['test1', 'test2', 'test3'], 'test3');
expect(persistent.storageKeys).toStrictEqual([
'test1',
'test2',
'test3',
]);
expect(persistent.config.defaultStorageKey).toBe('test3');
});
it(
'should assign specified StorageKeys, set specified defaultStorageKey as default StorageKey' +
"and push defaultStorageKey into storageKeys if it isn't included there",
() => {
persistent.assignStorageKeys(['test1', 'test2', 'test3'], 'test4');
expect(persistent.storageKeys).toStrictEqual([
'test1',
'test2',
'test3',
'test4',
]);
expect(persistent.config.defaultStorageKey).toBe('test4');
}
);
it(
'should try to get default StorageKey from Agile if no StorageKey was specified ' +
'and assign it as StorageKey, if it is a valid StorageKey',
() => {
storageManager.register(
new Storage({
key: 'storage1',
methods: {
get: () => {
/* empty function */
},
set: () => {
/* empty function */
},
remove: () => {
/* empty function */
},
},
}),
{ default: true }
);
persistent.assignStorageKeys();
expect(persistent.storageKeys).toStrictEqual(['storage1']);
expect(persistent.config.defaultStorageKey).toBe('storage1');
}
);
it(
'should try to get default StorageKey from Agile if no StorageKey was specified ' +
"and shouldn't assign it as StorageKey, if it is no valid StorageKey",
() => {
persistent.assignStorageKeys();
expect(persistent.storageKeys).toStrictEqual([]);
expect(persistent.config.defaultStorageKey).toBeNull();
}
);
});
describe('initialLoading function tests', () => {
beforeEach(() => {
persistent.onLoad = jest.fn();
persistent.loadPersistedValue = jest.fn();
persistent.persistValue = jest.fn();
});
it("shouldn't call persistValue if value got successful loaded", async () => {
persistent.loadPersistedValue = jest.fn(() => Promise.resolve(true));
await persistent.initialLoading();
expect(persistent.loadPersistedValue).toHaveBeenCalled();
expect(persistent.persistValue).not.toHaveBeenCalled();
expect(persistent.onLoad).toHaveBeenCalledWith(true);
});
it("should call persistValue if value doesn't got successful loaded", async () => {
persistent.loadPersistedValue = jest.fn(() => Promise.resolve(false));
await persistent.initialLoading();
expect(persistent.loadPersistedValue).toHaveBeenCalled();
expect(persistent.persistValue).toHaveBeenCalled();
expect(persistent.onLoad).toHaveBeenCalledWith(false);
});
});
describe('loadPersistedValue function tests', () => {
it('should print error', () => {
persistent.loadPersistedValue();
LogMock.hasLoggedCode('00:03:00', ['loadPersistedValue', 'Persistent']);
});
});
describe('persistValue function tests', () => {
it('should print error', () => {
persistent.persistValue();
LogMock.hasLoggedCode('00:03:00', ['persistValue', 'Persistent']);
});
});
describe('removePersistedValue function tests', () => {
it('should print error', () => {
persistent.removePersistedValue();
LogMock.hasLoggedCode('00:03:00', [
'removePersistedValue',
'Persistent',
]);
});
describe('formatKey function tests', () => {
it('should return passed key', () => {
expect(persistent.formatKey('test')).toBe('test');
});
});
});
});
}); | the_stack |
import React, {Component} from 'react';
import {Row, Col, notification, Input, Button, Popconfirm} from 'antd'
import * as dagreD3 from 'dagre-d3/dist/dagre-d3'
import d3 from 'd3';
import './dagFix.less';
import * as ReactDOM from 'react-dom';
import EnumUtils from "../../../../common/utils/EnumUtils";
import CommonUtils from "../../../../common/utils/CommonUtils";
import {Flow, FlowModel} from "../../model/FlowModel";
import {kernel} from "../../../../common/utils/IOC";
import {TaskVersionModel} from "../../../taskVersion/model/TaskVersionModel";
import ResultUtils from "../../../../common/utils/ResultUtils";
/**
* 获取鼠标位置
* @returns {{x: any; y: any}}
*/
const getMousePosition = () => {
let e = window.event;
let scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
let scrollY = document.documentElement.scrollTop || document.body.scrollTop;
let x = e["pageX"] || e["clientX"] + scrollX;
let y = e["pageY"] || e["clientY"] + scrollY;
return {'x': x + 10, 'y': y + 10};
}
export interface DagFixProps {
height: number; //宽度
flow: Flow; //任务流
firstTaskVersionNo: number; //数据
}
/***
* 验证任务是否正确
* @param dagDatas
* @returns {boolean}
*/
const checkDatas = (dagDatas) => {
if (!dagDatas || !dagDatas["nodes"]) {
return false;
}
return true;
}
/**
* 获取点击事件
* @param isPreventDefault
* @returns {Event | undefined}
*/
const getEvent = (isPreventDefault) => {
const event = window.event;
if (isPreventDefault && isPreventDefault == true) {
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
}
return event;
};
/**
* 任务流修复
*/
class DagVersionFixShow extends Component<DagFixProps, any> {
private flowModel: FlowModel;
private taskVersionModel: TaskVersionModel;
private dagData: any = {};
private nodeId: number = 0;
constructor(pros) {
super(pros);
this.state = {
labelTop: 0,
labelLeft: 0,
//node右键菜单
showMenu: false,
nodeTop: 0,
nodeLeft: 0,
//任务详情
detailTop: 0,
detailLeft: 0,
showDetail: false
};
}
componentWillMount() {
this.flowModel = kernel.get(FlowModel);
this.taskVersionModel = kernel.get(TaskVersionModel);
this.getDataAndRender();
}
/**
* 获取数据并画图
*/
getDataAndRender() {
let that = this;
let id = this.props.flow.id;
const {flow, firstTaskVersionNo} = this.props;
this.flowModel.fixViewDag(flow.id, firstTaskVersionNo).then((result) => {
if (ResultUtils.isSuccess(result)) {
that.hideAllWindow();
const resultData = ResultUtils.getData(result);
that.dagData = resultData;
that.renderDag(resultData);
}
});
}
/**
* 隐藏窗口
*/
hideAllWindow = () => {
this.setState({showMenu: false, showDetail: false, showLabelMenu: false})
}
/**
* 渲染dag图
*/
renderDag = (dagData) => {
let that = this;
if (!checkDatas(dagData)) {
return;
}
let nodes = dagData["nodes"];
let links = dagData["links"];
// 获取dom节点
const svgDOMNode = ReactDOM.findDOMNode(this.refs.dag);
const svg = d3.select(svgDOMNode);
svg.selectAll("*").remove();
let inner = svg.append("g");
const renderDag = new dagreD3.render();
//创建graph对象
let conf = {
labelpos: "l",
nodesep: 70,
ranksep: 50,
marginx: 20,
marginy: 20
};
let g = new dagreD3.graphlib.Graph()
.setGraph(conf);
//添加节点
for (let node of nodes) {
g.setNode(node.id, {
label: node.taskName,
width: 266,
class: "dag-fix-node-" + node.finalStatus
});
}
// 添加节点关系
if (links && links.length > 0) {
for (let link of links) {
g.setEdge(link.upstreamVersionId, link.versionId, {
label: "",
labelStyle: 'width: 25px;height: 25px;text-align: center;line-height: 25px;'
});
}
}
//每个node添加radus
g.nodes().forEach(function (v) {
let node = g.node(v);
//每个节点
node.rx = node.ry = 5;
});
// render画布
renderDag(inner, g);
// 放大缩小、拖拽
let zoom = d3.behavior.zoom().on("zoom", function () {
inner.attr("transform", "translate(" + d3.event.translate + ")" +
"scale(" + d3.event.scale + ")");
});
svg.call(zoom);
/**
* 右键处理
*/
svg.selectAll("g.node").on("contextmenu", function (id) {
const event = getEvent(true);
let btnCode = event["button"];
if (btnCode != 2) {
return;
}
let position = getMousePosition();
that.nodeId = id; //设置节点id
that.setState({
showDetail: false,//隐藏详情
showMenu: true,
nodeTop: position["y"],
nodeLeft: position["x"]
});
});
/**
* 鼠标移动到node节点时
*/
svg.selectAll("g.node").on("mouseenter", function (id) {
const position = getMousePosition();
that.nodeId = id; //设置节点id
that.setState({
showDetail: true,
detailTop: position["y"],
detailLeft: position["x"]
});
});
/**
* 鼠标移出
*/
svg.selectAll("g.node").on("mouseleave", function (id) {
that.setState({
showDetail: false
});
});
svg.on("click", function () {
let e = window.event;
let btnCode = e["button"];
if (btnCode == 0) {
that.hideAllWindow();
}
});
//画布居中
let svgWidth = svg.attr("width") ? svg.attr("width") : svg.style("width");
let psIndex = svgWidth.indexOf("px");
if (psIndex >= 0) {
svgWidth = svgWidth.substring(0, psIndex);
}
const initialScale = 0.8;
zoom
.translate([(parseInt(svgWidth) - g.graph().width * initialScale) / 2, 20])
.scale(initialScale)
.event(svg);
svg.attr('height', g.graph().height * initialScale + 40);
}
/**
* 通过任务id获取任务数据
* @param id
* @returns {any}
*/
getTaskVersionById = (id) => {
let versions = this.dagData["nodes"];
let current = null;
if (versions) {
for (let version of versions) {
if (version.id == id) {
current = version;
break;
}
}
}
return current;
}
/**
* 提交任务流
* @returns {any}
*/
fixFlow() {
this.hideAllWindow();
const that = this;
const {flow, firstTaskVersionNo} = this.props;
this.flowModel.fixFlow(flow.id, firstTaskVersionNo)
.then((result) => {
if (ResultUtils.isSuccess(result)) {
notification["success"]({
message: '成功',
description: '操作成功',
});
that.getDataAndRender();
}
});
}
/**
* kill掉任务版本
* @returns {any}
*/
killVersion() {
this.hideAllWindow();
const versionId = this.nodeId;
const that = this;
this.taskVersionModel.fixById(versionId).then(result => {
if (ResultUtils.isSuccess(result)) {
notification["success"]({
message: '成功',
description: '操作成功',
});
that.getDataAndRender();
}
});
}
/**
* kill掉任务版本
* @returns {any}
*/
fixVersion() {
this.hideAllWindow();
const versionId = this.nodeId;
const that = this;
this.taskVersionModel.fixById(versionId).then(result => {
if (ResultUtils.isSuccess(result)) {
notification["success"]({
message: '成功',
description: '操作成功',
});
that.getDataAndRender();
}
});
}
/**
* kill掉任务版本
* @returns {any}
*/
fixVersionFromNode() {
this.hideAllWindow();
const versionId = this.nodeId;
const {flow, firstTaskVersionNo} = this.props;
const that = this;
this.flowModel.fixFromNode(flow.id, firstTaskVersionNo, versionId).then(result => {
if (ResultUtils.isSuccess(result)) {
notification["success"]({
message: '成功',
description: '操作成功',
});
that.getDataAndRender();
}
});
}
/**
* 忽略任务版本
* @returns {any}
*/
ignoreVersion() {
this.hideAllWindow();
const versionId = this.nodeId;
const that = this;
this.taskVersionModel.ignoreById(versionId).then(result => {
if (ResultUtils.isSuccess(result)) {
notification["success"]({
message: '成功',
description: '操作成功',
});
that.getDataAndRender();
}
});
}
render() {
const currentVersion = this.getTaskVersionById(this.nodeId);
const killBtn = (<div key={"kill-versionBtn"}>
<Popconfirm title={"确定KIll?"} key={"killVersionPop"}
onConfirm={this.killVersion.bind(this)}>
<Button key={"killVersionBtn"}>KILL</Button>
</Popconfirm>
</div>);
const ignoreBtn = (<div key={"ignore-versionBtn"}>
<Popconfirm title={"确定忽略?"} key={"ignoreVersionPop"}
onConfirm={this.ignoreVersion.bind(this)}>
<Button key={"successVersionBtn"}>忽略</Button>
</Popconfirm>
</div>);
/**
* 右键按钮判断
* @type {any[]}
*/
let rightMenuBtns = [];
if (currentVersion) {
const finalStatus = currentVersion.finalStatus;
if (finalStatus == EnumUtils.taskVersionFinalStatusUndefined) {
rightMenuBtns.push(killBtn);
}
if (finalStatus != EnumUtils.taskVersionFinalStatusSuccess) {
rightMenuBtns.push(ignoreBtn);
}
}
//按钮添加
let topBtns = [];
topBtns.push(<div>
<Popconfirm title={"确定修复任务流?"} onConfirm={this.fixFlow.bind(this)}>
<Button size={"large"} type={"primary"} icon={"tool"}>修复任务流</Button>
</Popconfirm>
</div>);
return (
<div className={"dag-fix-container"} key={"dagContainer"}
style={{width: "100%", height: this.props.height, margin: "0 auto"}}>
<svg ref={"dag"} style={{width: "100%", height: "100%"}}></svg>
<div className={"top-menu-container"}>
{topBtns}
</div>
: ""
{this.state.showMenu ?
<div className={"menu-container"} key={"menu2Container"}
style={{top: this.state.nodeTop, left: this.state.nodeLeft}}>
<div>
<Popconfirm title={"是否修复?"} key={"fixVersionPop"}
onConfirm={this.fixVersion.bind(this)}>
<Button key={"fixVersionBtn"}>修复当前节点</Button>
</Popconfirm>
</div>
<div>
<Popconfirm title={"是否从该节点修复任务流?"} key={"fixFlowPop"}
onConfirm={this.fixVersionFromNode.bind(this)}>
<Button key={"fixFlowBtn"}>从该节点修复</Button>
</Popconfirm>
</div>
{rightMenuBtns}
</div> : ""}
{this.state.showDetail ?
<div className={"detail-container"}
style={{top: this.state.detailTop, left: this.state.detailLeft}}>
<p><strong>id: </strong>{currentVersion.id}</p>
<p><strong>任务id: </strong>{currentVersion.taskId}</p>
<p><strong>任务名称: </strong>{currentVersion.taskName}</p>
<p><strong>任务版本: </strong>{currentVersion.versionNo}</p>
<p><strong>状态: </strong>{EnumUtils.getTaskVersionStatusName(currentVersion.status)}</p>
<p><strong>时间粒度: </strong>{EnumUtils.getPeriodName(currentVersion.taskPeriod)}</p>
<p><strong>时间规则: </strong>{currentVersion.taskCronExpression}</p>
<p><strong>描述: </strong>{currentVersion.taskDescription}</p>
<p><strong>信息: </strong>{currentVersion.msg}</p>
<p><strong>创建时间: </strong>{CommonUtils.dateFormat(currentVersion.createTime)}</p>
<p><strong>更新时间: </strong>{CommonUtils.dateFormat(currentVersion.updateTime)}</p>
</div> : ""}
</div>
)
}
}
export default DagVersionFixShow; | the_stack |
import { getStackJsonOutput, StackOutput } from '@aws-accelerator/common-outputs/src/stack-output';
import { getOutput, OutputUtilGenericType, SaveOutputsInput, getIndexOutput, saveIndexOutput } from './utils';
import {
SecurityGroupsOutput,
VpcOutputFinder,
VpcSecurityGroupOutput,
VpcSubnetOutput,
} from '@aws-accelerator/common-outputs/src/vpc';
import { ResolvedVpcConfig, SecurityGroupConfig, SubnetConfig } from '@aws-accelerator/common-config';
import { SSM } from '@aws-accelerator/common/src/aws/ssm';
import { Account } from '@aws-accelerator/common-outputs/src/accounts';
import { STS } from '@aws-accelerator/common/src/aws/sts';
interface OutputUtilSubnet extends OutputUtilGenericType {
azs: string[];
}
interface OutputUtilVpc extends OutputUtilGenericType {
subnets: OutputUtilSubnet[];
securityGroups: OutputUtilGenericType[];
type: 'vpc' | 'lvpc';
}
interface OutputUtilNetwork {
vpcs?: OutputUtilVpc[];
}
/**
* Outputs for network related deployments will be found in following phases
* - Phase-1
* - Phase-2
*/
/**
*
* @param outputsTableName
* @param client
* @param config
* @param account
*
* @returns void
*/
export async function saveNetworkOutputs(props: SaveOutputsInput) {
const {
acceleratorPrefix,
account,
config,
dynamodb,
outputsTableName,
assumeRoleName,
region,
outputUtilsTableName,
} = props;
const oldNetworkOutputUtils = await getIndexOutput(
outputUtilsTableName,
`${account.key}-${region}-network`,
dynamodb,
);
// Existing index check happens on this variable
let networkOutputUtils: OutputUtilNetwork;
if (oldNetworkOutputUtils) {
networkOutputUtils = oldNetworkOutputUtils;
} else {
networkOutputUtils = {
vpcs: [],
};
}
// Storing new resource index and updating DDB in this variable
const newNetworkOutputs: OutputUtilNetwork = {
vpcs: [],
};
if (!newNetworkOutputs.vpcs) {
newNetworkOutputs.vpcs = [];
}
// Removal from SSM Parameter store happens on left over in this variable
const removalObjects: OutputUtilNetwork = {
vpcs: [...(networkOutputUtils.vpcs || [])],
};
const vpcConfigs = config.getVpcConfigs();
const localVpcConfigs = vpcConfigs.filter(
vc => vc.accountKey === account.key && vc.vpcConfig.region === region && !vc.ouKey,
);
const localOuVpcConfigs = vpcConfigs.filter(
vc => vc.accountKey === account.key && vc.vpcConfig.region === region && vc.ouKey,
);
const sharedVpcConfigs = vpcConfigs.filter(
vc =>
vc.accountKey !== account.key &&
vc.vpcConfig.region === region &&
vc.ouKey === account.ou &&
(vc.vpcConfig.subnets?.find(sc => sc['share-to-ou-accounts']) ||
vc.vpcConfig.subnets?.find(sc => sc['share-to-specific-accounts']?.includes(account.key))),
);
let localOutputs: StackOutput[] = [];
if (localVpcConfigs.length > 0 || localOuVpcConfigs.length > 0) {
localOutputs = await getOutput(outputsTableName, `${account.key}-${region}-1`, dynamodb);
}
if (!networkOutputUtils.vpcs) {
networkOutputUtils.vpcs = [];
}
const lvpcIndices = networkOutputUtils.vpcs.filter(lv => lv.type === 'lvpc').flatMap(v => v.index) || [];
let lvpcMaxIndex = lvpcIndices.length === 0 ? 0 : Math.max(...lvpcIndices);
const sts = new STS();
const credentials = await sts.getCredentialsForAccountAndRole(account.id, assumeRoleName);
const ssm = new SSM(credentials, region);
for (const resolvedVpcConfig of localVpcConfigs) {
let currentIndex: number;
const previousIndex = networkOutputUtils.vpcs.findIndex(
vpc => vpc.type === 'lvpc' && vpc.name === resolvedVpcConfig.vpcConfig.name,
);
if (previousIndex >= 0) {
currentIndex = networkOutputUtils.vpcs[previousIndex].index;
} else {
currentIndex = ++lvpcMaxIndex;
}
const vpcResult = await saveVpcOutputs({
index: currentIndex,
resolvedVpcConfig,
outputs: localOutputs,
ssm,
acceleratorPrefix,
vpcPrefix: 'lvpc',
account,
vpcUtil: previousIndex >= 0 ? networkOutputUtils.vpcs[previousIndex] : undefined,
});
if (vpcResult) {
newNetworkOutputs.vpcs.push(vpcResult);
}
const removalIndex = removalObjects.vpcs?.findIndex(
vpc => vpc.type === 'lvpc' && vpc.name === resolvedVpcConfig.vpcConfig.name,
);
if (removalIndex! >= 0) {
removalObjects.vpcs?.splice(removalIndex!, 1);
}
}
const vpcIndices = networkOutputUtils.vpcs.filter(vpc => vpc.type === 'vpc').flatMap(v => v.index) || [];
let vpcMaxIndex = vpcIndices.length === 0 ? 0 : Math.max(...vpcIndices);
for (const resolvedVpcConfig of localOuVpcConfigs) {
let currentIndex: number;
const previousIndex = networkOutputUtils.vpcs.findIndex(
vpc => vpc.type === 'vpc' && vpc.name === resolvedVpcConfig.vpcConfig.name,
);
if (previousIndex >= 0) {
currentIndex = networkOutputUtils.vpcs[previousIndex].index;
} else {
currentIndex = ++vpcMaxIndex;
}
const vpcResult = await saveVpcOutputs({
index: currentIndex,
resolvedVpcConfig,
outputs: localOutputs,
ssm,
acceleratorPrefix,
vpcPrefix: 'vpc',
account,
vpcUtil: previousIndex >= 0 ? networkOutputUtils.vpcs[previousIndex] : undefined,
});
if (vpcResult) {
newNetworkOutputs.vpcs.push(vpcResult);
}
const removalIndex = removalObjects.vpcs?.findIndex(
vpc => vpc.type === 'vpc' && vpc.name === resolvedVpcConfig.vpcConfig.name,
);
if (removalIndex! >= 0) {
removalObjects.vpcs?.splice(removalIndex!, 1);
}
}
if (sharedVpcConfigs.length > 0) {
const sharedSgOutputs: StackOutput[] = await getOutput(outputsTableName, `${account.key}-${region}-2`, dynamodb);
const sgOutputs: SecurityGroupsOutput[] = getStackJsonOutput(sharedSgOutputs, {
accountKey: account.key,
outputType: 'SecurityGroupsOutput',
});
for (const resolvedVpcConfig of sharedVpcConfigs) {
let currentIndex: number;
const previousIndex = networkOutputUtils.vpcs.findIndex(
vpc => vpc.type === 'vpc' && vpc.name === resolvedVpcConfig.vpcConfig.name,
);
if (previousIndex >= 0) {
currentIndex = networkOutputUtils.vpcs[previousIndex].index;
} else {
currentIndex = ++vpcMaxIndex;
}
const rootOutputs: StackOutput[] = await getOutput(
outputsTableName,
`${resolvedVpcConfig.accountKey}-${region}-1`,
dynamodb,
);
const vpcSgOutputs = sgOutputs.find(sg => sg.vpcName);
const vpcResult = await saveVpcOutputs({
index: currentIndex,
resolvedVpcConfig,
outputs: rootOutputs,
ssm,
acceleratorPrefix,
vpcPrefix: 'vpc',
account,
sgOutputs: vpcSgOutputs?.securityGroupIds,
sharedVpc: true,
vpcUtil: previousIndex >= 0 ? networkOutputUtils.vpcs[previousIndex] : undefined,
});
if (vpcResult) {
newNetworkOutputs.vpcs.push(vpcResult);
}
const removalIndex = removalObjects.vpcs?.findIndex(
vpc => vpc.type === 'vpc' && vpc.name === resolvedVpcConfig.vpcConfig.name,
);
if (removalIndex! >= 0) {
removalObjects.vpcs?.splice(removalIndex!, 1);
}
}
}
await saveIndexOutput(
outputUtilsTableName,
`${account.key}-${region}-network`,
JSON.stringify(newNetworkOutputs),
dynamodb,
);
for (const removeObject of removalObjects.vpcs || []) {
const removalSgs = removeObject.securityGroups
.map(sg => [
`/${acceleratorPrefix}/network/${removeObject.type}/${removeObject.index}/sg/${sg.index}/name`,
`/${acceleratorPrefix}/network/${removeObject.type}/${removeObject.index}/sg/${sg.index}/id`,
])
.flatMap(s => s);
const removalSns = removeObject.subnets
.map(sn =>
sn.azs.map(snz => [
`/${acceleratorPrefix}/network/${removeObject.type}/${removeObject.index}/net/${sn.index}/az${snz}/name`,
`/${acceleratorPrefix}/network/${removeObject.type}/${removeObject.index}/net/${sn.index}/az${snz}/id`,
`/${acceleratorPrefix}/network/${removeObject.type}/${removeObject.index}/net/${sn.index}/az${snz}/cidr`,
]),
)
.flatMap(azSn => azSn)
.flatMap(sn => sn);
const removalVpc = [
`/${acceleratorPrefix}/network/${removeObject.type}/${removeObject.index}/name`,
`/${acceleratorPrefix}/network/${removeObject.type}/${removeObject.index}/id`,
`/${acceleratorPrefix}/network/${removeObject.type}/${removeObject.index}/cidr`,
`/${acceleratorPrefix}/network/${removeObject.type}/${removeObject.index}/cidr2`,
];
const removeNames = [...removalSgs, ...removalSns, ...removalVpc];
while (removeNames.length > 0) {
await ssm.deleteParameters(removeNames.splice(0, 10));
}
}
}
async function saveVpcOutputs(props: {
index: number;
resolvedVpcConfig: ResolvedVpcConfig;
outputs: StackOutput[];
ssm: SSM;
acceleratorPrefix: string;
vpcPrefix: 'vpc' | 'lvpc';
account: Account;
vpcUtil?: OutputUtilVpc;
sgOutputs?: VpcSecurityGroupOutput[];
sharedVpc?: boolean;
}): Promise<OutputUtilVpc | undefined> {
const { acceleratorPrefix, account, index, outputs, resolvedVpcConfig, ssm, vpcPrefix, sgOutputs, sharedVpc } = props;
const { accountKey, vpcConfig } = resolvedVpcConfig;
let vpcUtil: OutputUtilVpc;
if (props.vpcUtil) {
vpcUtil = props.vpcUtil;
} else {
vpcUtil = {
index,
name: vpcConfig.name,
securityGroups: [],
subnets: [],
type: vpcPrefix,
};
}
const vpcOutput = VpcOutputFinder.tryFindOneByAccountAndRegionAndName({
outputs,
accountKey,
vpcName: vpcConfig.name,
});
if (!vpcOutput) {
console.warn(`VPC "${vpcConfig.name}" in account "${accountKey}" is not created`);
return;
}
if (!vpcUtil.parameters) {
vpcUtil.parameters = [];
}
if (!vpcUtil.parameters.includes('name')) {
await ssm.putParameter(`/${acceleratorPrefix}/network/${vpcPrefix}/${index}/name`, `${vpcOutput.vpcName}_vpc`);
vpcUtil.parameters.push('name');
}
if (!vpcUtil.parameters.includes('id')) {
await ssm.putParameter(`/${acceleratorPrefix}/network/${vpcPrefix}/${index}/id`, vpcOutput.vpcId);
vpcUtil.parameters.push('id');
}
if (!vpcUtil.parameters.includes('cidr')) {
await ssm.putParameter(`/${acceleratorPrefix}/network/${vpcPrefix}/${index}/cidr`, vpcOutput.cidrBlock);
vpcUtil.parameters.push('cidr');
}
if (!vpcUtil.parameters.includes('cidr2') && vpcConfig.cidr.length > 1) {
for (const [cidrIndex, additionalCidr] of vpcOutput.additionalCidrBlocks.entries()) {
await ssm.putParameter(`/${acceleratorPrefix}/network/${vpcPrefix}/${index}/cidr2/${cidrIndex}`, additionalCidr);
}
vpcUtil.parameters.push('cidr2');
}
let subnetsConfig = vpcConfig.subnets;
if (sharedVpc) {
subnetsConfig = vpcConfig.subnets?.filter(
vs => vs['share-to-ou-accounts'] || vs['share-to-specific-accounts']?.includes(account.key),
);
}
if (subnetsConfig) {
vpcUtil.subnets = await saveSubnets({
subnetsConfig,
subnetOutputs: vpcOutput.subnets,
ssm,
vpcIndex: index,
acceleratorPrefix,
vpcPrefix,
vpcName: vpcConfig.name,
subnetsUtil: vpcUtil.subnets,
});
}
let vpcSgOutputs: VpcSecurityGroupOutput[] = vpcOutput.securityGroups;
if (sharedVpc) {
vpcSgOutputs = sgOutputs!;
}
if (vpcConfig['security-groups'] && vpcSgOutputs) {
vpcUtil.securityGroups = await saveSecurityGroups({
securityGroupsConfig: vpcConfig['security-groups'],
securityGroupsOutputs: vpcSgOutputs,
ssm,
vpcIndex: index,
acceleratorPrefix,
vpcPrefix,
securityGroupsUtil: vpcUtil.securityGroups,
});
}
console.log(vpcUtil);
return vpcUtil;
}
export async function saveSecurityGroups(props: {
securityGroupsConfig: SecurityGroupConfig[];
securityGroupsOutputs: VpcSecurityGroupOutput[];
ssm: SSM;
vpcIndex: number;
acceleratorPrefix: string;
vpcPrefix: string;
securityGroupsUtil: OutputUtilGenericType[];
}): Promise<OutputUtilGenericType[]> {
const {
acceleratorPrefix,
securityGroupsConfig,
securityGroupsOutputs,
ssm,
vpcIndex,
vpcPrefix,
securityGroupsUtil,
} = props;
const sgIndices = securityGroupsUtil.flatMap(r => r.index) || [];
let sgMaxIndex = sgIndices.length === 0 ? 0 : Math.max(...sgIndices);
const removalObjects = [...securityGroupsUtil];
const updatedObjects: OutputUtilGenericType[] = [];
for (const sgConfig of securityGroupsConfig) {
let currentIndex: number;
const previousIndex = securityGroupsUtil.findIndex(sg => sg.name === sgConfig.name);
if (previousIndex >= 0) {
currentIndex = securityGroupsUtil[previousIndex].index;
} else {
currentIndex = ++sgMaxIndex;
}
updatedObjects.push({
index: currentIndex,
name: sgConfig.name,
});
const sgOutput = securityGroupsOutputs.find(sg => sg.securityGroupName === sgConfig.name);
if (!sgOutput) {
console.warn(`Didn't find SecurityGroup "${sgConfig.name}" in output`);
continue;
}
if (previousIndex < 0) {
await ssm.putParameter(
`/${acceleratorPrefix}/network/${vpcPrefix}/${vpcIndex}/sg/${currentIndex}/name`,
`${sgConfig.name}_sg`,
);
await ssm.putParameter(
`/${acceleratorPrefix}/network/${vpcPrefix}/${vpcIndex}/sg/${currentIndex}/id`,
sgOutput.securityGroupId,
);
}
const removalIndex = removalObjects?.findIndex(r => r.name === sgConfig.name);
if (removalIndex >= 0) {
removalObjects?.splice(removalIndex, 1);
}
}
const removeNames = removalObjects
.map(sg => [
`/${acceleratorPrefix}/network/${vpcPrefix}/${vpcIndex}/sg/${sg.index}/name`,
`/${acceleratorPrefix}/network/${vpcPrefix}/${vpcIndex}/sg/${sg.index}/id`,
])
.flatMap(s => s);
while (removeNames.length > 0) {
await ssm.deleteParameters(removeNames.splice(0, 10));
}
return updatedObjects;
}
export async function saveSubnets(props: {
subnetsConfig: SubnetConfig[];
subnetOutputs: VpcSubnetOutput[];
ssm: SSM;
vpcIndex: number;
acceleratorPrefix: string;
vpcPrefix: string;
vpcName: string;
subnetsUtil: OutputUtilSubnet[];
}): Promise<OutputUtilSubnet[]> {
const { acceleratorPrefix, ssm, subnetOutputs, subnetsConfig, vpcIndex, vpcName, vpcPrefix, subnetsUtil } = props;
const subnetIndices = subnetsUtil.flatMap(s => s.index) || [];
let subnetMaxIndex = subnetIndices.length === 0 ? 0 : Math.max(...subnetIndices);
const removalObjects = [...subnetsUtil];
const updatedObjects: OutputUtilSubnet[] = [];
for (const subnetConfig of subnetsConfig || []) {
let currentIndex: number;
const previousIndex = subnetsUtil.findIndex(s => s.name === subnetConfig.name);
if (previousIndex >= 0) {
currentIndex = subnetsUtil[previousIndex].index;
} else {
currentIndex = ++subnetMaxIndex;
}
const newSubnetUtil: OutputUtilSubnet = {
index: currentIndex,
name: subnetConfig.name,
azs: subnetConfig.definitions.filter(sn => !sn.disabled).map(s => s.az),
};
for (const subnetDef of subnetConfig.definitions.filter(sn => !sn.disabled)) {
const subnetOutput = subnetOutputs.find(vs => vs.subnetName === subnetConfig.name && vs.az === subnetDef.az);
if (!subnetOutput) {
console.warn(`Didn't find subnet "${subnetConfig.name}" in output`);
continue;
}
if (previousIndex < 0 || (previousIndex >= 0 && !subnetsUtil[previousIndex].azs.includes(subnetDef.az))) {
await ssm.putParameter(
`/${acceleratorPrefix}/network/${vpcPrefix}/${vpcIndex}/net/${currentIndex}/az${subnetDef.az}/name`,
`${subnetOutput.subnetName}_${vpcName}_az${subnetOutput.az}_net`,
);
await ssm.putParameter(
`/${acceleratorPrefix}/network/${vpcPrefix}/${vpcIndex}/net/${currentIndex}/az${subnetOutput.az}/id`,
subnetOutput.subnetId,
);
await ssm.putParameter(
`/${acceleratorPrefix}/network/${vpcPrefix}/${vpcIndex}/net/${currentIndex}/az${subnetOutput.az}/cidr`,
subnetOutput.cidrBlock,
);
}
}
updatedObjects.push(newSubnetUtil);
const removalIndex = removalObjects?.findIndex(s => s.name === subnetConfig.name);
if (removalIndex >= 0) {
removalObjects?.splice(removalIndex, 1);
}
}
const removeNames = removalObjects
.map(sn =>
sn.azs.map(snz => [
`/${acceleratorPrefix}/network/${vpcPrefix}/${vpcIndex}/net/${sn.index}/az${snz}/name`,
`/${acceleratorPrefix}/network/${vpcPrefix}/${vpcIndex}/net/${sn.index}/az${snz}/id`,
`/${acceleratorPrefix}/network/${vpcPrefix}/${vpcIndex}/net/${sn.index}/az${snz}/cidr`,
]),
)
.flatMap(azSn => azSn)
.flatMap(sn => sn);
while (removeNames.length > 0) {
await ssm.deleteParameters(removeNames.splice(0, 10));
}
return updatedObjects;
} | the_stack |
declare module "php-parser" {
/**
* Defines an array structure
* @example
* // PHP code :
* [1, 'foo' => 'bar', 3]
*
* // AST structure :
* {
* "kind": "array",
* "shortForm": true
* "items": [
* {"kind": "number", "value": "1"},
* {
* "kind": "entry",
* "key": {"kind": "string", "value": "foo", "isDoubleQuote": false},
* "value": {"kind": "string", "value": "bar", "isDoubleQuote": false}
* },
* {"kind": "number", "value": "3"}
* ]
* }
* @property items - List of array items
* @property shortForm - Indicate if the short array syntax is used, ex `[]` instead `array()`
*/
class Array extends Expression {
/**
* List of array items
*/
items: Entry | Expression | Variable;
/**
* Indicate if the short array syntax is used, ex `[]` instead `array()`
*/
shortForm: boolean;
}
/**
* Defines an arrow function (it's like a closure)
*/
class ArrowFunc extends Expression {
arguments: Parameter[];
type: Identifier;
body: Expression;
byref: boolean;
nullable: boolean;
isStatic: boolean;
}
/**
* Assigns a value to the specified target
*/
class Assign extends Expression {
left: Expression;
right: Expression;
operator: string;
}
/**
* Assigns a value to the specified target
*/
class AssignRef extends Expression {
left: Expression;
right: Expression;
operator: string;
}
/**
* Binary operations
*/
class Bin extends Operation {
type: string;
left: Expression;
right: Expression;
}
/**
* A block statement, i.e., a sequence of statements surrounded by braces.
*/
class Block extends Statement {
children: Node[];
}
/**
* Defines a boolean value (true/false)
*/
class Boolean extends Literal {
}
/**
* A break statement
*/
class Break extends Statement {
level: number | null;
}
/**
* Passing by Reference - so the function can modify the variable
*/
class ByRef extends Expression {
what: ExpressionStatement;
}
/**
* Executes a call statement
*/
class Call extends Expression {
what: Identifier | Variable;
arguments: Variable[];
}
/**
* A switch case statement
* @property test - if null, means that the default case
*/
class Case extends Statement {
/**
* if null, means that the default case
*/
test: Expression | null;
body: Block | null;
}
/**
* Binary operations
*/
class Cast extends Operation {
type: string;
raw: string;
expr: Expression;
}
/**
* Defines a catch statement
*/
class Catch extends Statement {
what: Identifier[];
variable: Variable;
body: Statement;
}
/**
* A class definition
*/
class Class extends Declaration {
extends: Identifier | null;
implements: Identifier[];
body: Declaration[];
isAnonymous: boolean;
isAbstract: boolean;
isFinal: boolean;
}
/**
* Defines a class/interface/trait constant
*/
class ClassConstant extends ConstantStatement {
/**
* Generic flags parser
*/
parseFlags(flags: (number | null)[]): void;
visibility: string;
}
/**
* Defines a clone call
*/
class Clone extends Expression {
what: Expression;
}
/**
* Defines a closure
*/
class Closure extends Expression {
arguments: Parameter[];
uses: Variable[];
type: Identifier;
byref: boolean;
nullable: boolean;
body: Block | null;
isStatic: boolean;
}
/**
* Abstract documentation node (ComentLine or CommentBlock)
*/
class Comment extends Node {
value: string;
}
/**
* A comment block (multiline)
*/
class CommentBlock extends Comment {
}
/**
* A single line comment
*/
class CommentLine extends Comment {
}
/**
* Defines a constant
*/
class Constant extends Node {
name: string;
value: Node | string | number | boolean | null;
}
/**
* Declares a constants into the current scope
*/
class ConstantStatement extends Statement {
constants: Constant[];
}
/**
* A continue statement
*/
class Continue extends Statement {
level: number | null;
}
/**
* A declaration statement (function, class, interface...)
*/
class Declaration extends Statement {
/**
* Generic flags parser
*/
parseFlags(flags: (number | null)[]): void;
name: Identifier | string;
}
/**
* The declare construct is used to set execution directives for a block of code
*/
class Declare extends Block {
/**
* The node is declared as a short tag syntax :
* ```php
* <?php
* declare(ticks=1):
* // some statements
* enddeclare;
* ```
*/
readonly MODE_SHORT: string;
/**
* The node is declared bracket enclosed code :
* ```php
* <?php
* declare(ticks=1) {
* // some statements
* }
* ```
*/
readonly MODE_BLOCK: string;
/**
* The node is declared as a simple statement. In order to make things simpler
* children of the node are automatically collected until the next
* declare statement.
* ```php
* <?php
* declare(ticks=1);
* // some statements
* declare(ticks=2);
* // some statements
* ```
*/
readonly MODE_NONE: string;
directives: any[][];
mode: string;
}
/**
* Defines a constant
*/
class DeclareDirective extends Node {
name: Identifier;
value: Node | string | number | boolean | null;
}
/**
* Defines a do/while statement
*/
class Do extends Statement {
test: Expression;
body: Statement;
}
/**
* Defines system based call
*/
class Echo extends Statement {
shortForm: boolean;
}
/**
* Defines an empty check call
*/
class Empty extends Expression {
}
/**
* Defines an encapsed string (contains expressions)
* @property type - Defines the type of encapsed string (shell, heredoc, string)
* @property label - The heredoc label, defined only when the type is heredoc
*/
class Encapsed extends Literal {
/**
* The node is a double quote string :
* ```php
* <?php
* echo "hello $world";
* ```
*/
readonly TYPE_STRING: string;
/**
* The node is a shell execute string :
* ```php
* <?php
* echo `ls -larth $path`;
* ```
*/
readonly TYPE_SHELL: string;
/**
* The node is a shell execute string :
* ```php
* <?php
* echo <<<STR
* Hello $world
* STR
* ;
* ```
*/
readonly TYPE_HEREDOC: string;
/**
* The node contains a list of constref / variables / expr :
* ```php
* <?php
* echo $foo->bar_$baz;
* ```
*/
readonly TYPE_OFFSET: string;
/**
* Defines the type of encapsed string (shell, heredoc, string)
*/
type: string;
/**
* The heredoc label, defined only when the type is heredoc
*/
label: string | null;
}
/**
* Part of `Encapsed` node
*/
class EncapsedPart extends Expression {
expression: Expression;
syntax: string;
curly: boolean;
}
/**
* An array entry - see [Array](#array)
* @property key - The entry key/offset
* @property value - The entry value
* @property byRef - By reference
* @property unpack - Argument unpacking
*/
class Entry extends Expression {
/**
* The entry key/offset
*/
key: Node | null;
/**
* The entry value
*/
value: Node;
/**
* By reference
*/
byRef: boolean;
/**
* Argument unpacking
*/
unpack: boolean;
}
/**
* Defines an error node (used only on silentMode)
*/
class Error extends Node {
message: string;
line: number;
token: number | string;
expected: string | any[];
}
/**
* Defines an eval statement
*/
class Eval extends Expression {
source: Node;
}
/**
* Defines an exit / die call
*/
class Exit extends Expression {
expression: Node | null;
useDie: boolean;
}
/**
* Any expression node. Since the left-hand side of an assignment may
* be any expression in general, an expression can also be a pattern.
*/
class Expression extends Node {
}
/**
* Defines an expression based statement
*/
class ExpressionStatement extends Statement {
expression: Expression;
}
/**
* Defines a for iterator
*/
class For extends Statement {
init: Expression[];
test: Expression[];
increment: Expression[];
body: Statement;
shortForm: boolean;
}
/**
* Defines a foreach iterator
*/
class Foreach extends Statement {
source: Expression;
key: Expression | null;
value: Expression;
body: Statement;
shortForm: boolean;
}
/**
* Defines a classic function
*/
class Function extends Declaration {
arguments: Parameter[];
type: Identifier;
byref: boolean;
nullable: boolean;
body: Block | null;
}
/**
* Imports a variable from the global scope
*/
class Global extends Statement {
items: Variable[];
}
/**
* Defines goto statement
*/
class Goto extends Statement {
label: string;
}
/**
* Halts the compiler execution
* @property after - String after the halt statement
*/
class Halt extends Statement {
/**
* String after the halt statement
*/
after: string;
}
/**
* Defines an identifier node
*/
class Identifier extends Node {
name: string;
}
/**
* Defines a if statement
*/
class If extends Statement {
test: Expression;
body: Block;
alternate: Block | If | null;
shortForm: boolean;
}
/**
* Defines system include call
*/
class Include extends Expression {
target: Node;
once: boolean;
require: boolean;
}
/**
* Defines inline html output (treated as echo output)
*/
class Inline extends Literal {
}
/**
* An interface definition
*/
class Interface extends Declaration {
extends: Identifier[];
body: Declaration[];
}
/**
* Defines an isset call
*/
class Isset extends Expression {
}
/**
* A label statement (referenced by goto)
*/
class Label extends Statement {
name: string;
}
/**
* Defines list assignment
*/
class List extends Expression {
shortForm: boolean;
}
/**
* Defines an array structure
*/
class Literal extends Expression {
raw: string;
value: Node | string | number | boolean | null;
}
/**
* Defines the location of the node (with it's source contents as string)
*/
class Location {
source: string | null;
start: Position;
end: Position;
}
/**
* Lookup on an offset in the specified object
*/
class Lookup extends Expression {
what: Expression;
offset: Expression;
}
/**
* Defines magic constant
*/
class Magic extends Literal {
}
/**
* Defines a class/interface/trait method
*/
class Method extends Function {
isAbstract: boolean;
isFinal: boolean;
isStatic: boolean;
visibility: string;
}
/**
* Defines a class reference node
*/
class Name extends Reference {
/**
* This is an identifier without a namespace separator, such as Foo
*/
readonly UNQUALIFIED_NAME: string;
/**
* This is an identifier with a namespace separator, such as Foo\Bar
*/
readonly QUALIFIED_NAME: string;
/**
* This is an identifier with a namespace separator that begins with
* a namespace separator, such as \Foo\Bar. The namespace \Foo is also
* a fully qualified name.
*/
readonly FULL_QUALIFIED_NAME: string;
/**
* This is an identifier starting with namespace, such as namespace\Foo\Bar.
*/
readonly RELATIVE_NAME: string;
name: string;
resolution: string;
}
/**
* The main program node
*/
class Namespace extends Block {
name: string;
withBrackets: boolean;
}
/**
* Creates a new instance of the specified class
*/
class New extends Expression {
what: Identifier | Variable | Class;
arguments: Variable[];
}
/**
* A generic AST node
*/
class Node {
/**
* Attach comments to current node
*/
setTrailingComments(docs: any): void;
/**
* Destroying an unused node
*/
destroy(): void;
/**
* Includes current token position of the parser
*/
includeToken(parser: any): void;
/**
* Helper for extending the Node class
*/
static extends(type: string, constructor: (...params: any[]) => any): (...params: any[]) => any;
loc: Location | null;
leadingComments: CommentBlock[] | Comment[] | null;
trailingComments: CommentBlock[] | Comment[] | null;
kind: string;
}
/**
* Ignore this node, it implies a no operation block, for example :
* [$foo, $bar, /* here a noop node * /]
*/
class Noop extends Node {
}
/**
* Defines a nowdoc string
*/
class NowDoc extends Literal {
label: string;
raw: string;
}
/**
* Represents the null keyword
*/
class NullKeyword extends Node {
}
/**
* Defines a numeric value
*/
class Number extends Literal {
}
/**
* Lookup on an offset in an array
*/
class OffsetLookup extends Lookup {
}
/**
* Defines binary operations
*/
class Operation extends Expression {
}
/**
* Defines a function parameter
*/
class Parameter extends Declaration {
type: Identifier | null;
value: Node | null;
byref: boolean;
variadic: boolean;
nullable: boolean;
}
/**
* Defines a class reference node
*/
class ParentReference extends Reference {
}
/**
* Each Position object consists of a line number (1-indexed) and a column number (0-indexed):
*/
class Position {
line: number;
column: number;
offset: number;
}
/**
* Defines a post operation `$i++` or `$i--`
*/
class Post extends Operation {
type: string;
what: Variable;
}
/**
* Defines a pre operation `++$i` or `--$i`
*/
class Pre extends Operation {
type: string;
what: Variable;
}
/**
* Outputs
*/
class Print extends Expression {
}
/**
* The main program node
*/
class Program extends Block {
errors: Error[];
comments: Comment[] | null;
tokens: String[] | null;
}
/**
* Defines a class property
*/
class Property extends Statement {
name: string;
value: Node | null;
nullable: boolean;
type: Identifier | Identifier[] | null;
}
/**
* Lookup to an object property
*/
class PropertyLookup extends Lookup {
}
/**
* Declares a properties into the current scope
*/
class PropertyStatement extends Statement {
/**
* Generic flags parser
*/
parseFlags(flags: (number | null)[]): void;
properties: Property[];
}
/**
* Defines a reference node
*/
class Reference extends Node {
}
/**
* Defines a short if statement that returns a value
*/
class RetIf extends Expression {
test: Expression;
trueExpr: Expression;
falseExpr: Expression;
}
/**
* A continue statement
*/
class Return extends Statement {
expr: Expression | null;
}
/**
* Defines a class reference node
*/
class SelfReference extends Reference {
}
/**
* Avoids to show/log warnings & notices from the inner expression
*/
class Silent extends Expression {
expr: Expression;
}
/**
* Any statement.
*/
class Statement extends Node {
}
/**
* Declares a static variable into the current scope
*/
class Static extends Statement {
variables: StaticVariable[];
}
/**
* Lookup to a static property
*/
class StaticLookup extends Lookup {
}
/**
* Defines a class reference node
*/
class StaticReference extends Reference {
}
/**
* Defines a constant
*/
class StaticVariable extends Node {
variable: Variable;
defaultValue: Node | string | number | boolean | null;
}
/**
* Defines a string (simple or double quoted) - chars are already escaped
*/
class String extends Literal {
unicode: boolean;
isDoubleQuote: boolean;
}
/**
* Defines a switch statement
*/
class Switch extends Statement {
test: Expression;
body: Block;
shortForm: boolean;
}
/**
* Defines a throw statement
*/
class Throw extends Statement {
what: Expression;
}
/**
* A trait definition
*/
class Trait extends Declaration {
body: Declaration[];
}
/**
* Defines a trait alias
*/
class TraitAlias extends Node {
trait: Identifier | null;
method: Identifier;
as: Identifier | null;
visibility: string | null;
}
/**
* Defines a trait alias
*/
class TraitPrecedence extends Node {
trait: Identifier | null;
method: Identifier;
instead: Identifier[];
}
/**
* Defines a trait usage
*/
class TraitUse extends Node {
traits: Identifier[];
adaptations: Node[] | null;
}
/**
* Defines a try statement
*/
class Try extends Statement {
body: Block;
catches: Catch[];
allways: Block;
}
/**
* Defines a class reference node
*/
class TypeReference extends Reference {
name: string;
}
/**
* Unary operations
*/
class Unary extends Operation {
type: string;
what: Expression;
}
/**
* Deletes references to a list of variables
*/
class Unset extends Statement {
}
/**
* Defines a use statement (with a list of use items)
* @property type - Possible value : function, const
*/
class UseGroup extends Statement {
name: string | null;
/**
* Possible value : function, const
*/
type: string | null;
item: UseItem[];
}
/**
* Defines a use statement (from namespace)
* @property type - Possible value : function, const
*/
class UseItem extends Statement {
/**
* Importing a constant
*/
readonly TYPE_CONST: string;
/**
* Importing a function
*/
readonly TYPE_FUNC: string;
name: string;
/**
* Possible value : function, const
*/
type: string | null;
alias: Identifier | null;
}
/**
* Any expression node. Since the left-hand side of an assignment may
* be any expression in general, an expression can also be a pattern.
* @example
* // PHP code :
* $foo
* // AST output
* {
* "kind": "variable",
* "name": "foo",
* "curly": false
* }
* @property name - The variable name (can be a complex expression when the name is resolved dynamically)
* @property curly - Indicate if the name is defined between curlies, ex `${foo}`
*/
class Variable extends Expression {
/**
* The variable name (can be a complex expression when the name is resolved dynamically)
*/
name: string | Node;
/**
* Indicate if the name is defined between curlies, ex `${foo}`
*/
curly: boolean;
}
/**
* Introduce a list of items into the arguments of the call
*/
class Variadic extends Expression {
what: any[] | Expression;
}
/**
* Defines a while statement
*/
class While extends Statement {
test: Expression;
body: Statement;
shortForm: boolean;
}
/**
* Defines a yield generator statement
*/
class Yield extends Expression {
value: Expression | null;
key: Expression | null;
}
/**
* Defines a yield from generator statement
*/
class YieldFrom extends Expression {
value: Expression;
}
/**
* The AST builder class
* @property withPositions - Should locate any node (by default false)
* @property withSource - Should extract the node original code (by default false)
*/
class AST {
/**
* Should locate any node (by default false)
*/
withPositions: boolean;
/**
* Should extract the node original code (by default false)
*/
withSource: boolean;
}
/**
* Initialise a new parser instance with the specified options
* @example
* var parser = require('php-parser');
* var instance = new parser({
* parser: {
* extractDoc: true,
* suppressErrors: true,
* version: 704 // or '7.4'
* },
* ast: {
* withPositions: true
* },
* lexer: {
* short_tags: true,
* asp_tags: true
* }
* });
*
* var evalAST = instance.parseEval('some php code');
* var codeAST = instance.parseCode('<?php some php code', 'foo.php');
* var tokens = instance.tokenGetAll('<?php some php code');
* @param options - List of options
*/
class Engine {
constructor(options: any);
/**
* Parse an evaluating mode string (no need to open php tags)
*/
parseEval(buffer: string): Program;
/**
* Function that parse a php code with open/close tags
*
* Sample code :
* ```php
* <?php $x = 1;
* ```
*
* Usage :
* ```js
* var parser = require('php-parser');
* var phpParser = new parser({
* // some options
* });
* var ast = phpParser.parseCode('...php code...', 'foo.php');
* ```
* @param buffer - The code to be parsed
* @param filename - Filename
*/
parseCode(buffer: string, filename: string): Program;
/**
* Extract tokens from the specified buffer.
* > Note that the output tokens are *STRICLY* similar to PHP function `token_get_all`
* @returns - Each item can be a string or an array with following informations [token_name, text, line_number]
*/
tokenGetAll(buffer: string): String[];
lexer: Lexer;
parser: Parser;
ast: AST;
tokens: any;
}
/**
* This is the php lexer. It will tokenize the string for helping the
* parser to build the AST from its grammar.
* @property all_tokens - defines if all tokens must be retrieved (used by token_get_all only)
* @property comment_tokens - extracts comments tokens
* @property mode_eval - enables the evald mode (ignore opening tags)
* @property asp_tags - disables by default asp tags mode
* @property short_tags - enables by default short tags mode
* @property keywords - List of php keyword
* @property castKeywords - List of php keywords for type casting
*/
class Lexer {
/**
* Initialize the lexer with the specified input
*/
setInput(): void;
/**
* consumes and returns one char from the input
*/
input(): void;
/**
* revert eating specified size
*/
unput(): void;
/**
* check if the text matches
*/
tryMatch(text: string): boolean;
/**
* check if the text matches
*/
tryMatchCaseless(text: string): boolean;
/**
* look ahead
*/
ahead(size: number): string;
/**
* consume the specified size
*/
consume(size: number): Lexer;
/**
* Gets the current state
*/
getState(): void;
/**
* Sets the current lexer state
*/
setState(): void;
/**
* prepend next token
*/
appendToken(value: any, ahead: any): Lexer;
/**
* return next match that has a token
*/
lex(): number | string;
/**
* activates a new lexer condition state (pushes the new lexer condition state onto the condition stack)
*/
begin(condition: any): Lexer;
/**
* pop the previously active lexer condition state off the condition stack
*/
popState(): string | any;
/**
* return next match in input
*/
next(): number | any;
EOF: number;
/**
* defines if all tokens must be retrieved (used by token_get_all only)
*/
all_tokens: boolean;
/**
* extracts comments tokens
*/
comment_tokens: boolean;
/**
* enables the evald mode (ignore opening tags)
*/
mode_eval: boolean;
/**
* disables by default asp tags mode
*/
asp_tags: boolean;
/**
* enables by default short tags mode
*/
short_tags: boolean;
/**
* List of php keyword
*/
keywords: any;
/**
* List of php keywords for type casting
*/
castKeywords: any;
}
/**
* The PHP Parser class that build the AST tree from the lexer
* @property lexer - current lexer instance
* @property ast - the AST factory instance
* @property token - current token
* @property extractDoc - should extract documentation as AST node
* @property extractTokens - should extract each token
* @property suppressErrors - should ignore parsing errors and continue
* @property debug - should output debug informations
*/
class Parser {
/**
* helper : gets a token name
*/
getTokenName(): void;
/**
* main entry point : converts a source code to AST
*/
parse(): void;
/**
* Raise an error
*/
raiseError(): void;
/**
* handling errors
*/
error(): void;
/**
* Creates a new AST node
*/
node(): void;
/**
* expects an end of statement or end of file
*/
expectEndOfStatement(): boolean;
/**
* Force the parser to check the current token.
*
* If the current token does not match to expected token,
* the an error will be raised.
*
* If the suppressError mode is activated, then the error will
* be added to the program error stack and this function will return `false`.
*/
expect(token: string | number): boolean;
/**
* Returns the current token contents
*/
text(): string;
/**
* consume the next token
*/
next(): void;
/**
* Eating a token
*/
lex(): void;
/**
* Check if token is of specified type
*/
is(): void;
/**
* current lexer instance
*/
lexer: Lexer;
/**
* the AST factory instance
*/
ast: AST;
/**
* current token
*/
token: number | string;
/**
* should extract documentation as AST node
*/
extractDoc: boolean;
/**
* should extract each token
*/
extractTokens: boolean;
/**
* should ignore parsing errors and continue
*/
suppressErrors: boolean;
/**
* should output debug informations
*/
debug: boolean;
}
const enum TokenNames {
T_HALT_COMPILER = 101,
T_USE = 102,
T_ENCAPSED_AND_WHITESPACE = 103,
T_OBJECT_OPERATOR = 104,
T_STRING = 105,
T_DOLLAR_OPEN_CURLY_BRACES = 106,
T_STRING_VARNAME = 107,
T_CURLY_OPEN = 108,
T_NUM_STRING = 109,
T_ISSET = 110,
T_EMPTY = 111,
T_INCLUDE = 112,
T_INCLUDE_ONCE = 113,
T_EVAL = 114,
T_REQUIRE = 115,
T_REQUIRE_ONCE = 116,
T_NAMESPACE = 117,
T_NS_SEPARATOR = 118,
T_AS = 119,
T_IF = 120,
T_ENDIF = 121,
T_WHILE = 122,
T_DO = 123,
T_FOR = 124,
T_SWITCH = 125,
T_BREAK = 126,
T_CONTINUE = 127,
T_RETURN = 128,
T_GLOBAL = 129,
T_STATIC = 130,
T_ECHO = 131,
T_INLINE_HTML = 132,
T_UNSET = 133,
T_FOREACH = 134,
T_DECLARE = 135,
T_TRY = 136,
T_THROW = 137,
T_GOTO = 138,
T_FINALLY = 139,
T_CATCH = 140,
T_ENDDECLARE = 141,
T_LIST = 142,
T_CLONE = 143,
T_PLUS_EQUAL = 144,
T_MINUS_EQUAL = 145,
T_MUL_EQUAL = 146,
T_DIV_EQUAL = 147,
T_CONCAT_EQUAL = 148,
T_MOD_EQUAL = 149,
T_AND_EQUAL = 150,
T_OR_EQUAL = 151,
T_XOR_EQUAL = 152,
T_SL_EQUAL = 153,
T_SR_EQUAL = 154,
T_INC = 155,
T_DEC = 156,
T_BOOLEAN_OR = 157,
T_BOOLEAN_AND = 158,
T_LOGICAL_OR = 159,
T_LOGICAL_AND = 160,
T_LOGICAL_XOR = 161,
T_SL = 162,
T_SR = 163,
T_IS_IDENTICAL = 164,
T_IS_NOT_IDENTICAL = 165,
T_IS_EQUAL = 166,
T_IS_NOT_EQUAL = 167,
T_IS_SMALLER_OR_EQUAL = 168,
T_IS_GREATER_OR_EQUAL = 169,
T_INSTANCEOF = 170,
T_INT_CAST = 171,
T_DOUBLE_CAST = 172,
T_STRING_CAST = 173,
T_ARRAY_CAST = 174,
T_OBJECT_CAST = 175,
T_BOOL_CAST = 176,
T_UNSET_CAST = 177,
T_EXIT = 178,
T_PRINT = 179,
T_YIELD = 180,
T_YIELD_FROM = 181,
T_FUNCTION = 182,
T_DOUBLE_ARROW = 183,
T_DOUBLE_COLON = 184,
T_ARRAY = 185,
T_CALLABLE = 186,
T_CLASS = 187,
T_ABSTRACT = 188,
T_TRAIT = 189,
T_FINAL = 190,
T_EXTENDS = 191,
T_INTERFACE = 192,
T_IMPLEMENTS = 193,
T_VAR = 194,
T_PUBLIC = 195,
T_PROTECTED = 196,
T_PRIVATE = 197,
T_CONST = 198,
T_NEW = 199,
T_INSTEADOF = 200,
T_ELSEIF = 201,
T_ELSE = 202,
T_ENDSWITCH = 203,
T_CASE = 204,
T_DEFAULT = 205,
T_ENDFOR = 206,
T_ENDFOREACH = 207,
T_ENDWHILE = 208,
T_CONSTANT_ENCAPSED_STRING = 209,
T_LNUMBER = 210,
T_DNUMBER = 211,
T_LINE = 212,
T_FILE = 213,
T_DIR = 214,
T_TRAIT_C = 215,
T_METHOD_C = 216,
T_FUNC_C = 217,
T_NS_C = 218,
T_START_HEREDOC = 219,
T_END_HEREDOC = 220,
T_CLASS_C = 221,
T_VARIABLE = 222,
T_OPEN_TAG = 223,
T_OPEN_TAG_WITH_ECHO = 224,
T_CLOSE_TAG = 225,
T_WHITESPACE = 226,
T_COMMENT = 227,
T_DOC_COMMENT = 228,
T_ELLIPSIS = 229,
T_COALESCE = 230,
T_POW = 231,
T_POW_EQUAL = 232,
T_SPACESHIP = 233,
T_COALESCE_EQUAL = 234,
T_FN = 235
}
/**
* PHP AST Tokens
*/
const tokens: {
values: {
[key: number]: string;
};
names: TokenNames;
};
} | the_stack |
export type NumberProp = string | number;
export type NumberArrayProp = [NumberProp] | NumberProp;
export interface FillProps {
fill?: string;
fillOpacity?: NumberProp;
fillRule?: 'evenodd' | 'nonzero';
}
export interface ClipProps {
clipRule?: 'evenodd' | 'nonzero';
clipPath?: string;
}
export interface DefinationProps {
name?: string;
}
export interface StrokeProps {
stroke?: string;
strokeWidth?: NumberProp;
strokeOpacity?: NumberProp;
strokeDasharray?: NumberArrayProp;
strokeDashoffset?: NumberProp;
strokeLinecap?: 'butt' | 'square' | 'round';
strokeLinejoin?: 'miter' | 'bevel' | 'round';
strokeMiterlimit?: NumberProp;
}
export interface TransformProps {
scale?: NumberProp;
scaleX?: NumberProp;
scaleY?: NumberProp;
rotate?: NumberProp;
rotation?: NumberProp;
translate?: NumberProp;
translateX?: NumberProp;
translateY?: NumberProp;
x?: NumberProp;
y?: NumberProp;
origin?: NumberProp;
originX?: NumberProp;
originY?: NumberProp;
skew?: NumberProp;
skewX?: NumberProp;
skewY?: NumberProp;
transform?: object | string;
}
export interface PathProps
extends FillProps,
StrokeProps,
ClipProps,
TransformProps,
DefinationProps {}
// normal | italic | oblique | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-style
export type FontStyle = 'normal' | 'italic' | 'oblique';
// normal | small-caps | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-variant
export type FontVariant = 'normal' | 'small-caps';
// normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-weight
export type FontWeight =
| 'normal'
| 'bold'
| 'bolder'
| 'lighter'
| '100'
| '200'
| '300'
| '400'
| '500'
| '600'
| '700'
| '800'
| '900';
// normal | wider | narrower | ultra-condensed | extra-condensed |
// condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-stretch
export type FontStretch =
| 'normal'
| 'wider'
| 'narrower'
| 'ultra-condensed'
| 'extra-condensed'
| 'condensed'
| 'semi-condensed'
| 'semi-expanded'
| 'expanded'
| 'extra-expanded'
| 'ultra-expanded';
// <absolute-size> | <relative-size> | <length> | <percentage> | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-size
export type fontSize = NumberProp;
// [[<family-name> | <generic-family>],]* [<family-name> | <generic-family>] | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-family
export type FontFamily = string;
/*
font syntax [ [ <'font-style'> || <font-variant-css21> ||
<'font-weight'> || <'font-stretch'> ]? <'font-size'> [ / <'line-height'> ]? <'font-family'> ] |
caption | icon | menu | message-box | small-caption | status-bar
where <font-variant-css21> = [ normal | small-caps ]
Shorthand property for setting ‘font-style’, ‘font-variant’,
‘font-weight’, ‘font-size’, ‘line-height’ and ‘font-family’.
The ‘line-height’ property has no effect on text layout in SVG.
Note: for the purposes of processing the ‘font’ property in SVG,
'line-height' is assumed to be equal the value for property ‘font-size’
https://www.w3.org/TR/SVG11/text.html#FontProperty
https://developer.mozilla.org/en-US/docs/Web/CSS/font
https://drafts.csswg.org/css-fonts-3/#font-prop
https://www.w3.org/TR/CSS2/fonts.html#font-shorthand
https://www.w3.org/TR/CSS1/#font
*/
export type Font = object;
// start | middle | end | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-anchor
export type TextAnchor = 'start' | 'middle' | 'end';
// none | underline | overline | line-through | blink | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-decoration
export type TextDecoration =
| 'none'
| 'underline'
| 'overline'
| 'line-through'
| 'blink';
// normal | <length> | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/letter-spacing
export type LetterSpacing = NumberProp;
// normal | <length> | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/word-spacing
export type WordSpacing = NumberProp;
// auto | <length> | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/kerning
export type Kerning = NumberProp;
/*
Name: font-variant-ligatures
Value: normal | none | [ <common-lig-values> || <discretionary-lig-values> ||
<historical-lig-values> || <contextual-alt-values> ]
Initial: normal
Applies to: all elements
Inherited: yes
Percentages: N/A
Media: visual
Computed value: as specified
Animatable: no
Ligatures and contextual forms are ways of combining glyphs to produce more harmonized forms.
<common-lig-values> = [ common-ligatures | no-common-ligatures ]
<discretionary-lig-values> = [ discretionary-ligatures | no-discretionary-ligatures ]
<historical-lig-values> = [ historical-ligatures | no-historical-ligatures ]
<contextual-alt-values> = [ contextual | no-contextual ]
https://developer.mozilla.org/en/docs/Web/CSS/font-variant-ligatures
https://www.w3.org/TR/css-fonts-3/#font-variant-ligatures-prop
*/
export type FontVariantLigatures = 'normal' | 'none';
export interface FontProps {
fontStyle?: FontStyle;
fontVariant?: FontVariant;
fontWeight?: FontWeight;
fontStretch?: FontStretch;
fontSize?: fontSize;
fontFamily?: FontFamily;
textAnchor?: TextAnchor;
textDecoration?: TextDecoration;
letterSpacing?: LetterSpacing;
wordSpacing?: WordSpacing;
kerning?: Kerning;
fontVariantLigatures?: FontVariantLigatures;
font?: Font;
}
/*
Name Value Initial value Animatable
lengthAdjust spacing | spacingAndGlyphs spacing yes
https://svgwg.org/svg2-draft/text.html#TextElementLengthAdjustAttribute
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/lengthAdjust
*/
export type LengthAdjust = 'spacing' | 'spacingAndGlyphs';
/*
Name Value Initial value Animatable
textLength <length> | <percentage> | <number> See below yes
https://svgwg.org/svg2-draft/text.html#TextElementTextLengthAttribute
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/textLength
*/
export type TextLength = NumberProp;
/*
2.2. Transverse Box Alignment: the vertical-align property
Name: vertical-align
Value: <‘baseline-shift’> || <‘alignment-baseline’>
Initial: baseline
Applies to: inline-level boxes
Inherited: no
Percentages: N/A
Media: visual
Computed value: as specified
Canonical order: per grammar
Animation type: discrete
This shorthand property specifies how an inline-level box is aligned within the line.
Values are the same as for its longhand properties, see below.
Authors should use this property (vertical-align) instead of its longhands.
https://www.w3.org/TR/css-inline-3/#transverse-alignment
https://drafts.csswg.org/css-inline/#propdef-vertical-align
*/
export type VerticalAlign = NumberProp;
/*
Name: alignment-baseline
1.1 Value: auto | baseline | before-edge | text-before-edge | middle | central |
after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | inherit
2.0 Value: baseline | text-bottom | alphabetic | ideographic | middle | central |
mathematical | text-top | bottom | center | top
Initial: baseline
Applies to: inline-level boxes, flex items, grid items, table cells
Inherited: no
Percentages: N/A
Media: visual
Computed value: as specified
Canonical order: per grammar
Animation type: discrete
https://drafts.csswg.org/css-inline/#propdef-alignment-baseline
https://www.w3.org/TR/SVG11/text.html#AlignmentBaselineProperty
https://svgwg.org/svg2-draft/text.html#AlignmentBaselineProperty
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/alignment-baseline
*/
export type AlignmentBaseline =
| 'baseline'
| 'text-bottom'
| 'alphabetic'
| 'ideographic'
| 'middle'
| 'central'
| 'mathematical'
| 'text-top'
| 'bottom'
| 'center'
| 'top'
| 'text-before-edge'
| 'text-after-edge'
| 'before-edge'
| 'after-edge'
| 'hanging';
/*
2.2.2. Alignment Shift: baseline-shift longhand
Name: baseline-shift
Value: <length> | <percentage> | sub | super
Initial: 0
Applies to: inline-level boxes
Inherited: no
Percentages: refer to the used value of line-height
Media: visual
Computed value: absolute length, percentage, or keyword specified
Animation type: discrete
This property specifies by how much the box is shifted up from its alignment point.
It does not apply when alignment-baseline is top or bottom.
https://www.w3.org/TR/css-inline-3/#propdef-baseline-shift
*/
export type BaselineShift =
| 'sub'
| 'super'
| 'baseline'
| [NumberProp]
| NumberProp;
/*
6.12. Low-level font feature settings control: the font-feature-settings property
Name: font-feature-settings
Value: normal | <feature-tag-value> #
Initial: normal
Applies to: all elements
Inherited: yes
Percentages: N/A
Media: visual
Computed value: as specified
Animatable: no
This property provides low-level control over OpenType font features.
It is intended as a way of providing access to font features
that are not widely used but are needed for a particular use case.
Authors should generally use ‘font-variant’ and its related subproperties
whenever possible and only use this property for special cases where its use
is the only way of accessing a particular infrequently used font feature.
enable small caps and use second swash alternate
font-feature-settings: "smcp", "swsh" 2;
A value of ‘normal’ means that no change in glyph selection or positioning
occurs due to this property.
Feature tag values have the following syntax:
<feature-tag-value> = <string> [ <integer> | on | off ]?
The <string> is a case-sensitive OpenType feature tag. As specified in the
OpenType specification, feature tags contain four ASCII characters.
Tag strings longer or shorter than four characters,
or containing characters outside the U+20–7E codepoint range are invalid.
Feature tags need only match a feature tag defined in the font,
so they are not limited to explicitly registered OpenType features.
Fonts defining custom feature tags should follow the tag name rules
defined in the OpenType specification [OPENTYPE-FEATURES].
Feature tags not present in the font are ignored;
a user agent must not attempt to synthesize fallback behavior based on these feature tags.
The one exception is that user agents may synthetically support the kern feature with fonts
that contain kerning data in the form of a ‘kern’ table but lack kern feature
support in the ‘GPOS’ table.
In general, authors should use the ‘font-kerning’ property to explicitly
enable or disable kerning
since this property always affects fonts with either type of kerning data.
If present, a value indicates an index used for glyph selection.
An <integer> value must be 0 or greater.
A value of 0 indicates that the feature is disabled.
For boolean features, a value of 1 enables the feature.
For non-boolean features, a value of 1 or greater enables the
feature and indicates the feature selection index.
A value of ‘on’ is synonymous with 1 and ‘off’ is synonymous with 0.
If the value is omitted, a value of 1 is assumed.
font-feature-settings: "dlig" 1; /* dlig=1 enable discretionary ligatures * /
font-feature-settings: "smcp" on; /* smcp=1 enable small caps * /
font-feature-settings: 'c2sc'; /* c2sc=1 enable caps to small caps * /
font-feature-settings: "liga" off; /* liga=0 no common ligatures * /
font-feature-settings: "tnum", 'hist'; /* tnum=1, hist=1 enable tabular numbers
and historical forms * /
font-feature-settings: "tnum" "hist"; /* invalid, need a comma-delimited list * /
font-feature-settings: "silly" off; /* invalid, tag too long * /
font-feature-settings: "PKRN"; /* PKRN=1 enable custom feature * /
font-feature-settings: dlig; /* invalid, tag must be a string * /
When values greater than the range supported by the font are specified,
the behavior is explicitly undefined.
For boolean features, in general these will enable the feature.
For non-boolean features, out of range values will in general be equivalent to a 0 value.
However, in both cases the exact behavior will depend upon the way the font is designed
(specifically, which type of lookup is used to define the feature).
Although specifically defined for OpenType feature tags,
feature tags for other modern font formats that support font features
may be added in the future.
Where possible, features defined for other font formats
should attempt to follow the pattern of registered OpenType tags.
The Japanese text below will be rendered with half-width kana characters:
body { font-feature-settings: "hwid"; /* Half-width OpenType feature * / }
<p>毎日カレー食べてるのに、飽きない</p>
https://drafts.csswg.org/css-fonts-3/#propdef-font-feature-settings
https://developer.mozilla.org/en/docs/Web/CSS/font-feature-settings
*/
export type FontFeatureSettings = string;
export interface TextSpecificProps extends PathProps, FontProps {
alignmentBaseline?: AlignmentBaseline;
baselineShift?: BaselineShift;
verticalAlign?: VerticalAlign;
lengthAdjust?: LengthAdjust;
textLength?: TextLength;
fontData?: object;
fontFeatureSettings?: FontFeatureSettings;
}
// https://svgwg.org/svg2-draft/text.html#TSpanAttributes
export interface TextProps extends TextSpecificProps {
dx?: NumberArrayProp;
dy?: NumberArrayProp;
}
/*
Name
side
Value
left | right
initial value
left
Animatable
yes
https://svgwg.org/svg2-draft/text.html#TextPathElementSideAttribute
*/
export type Side = 'left' | 'right';
/*
Name
startOffset
Value
<length> | <percentage> | <number>
initial value
0
Animatable
yes
https://svgwg.org/svg2-draft/text.html#TextPathElementStartOffsetAttribute
https://developer.mozilla.org/en/docs/Web/SVG/Element/textPath
*/
export type StartOffset = NumberProp;
/*
Name
method
Value
align | stretch
initial value
align
Animatable
yes
https://svgwg.org/svg2-draft/text.html#TextPathElementMethodAttribute
https://developer.mozilla.org/en/docs/Web/SVG/Element/textPath
*/
export type Method = 'align' | 'stretch';
/*
Name
spacing
Value
auto | exact
initial value
exact
Animatable
yes
https://svgwg.org/svg2-draft/text.html#TextPathElementSpacingAttribute
https://developer.mozilla.org/en/docs/Web/SVG/Element/textPath
*/
export type Spacing = 'auto' | 'exact';
/*
Name
mid-line
Value
sharp | smooth
initial value
smooth
Animatable
yes
*/
export type MidLine = 'sharp' | 'smooth';
// https://svgwg.org/svg2-draft/text.html#TextPathAttributes
// https://developer.mozilla.org/en/docs/Web/SVG/Element/textPath
export interface TextPathProps extends TextSpecificProps {
href: string;
startOffset?: StartOffset;
method?: Method;
spacing?: Spacing;
side?: Side;
midLine?: MidLine;
} | the_stack |
import type {TemplateResult} from './lit-html.js';
import {noChange, RenderOptions, _$LH} from './lit-html.js';
import {AttributePartInfo, PartType} from './directive.js';
import {
isPrimitive,
isSingleExpression,
isTemplateResult,
} from './directive-helpers.js';
const {
_TemplateInstance: TemplateInstance,
_isIterable: isIterable,
_resolveDirective: resolveDirective,
_ChildPart: ChildPart,
_ElementPart: ElementPart,
} = _$LH;
type ChildPart = InstanceType<typeof ChildPart>;
type TemplateInstance = InstanceType<typeof TemplateInstance>;
/**
* Information needed to rehydrate a single TemplateResult.
*/
type ChildPartState =
| {
type: 'leaf';
/** The ChildPart that the result is rendered to */
part: ChildPart;
}
| {
type: 'iterable';
/** The ChildPart that the result is rendered to */
part: ChildPart;
value: Iterable<unknown>;
iterator: Iterator<unknown>;
done: boolean;
}
| {
type: 'template-instance';
/** The ChildPart that the result is rendered to */
part: ChildPart;
result: TemplateResult;
/** The TemplateInstance created from the TemplateResult */
instance: TemplateInstance;
/**
* The index of the next Template part to be hydrated. This is mutable and
* updated as the tree walk discovers new part markers at the right level in
* the template instance tree. Note there is only one Template part per
* attribute with (one or more) bindings.
*/
templatePartIndex: number;
/**
* The index of the next TemplateInstance part to be hydrated. This is used
* to retrieve the value from the TemplateResult and initialize the
* TemplateInstance parts' values for dirty-checking on first render.
*/
instancePartIndex: number;
};
/**
* hydrate() operates on a container with server-side rendered content and
* restores the client side data structures needed for lit-html updates such as
* TemplateInstances and Parts. After calling `hydrate`, lit-html will behave as
* if it initially rendered the DOM, and any subsequent updates will update
* efficiently, the same as if lit-html had rendered the DOM on the client.
*
* hydrate() must be called on DOM that adheres the to lit-ssr structure for
* parts. ChildParts must be represented with both a start and end comment
* marker, and ChildParts that contain a TemplateInstance must have the template
* digest written into the comment data.
*
* Since render() encloses its output in a ChildPart, there must always be a root
* ChildPart.
*
* Example (using for # ... for annotations in HTML)
*
* Given this input:
*
* html`<div class=${x}>${y}</div>`
*
* The SSR DOM is:
*
* <!--lit-part AEmR7W+R0Ak=--> # Start marker for the root ChildPart created
* # by render(). Includes the digest of the
* # template
* <div class="TEST_X">
* <!--lit-node 0--> # Indicates there are attribute bindings here
* # The number is the depth-first index of the parent
* # node in the template.
* <!--lit-part--> # Start marker for the ${x} expression
* TEST_Y
* <!--/lit-part--> # End marker for the ${x} expression
* </div>
*
* <!--/lit-part--> # End marker for the root ChildPart
*
* @param rootValue
* @param container
* @param userOptions
*/
export const hydrate = (
rootValue: unknown,
container: Element | DocumentFragment,
options: Partial<RenderOptions> = {}
) => {
// TODO(kschaaf): Do we need a helper for _$litPart$ ("part for node")?
// This property needs to remain unminified.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((container as any)['_$litPart$'] !== undefined) {
throw new Error('container already contains a live render');
}
// Since render() creates a ChildPart to render into, we'll always have
// exactly one root part. We need to hold a reference to it so we can set
// it in the parts cache.
let rootPart: ChildPart | undefined = undefined;
// When we are in-between ChildPart markers, this is the current ChildPart.
// It's needed to be able to set the ChildPart's endNode when we see a
// close marker
let currentChildPart: ChildPart | undefined = undefined;
// Used to remember parent template state as we recurse into nested
// templates
const stack: Array<ChildPartState> = [];
const walker = document.createTreeWalker(
container,
NodeFilter.SHOW_COMMENT,
null,
false
);
let marker: Comment | null;
// Walk the DOM looking for part marker comments
while ((marker = walker.nextNode() as Comment | null) !== null) {
const markerText = marker.data;
if (markerText.startsWith('lit-part')) {
if (stack.length === 0 && rootPart !== undefined) {
throw new Error('there must be only one root part per container');
}
// Create a new ChildPart and push it onto the stack
currentChildPart = openChildPart(rootValue, marker, stack, options);
rootPart ??= currentChildPart;
} else if (markerText.startsWith('lit-node')) {
// Create and hydrate attribute parts into the current ChildPart on the
// stack
createAttributeParts(marker, stack, options);
// Remove `defer-hydration` attribute, if any
const parent = marker.parentElement!;
if (parent.hasAttribute('defer-hydration')) {
parent.removeAttribute('defer-hydration');
}
} else if (markerText.startsWith('/lit-part')) {
// Close the current ChildPart, and pop the previous one off the stack
if (stack.length === 1 && currentChildPart !== rootPart) {
throw new Error('internal error');
}
currentChildPart = closeChildPart(marker, currentChildPart, stack);
}
}
console.assert(
rootPart !== undefined,
'there should be exactly one root part in a render container'
);
// This property needs to remain unminified.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(container as any)['_$litPart$'] = rootPart;
};
const openChildPart = (
rootValue: unknown,
marker: Comment,
stack: Array<ChildPartState>,
options: RenderOptions
) => {
let value: unknown;
// We know the startNode now. We'll know the endNode when we get to
// the matching marker and set it in closeChildPart()
// TODO(kschaaf): Current constructor takes both nodes
let part;
if (stack.length === 0) {
part = new ChildPart(marker, null, undefined, options);
value = rootValue;
} else {
const state = stack[stack.length - 1];
if (state.type === 'template-instance') {
part = new ChildPart(marker, null, state.instance, options);
state.instance._parts.push(part);
value = state.result.values[state.instancePartIndex++];
state.templatePartIndex++;
} else if (state.type === 'iterable') {
part = new ChildPart(marker, null, state.part, options);
const result = state.iterator.next();
if (result.done) {
value = undefined;
state.done = true;
throw new Error('Unhandled shorter than expected iterable');
} else {
value = result.value;
}
(state.part._$committedValue as Array<ChildPart>).push(part);
} else {
// state.type === 'leaf'
// TODO(kschaaf): This is unexpected, and likely a result of a primitive
// been rendered on the client when a TemplateResult was rendered on the
// server; this part will be hydrated but not used. We can detect it, but
// we need to decide what to do in this case. Note that this part won't be
// retained by any parent TemplateInstance, since a primitive had been
// rendered in its place.
// https://github.com/lit/lit/issues/1434
// throw new Error('Hydration value mismatch: Found a TemplateInstance' +
// 'where a leaf value was expected');
part = new ChildPart(marker, null, state.part, options);
}
}
// Initialize the ChildPart state depending on the type of value and push
// it onto the stack. This logic closely follows the ChildPart commit()
// cascade order:
// 1. directive
// 2. noChange
// 3. primitive (note strings must be handled before iterables, since they
// are iterable)
// 4. TemplateResult
// 5. Node (not yet implemented, but fallback handling is fine)
// 6. Iterable
// 7. nothing (handled in fallback)
// 8. Fallback for everything else
value = resolveDirective(part, value);
if (value === noChange) {
stack.push({part, type: 'leaf'});
} else if (isPrimitive(value)) {
stack.push({part, type: 'leaf'});
part._$committedValue = value;
// TODO(kschaaf): We can detect when a primitive is being hydrated on the
// client where a TemplateResult was rendered on the server, but we need to
// decide on a strategy for what to do next.
// https://github.com/lit/lit/issues/1434
// if (marker.data !== 'lit-part') {
// throw new Error('Hydration value mismatch: Primitive found where TemplateResult expected');
// }
} else if (isTemplateResult(value)) {
// Check for a template result digest
const markerWithDigest = `lit-part ${digestForTemplateResult(value)}`;
if (marker.data === markerWithDigest) {
const template = ChildPart.prototype._$getTemplate(value);
const instance = new TemplateInstance(template, part);
stack.push({
type: 'template-instance',
instance,
part,
templatePartIndex: 0,
instancePartIndex: 0,
result: value,
});
// For TemplateResult values, we set the part value to the
// generated TemplateInstance
part._$committedValue = instance;
} else {
// TODO: if this isn't the server-rendered template, do we
// need to stop hydrating this subtree? Clear it? Add tests.
throw new Error(
'Hydration value mismatch: Unexpected TemplateResult rendered to part'
);
}
} else if (isIterable(value)) {
// currentChildPart.value will contain an array of ChildParts
stack.push({
part: part,
type: 'iterable',
value,
iterator: value[Symbol.iterator](),
done: false,
});
part._$committedValue = [];
} else {
// Fallback for everything else (nothing, Objects, Functions,
// etc.): we just initialize the part's value
// Note that `Node` value types are not currently supported during
// SSR, so that part of the cascade is missing.
stack.push({part: part, type: 'leaf'});
part._$committedValue = value == null ? '' : value;
}
return part;
};
const closeChildPart = (
marker: Comment,
part: ChildPart | undefined,
stack: Array<ChildPartState>
): ChildPart | undefined => {
if (part === undefined) {
throw new Error('unbalanced part marker');
}
part._$endNode = marker;
const currentState = stack.pop()!;
if (currentState.type === 'iterable') {
if (!currentState.iterator.next().done) {
throw new Error('unexpected longer than expected iterable');
}
}
if (stack.length > 0) {
const state = stack[stack.length - 1];
return state.part;
} else {
return undefined;
}
};
const createAttributeParts = (
comment: Comment,
stack: Array<ChildPartState>,
options: RenderOptions
) => {
// Get the nodeIndex from DOM. We're only using this for an integrity
// check right now, we might not need it.
const match = /lit-node (\d+)/.exec(comment.data)!;
const nodeIndex = parseInt(match[1]);
// For void elements, the node the comment was referring to will be
// the previousSibling; for non-void elements, the comment is guaranteed
// to be the first child of the element (i.e. it won't have a previousSibling
// meaning it should use the parentElement)
const node = comment.previousSibling ?? comment.parentElement;
const state = stack[stack.length - 1];
if (state.type === 'template-instance') {
const instance = state.instance;
// eslint-disable-next-line no-constant-condition
while (true) {
// If the next template part is in attribute-position on the current node,
// create the instance part for it and prime its state
const templatePart = instance._$template.parts[state.templatePartIndex];
if (
templatePart === undefined ||
(templatePart.type !== PartType.ATTRIBUTE &&
templatePart.type !== PartType.ELEMENT) ||
templatePart.index !== nodeIndex
) {
break;
}
if (templatePart.type === PartType.ATTRIBUTE) {
// The instance part is created based on the constructor saved in the
// template part
const instancePart = new templatePart.ctor(
node as HTMLElement,
templatePart.name,
templatePart.strings,
state.instance,
options
);
const value = isSingleExpression(
instancePart as unknown as AttributePartInfo
)
? state.result.values[state.instancePartIndex]
: state.result.values;
// Setting the attribute value primes committed value with the resolved
// directive value; we only then commit that value for event/property
// parts since those were not serialized, and pass `noCommit` for the
// others to avoid perf impact of touching the DOM unnecessarily
const noCommit = !(
instancePart.type === PartType.EVENT ||
instancePart.type === PartType.PROPERTY
);
instancePart._$setValue(
value,
instancePart,
state.instancePartIndex,
noCommit
);
state.instancePartIndex += templatePart.strings.length - 1;
instance._parts.push(instancePart);
} else {
// templatePart.type === PartType.ELEMENT
const instancePart = new ElementPart(
node as HTMLElement,
state.instance,
options
);
resolveDirective(
instancePart,
state.result.values[state.instancePartIndex++]
);
instance._parts.push(instancePart);
}
state.templatePartIndex++;
}
} else {
throw new Error('internal error');
}
};
// Number of 32 bit elements to use to create template digests
const digestSize = 2;
// We need to specify a digest to use across rendering environments. This is a
// simple digest build from a DJB2-ish hash modified from:
// https://github.com/darkskyapp/string-hash/blob/master/index.js
// It has been changed to an array of hashes to add additional bits.
// Goals:
// - Extremely low collision rate. We may not be able to detect collisions.
// - Extremely fast.
// - Extremely small code size.
// - Safe to include in HTML comment text or attribute value.
// - Easily specifiable and implementable in multiple languages.
// We don't care about cryptographic suitability.
export const digestForTemplateResult = (templateResult: TemplateResult) => {
const hashes = new Uint32Array(digestSize).fill(5381);
for (const s of templateResult.strings) {
for (let i = 0; i < s.length; i++) {
hashes[i % digestSize] = (hashes[i % digestSize] * 33) ^ s.charCodeAt(i);
}
}
return btoa(String.fromCharCode(...new Uint8Array(hashes.buffer)));
}; | the_stack |
import Events, { EventName, preloadEvent } from "../../common/util/Events";
import Res from "../../common/util/Res";
import { ResUrl } from "../../constant/ResUrl";
import State from "../data/State";
import StateMachine from "../data/StateMachine";
import Transition from "../data/Transition";
import Line from "./Line";
import NavBar from "./NavBar";
import UnitBase from "./UnitBase";
import UnitState from "./UnitState";
import UnitStateMachine from "./UnitStateMachine";
const { ccclass, property } = cc._decorator;
/** 状态机视图界面边长 */
const LEN = 9000;
@ccclass
export default class MachineLayer extends cc.Component {
@property(cc.Node) Grid: cc.Node = null;
@property(cc.Node) UnitContent: cc.Node = null;
@property(cc.Node) LineContent: cc.Node = null;
@property(NavBar) NavBar: NavBar = null;
/** 默认状态,整个状态机运行的入口 */
private _defaultState: State = null;
public get defaultState() { return this._defaultState; }
public set defaultState(v: State) { this._defaultState = v; }
/** 主状态机 */
private _mainStateMachine: StateMachine = null;
public get mainStateMachine() { return this._mainStateMachine; }
/** 当前视图显示的状态机 */
private _curStateMachine: StateMachine = null;
public get curStateMachine() { return this._curStateMachine; }
/** AnyState节点 */
private _anyState: UnitState = null;
public get anyState() { return this._anyState; }
/** 父状态机节点 */
private _upUnit: UnitStateMachine = null;
protected onLoad() {
this.node.setContentSize(LEN, LEN);
this.Grid.setContentSize(LEN, LEN);
this._mainStateMachine = new StateMachine(null);
this._curStateMachine = this._mainStateMachine;
this._anyState = this.createState(cc.v2(-300, 300), true);
this._curStateMachine.setAnyStatePos(this._anyState.node.position);
this.NavBar.refreshBar([this._mainStateMachine]);
Events.targetOn(this);
}
protected onDestroy() {
this.clear();
Events.targetOff(this);
}
/**
* 更新面包屑导航栏的显示
*/
private refreshNavBar(curStateMachine: StateMachine) {
// 更新面包屑导航栏的显示
let arr: StateMachine[] = [curStateMachine];
while (curStateMachine.upStateMachine) {
arr.unshift(curStateMachine.upStateMachine);
curStateMachine = curStateMachine.upStateMachine;
}
this.NavBar.refreshBar(arr);
}
/**
* 清空状态机数据
*/
public clear() {
this._mainStateMachine.destroy();
}
/**
* 改变当前视图显示的状态机,不传参则刷新当前视图
*/
public setCurStateMachine(stateMachine: StateMachine = null) {
if (this._curStateMachine === stateMachine) {
return;
}
if (stateMachine === null) {
stateMachine = this._curStateMachine;
}
this._curStateMachine = stateMachine;
this.refreshNavBar(stateMachine);
// 处理父状态机节点和AnyState
if (!stateMachine.upStateMachine) {
if (this._upUnit) {
this._upUnit.node.removeFromParent();
this._upUnit.node.destroy();
this._upUnit = null;
}
} else {
if (!this._upUnit) {
let node: cc.Node = cc.instantiate(Res.getLoaded(ResUrl.PREFAB.STATE_MACHINE_NODE));
this.UnitContent.addChild(node);
let unitStateMachine = node.getComponent(UnitStateMachine);
this._upUnit = unitStateMachine;
}
this._upUnit.initByStateMachine(stateMachine.upStateMachine, stateMachine.upStateMachinePos);
this._upUnit.isDefault = stateMachine.upStateMachine.has(this._defaultState, false);
}
this._anyState.setPos(stateMachine.anyStatePos);
this.node.position = stateMachine.layerPos;
this.node.scale = stateMachine.layerScale;
// 清理连线、状态、状态机节点
this.LineContent.destroyAllChildren();
this.LineContent.removeAllChildren();
for (let i = this.UnitContent.childrenCount - 1; i >= 0; i--) {
let node = this.UnitContent.children[i];
let unit = node.getComponent(UnitBase);
if (unit === this._anyState || unit === this._upUnit) {
continue;
}
node.removeFromParent();
node.destroy();
}
// 生成状态、状态机节点
let stateMap: Map<State, UnitState> = new Map();
let machineMap: Map<StateMachine, UnitStateMachine> = new Map();
this._upUnit && machineMap.set(stateMachine.upStateMachine, this._upUnit);
stateMachine.subStates.forEach((e) => {
let node: cc.Node = cc.instantiate(Res.getLoaded(ResUrl.PREFAB.STATE_NODE));
this.UnitContent.addChild(node);
let unitState = node.getComponent(UnitState);
unitState.initByState(e);
unitState.isDefault = e === this._defaultState;
stateMap.set(e, unitState);
});
stateMachine.subStateMachines.forEach((e) => {
let node: cc.Node = cc.instantiate(Res.getLoaded(ResUrl.PREFAB.STATE_MACHINE_NODE));
this.UnitContent.addChild(node);
let unitStateMachine = node.getComponent(UnitStateMachine);
unitStateMachine.initByStateMachine(e);
unitStateMachine.isDefault = e.has(this._defaultState);
if (machineMap.size >= 1) {
machineMap.forEach((v, k) => {
// 状态机节点相互之间的连线
if (k.getTransitions(e).length > 0) {
let line = this.createLine();
line.onInit(v, unitStateMachine);
}
if (e.getTransitions(k).length > 0) {
let line = this.createLine();
line.onInit(unitStateMachine, v);
}
});
}
machineMap.set(e, unitStateMachine);
});
// 生成连线节点
let stateKeys = stateMap.keys();
for (let i = 0; i < stateMap.size; i++) {
let state: State = stateKeys.next().value;
let fromUnit: UnitBase = stateMap.get(state);
let toUnitSet: Set<UnitBase> = new Set();
let transitions = state.getTransitions();
transitions.forEach((t: Transition) => {
let toUnit: UnitBase = stateMap.get(t.toState);
if (!toUnit) {
if (stateMachine.has(t.toState)) {
let machineKeys = machineMap.keys();
for (let j = 0; j < machineMap.size; j++) {
let machine: StateMachine = machineKeys.next().value;
if (machine !== stateMachine.upStateMachine && machine.has(t.toState)) {
toUnit = machineMap.get(machine);
break;
}
}
} else {
toUnit = this._upUnit;
}
if (!toUnit) {
cc.error(`[MachineLayer.setCurStateMachine] error transition: ${t}`);
return;
}
}
// fromUnit向其余状态、状态机的连线
if (!toUnitSet.has(toUnit)) {
toUnitSet.add(toUnit);
let line = this.createLine();
line.onInit(fromUnit, toUnit);
}
});
// AnyState连向fromUnit的连线
if (this._anyState.state.getTransitions(state).length > 0) {
let line = this.createLine();
line.onInit(this._anyState, fromUnit);
}
// 状态机节点连向fromUnit的连线
let machineKeys = machineMap.keys();
for (let j = 0; j < machineMap.size; j++) {
let machine: StateMachine = machineKeys.next().value;
if (machine.getTransitions(state).length > 0) {
let line = this.createLine();
line.onInit(machineMap.get(machine), fromUnit);
}
}
}
}
/**
* 新建状态机节点
*/
public createStateMachine(pos: cc.Vec2): UnitStateMachine {
let node: cc.Node = cc.instantiate(Res.getLoaded(ResUrl.PREFAB.STATE_MACHINE_NODE));
this.UnitContent.addChild(node);
let unitStateMachine = node.getComponent(UnitStateMachine);
unitStateMachine.onInit(this._curStateMachine);
unitStateMachine.setPos(pos);
return unitStateMachine;
}
/**
* 新建状态节点
*/
public createState(pos: cc.Vec2, isAnyState: boolean = false): UnitState {
let node: cc.Node = cc.instantiate(Res.getLoaded(ResUrl.PREFAB.STATE_NODE));
this.UnitContent.addChild(node);
let unitState = node.getComponent(UnitState);
unitState.onInit(this._curStateMachine, isAnyState);
unitState.setPos(pos);
// 新建状态时,如果为当前唯一一个状态则设置为默认状态
if (State.getStateNum() === 1) {
this.setDefaultState(unitState);
}
return unitState;
}
public createLine(): Line {
let node: cc.Node = cc.instantiate(Res.getLoaded(ResUrl.PREFAB.LINE));
this.LineContent.addChild(node);
return node.getComponent(Line);
}
/**
* 删除子状态机
*/
public deleteStateMachine(unitStateMachine: UnitStateMachine) {
// 先删除连线,再删除状态机(删除顺序倒过来会影响查找到的连线数据)
for (let i = this.LineContent.childrenCount - 1; i >= 0; i--) {
let line: Line = this.LineContent.children[i].getComponent(Line);
if (line.relatedState(unitStateMachine)) {
this.deleteLine(line);
}
}
this._curStateMachine.delete(unitStateMachine.stateMachine);
unitStateMachine.node.removeFromParent();
unitStateMachine.node.destroy();
// 删除默认状态时,更改另一个状态为默认状态
if (unitStateMachine.isDefault) {
this.setDefaultState();
}
}
/**
* 删除状态
*/
public deleteState(unitState: UnitState) {
// 先删除连线,再删除状态(删除顺序倒过来会影响查找到的连线数据)
for (let i = this.LineContent.childrenCount - 1; i >= 0; i--) {
let line: Line = this.LineContent.children[i].getComponent(Line);
if (line.relatedState(unitState)) {
this.deleteLine(line);
}
}
this._curStateMachine.delete(unitState.state);
unitState.node.removeFromParent();
unitState.node.destroy();
// 删除默认状态时,更改另一个状态为默认状态
if (unitState.isDefault) {
this.setDefaultState();
}
}
/**
* 删除连线
*/
public deleteLine(line: Line) {
line.getTransitions().forEach((e) => {
e.fromState.deleteTransition(e);
});
line.node.removeFromParent();
line.node.destroy();
}
/**
* 根据Layer层坐标获取点击到的unit
*/
public getUnitByPos(pos: cc.Vec2): UnitBase {
for (let i = this.UnitContent.childrenCount - 1; i >= 0; i--) {
let node = this.UnitContent.children[i];
let rect = node.getBoundingBox();
if (rect.contains(pos)) {
return node.getComponent(UnitBase);
}
}
return null;
}
/**
* 根据Layer层坐标获取点击到的line
*/
public getLineByPos(pos: cc.Vec2): Line {
for (let i = this.LineContent.childrenCount - 1; i >= 0; i--) {
let node = this.LineContent.children[i];
let line = node.getComponent(Line);
if (line.contains(pos)) {
return line;
}
}
return null;
}
/**
* 根据连线两端节点获取line
*/
public getLineByUnit(from: UnitBase, to: UnitBase): Line {
for (let i = this.LineContent.childrenCount - 1; i >= 0; i--) {
let node = this.LineContent.children[i];
let line = node.getComponent(Line);
if (line.fromUnit === from && line.toUnit === to) {
return line;
}
}
return null;
}
/**
* 判断moveUnit节点是否可移入某个状态机节点内
* @param moveUnit 跟随鼠标移动的unit
*/
public checkMoveUnit(moveUnit: UnitBase): UnitStateMachine {
if (moveUnit === this._anyState || moveUnit === this._upUnit) {
return null;
}
for (let i = this.UnitContent.childrenCount - 1; i >= 0; i--) {
let node = this.UnitContent.children[i];
let unit = node.getComponent(UnitStateMachine);
if (!unit || unit === moveUnit) {
continue;
}
let rect = node.getBoundingBox();
if (rect.contains(moveUnit.node.position)) {
return unit;
}
}
return null;
}
/**
* 尝试将moveUnit节点移入重叠的状态机内
* @param moveUnit
* @returns 是否进行移入操作
*/
public moveIntoStateMachine(moveUnit: UnitBase): boolean {
let unit: UnitStateMachine = this.checkMoveUnit(moveUnit);
if (!unit) {
return false;
}
let needRefresh: boolean = false;
if (moveUnit instanceof UnitState) {
needRefresh = unit.stateMachine.moveTargetIn(moveUnit.state);
} else if (moveUnit instanceof UnitStateMachine) {
needRefresh = unit.stateMachine.moveTargetIn(moveUnit.stateMachine);
}
if (!needRefresh) {
return false;
}
this.setCurStateMachine();
return true;
}
/**
* 设置默认状态
* @param unitState 不传参则表示随机一个设置为默认状态
*/
public setDefaultState(unitState: UnitState = null) {
if (!unitState) {
if (this._curStateMachine.subStates.size === 0) {
// 当前视图没有State
this._defaultState = State.getRandState();
if (!this._defaultState) {
return;
}
for (let i = this.UnitContent.childrenCount - 1; i >= 0; i--) {
let node = this.UnitContent.children[i];
let v = node.getComponent(UnitStateMachine);
if (v) {
v.isDefault = v.stateMachine.has(this._defaultState);
break;
}
}
} else {
for (let i = this.UnitContent.childrenCount - 1; i >= 0; i--) {
let node = this.UnitContent.children[i];
let v = node.getComponent(UnitState);
if (v && !v.isAnyState) {
v.isDefault = true;
this._defaultState = v.state;
break;
}
}
}
} else {
if (unitState.state === this._defaultState || unitState.isAnyState) {
return;
}
this.UnitContent.children.forEach((e) => {
let v = e.getComponent(UnitBase);
if (v === this._anyState) {
return;
}
if (v === unitState) {
v.isDefault = true;
this._defaultState = unitState.state;
} else {
v.isDefault = false;
}
});
}
}
/**
* 限制节点修改坐标时不超出边缘
* @param pos
*/
public setPos(pos: cc.Vec2) {
let rect = this.node.getBoundingBox();
let x = cc.misc.clampf(pos.x, -this.node.parent.width / 2 + rect.width / 2, this.node.parent.width / 2 - rect.width / 2);
let y = cc.misc.clampf(pos.y, -this.node.parent.height / 2 + rect.height / 2, this.node.parent.height / 2 - rect.height / 2);
this.node.x = x;
this.node.y = y;
this._curStateMachine.setLayerPos(x, y);
}
/**
* 缩放
* @param value true为放大, false为缩小
* @param worldPos 鼠标所在的世界坐标
*/
public changeScale(value: boolean, worldPos: cc.Vec2) {
let localPos1 = this.node.convertToNodeSpaceAR(worldPos);
this.node.scale = cc.misc.clampf(value ? this.node.scale + 0.1 : this.node.scale - 0.1, 0.3, 3);
let localPos2 = this.node.convertToNodeSpaceAR(worldPos);
let delta = localPos2.sub(localPos1).mul(this.node.scale);
this.setPos(this.node.position.add(delta));
this._curStateMachine.setLayerScale(this.node.scale);
}
@preloadEvent(EventName.ANY_STATE_MOVE)
private onEventAnyStateMove(pos: cc.Vec2) {
this._curStateMachine.setAnyStatePos(pos);
}
@preloadEvent(EventName.UP_STATE_MACHINE_MOVE)
private onEventUpStateMachineMove(pos: cc.Vec2) {
this._curStateMachine.setUpStateMachinePos(pos);
}
} | the_stack |
import { ERC20Wrapper } from '@0x/contracts-asset-proxy';
import { artifacts as erc20Artifacts, DummyERC20TokenContract, WETH9Contract } from '@0x/contracts-erc20';
import { BlockchainTestsEnvironment, constants, filterLogsToArguments, txDefaults } from '@0x/contracts-test-utils';
import { BigNumber } from '@0x/utils';
import { Web3Wrapper } from '@0x/web3-wrapper';
import { BlockParamLiteral, ContractArtifact, TransactionReceiptWithDecodedLogs } from 'ethereum-types';
import * as _ from 'lodash';
import { artifacts } from '../artifacts';
import {
IStakingEventsEpochEndedEventArgs,
IStakingEventsStakingPoolEarnedRewardsInEpochEventArgs,
StakingProxyContract,
TestCobbDouglasContract,
TestStakingContract,
TestStakingEvents,
ZrxVaultContract,
} from '../wrappers';
import { constants as stakingConstants } from '../../src/constants';
import { DecodedLogs, EndOfEpochInfo, StakingParams } from '../../src/types';
export class StakingApiWrapper {
// The address of the real Staking.sol contract
public stakingContractAddress: string;
// The StakingProxy.sol contract wrapped as a StakingContract to borrow API
public stakingContract: TestStakingContract;
// The StakingProxy.sol contract as a StakingProxyContract
public stakingProxyContract: StakingProxyContract;
public zrxVaultContract: ZrxVaultContract;
public zrxTokenContract: DummyERC20TokenContract;
public wethContract: WETH9Contract;
public cobbDouglasContract: TestCobbDouglasContract;
public utils = {
// Epoch Utils
fastForwardToNextEpochAsync: async (): Promise<void> => {
// increase timestamp of next block by how many seconds we need to
// get to the next epoch.
const epochEndTime = await this.stakingContract.getCurrentEpochEarliestEndTimeInSeconds().callAsync();
const lastBlockTime = await this._web3Wrapper.getBlockTimestampAsync('latest');
const dt = Math.max(0, epochEndTime.minus(lastBlockTime).toNumber());
await this._web3Wrapper.increaseTimeAsync(dt);
// mine next block
await this._web3Wrapper.mineBlockAsync();
},
skipToNextEpochAndFinalizeAsync: async (): Promise<DecodedLogs> => {
await this.utils.fastForwardToNextEpochAsync();
const endOfEpochInfo = await this.utils.endEpochAsync();
const allLogs = [] as DecodedLogs;
for (const poolId of endOfEpochInfo.activePoolIds) {
const receipt = await this.stakingContract.finalizePool(poolId).awaitTransactionSuccessAsync();
allLogs.splice(allLogs.length, 0, ...(receipt.logs as DecodedLogs));
}
return allLogs;
},
endEpochAsync: async (): Promise<EndOfEpochInfo> => {
const activePoolIds = await this.utils.findActivePoolIdsAsync();
const receipt = await this.stakingContract.endEpoch().awaitTransactionSuccessAsync();
const [epochEndedEvent] = filterLogsToArguments<IStakingEventsEpochEndedEventArgs>(
receipt.logs,
TestStakingEvents.EpochEnded,
);
return {
closingEpoch: epochEndedEvent.epoch,
activePoolIds,
rewardsAvailable: epochEndedEvent.rewardsAvailable,
totalFeesCollected: epochEndedEvent.totalFeesCollected,
totalWeightedStake: epochEndedEvent.totalWeightedStake,
};
},
findActivePoolIdsAsync: async (epoch?: number): Promise<string[]> => {
const _epoch = epoch !== undefined ? epoch : await this.stakingContract.currentEpoch().callAsync();
const events = filterLogsToArguments<IStakingEventsStakingPoolEarnedRewardsInEpochEventArgs>(
await this.stakingContract.getLogsAsync(
TestStakingEvents.StakingPoolEarnedRewardsInEpoch,
{ fromBlock: BlockParamLiteral.Earliest, toBlock: BlockParamLiteral.Latest },
{ epoch: new BigNumber(_epoch) },
),
TestStakingEvents.StakingPoolEarnedRewardsInEpoch,
);
return events.map(e => e.poolId);
},
// Other Utils
createStakingPoolAsync: async (
operatorAddress: string,
operatorShare: number,
addOperatorAsMaker: boolean,
): Promise<string> => {
const txReceipt = await this.stakingContract
.createStakingPool(operatorShare, addOperatorAsMaker)
.awaitTransactionSuccessAsync({ from: operatorAddress });
const createStakingPoolLog = txReceipt.logs[0];
const poolId = (createStakingPoolLog as any).args.poolId;
return poolId;
},
getZrxTokenBalanceOfZrxVaultAsync: async (): Promise<BigNumber> => {
return this.zrxTokenContract.balanceOf(this.zrxVaultContract.address).callAsync();
},
setParamsAsync: async (params: Partial<StakingParams>): Promise<TransactionReceiptWithDecodedLogs> => {
const _params = {
...stakingConstants.DEFAULT_PARAMS,
...params,
};
return this.stakingContract
.setParams(
new BigNumber(_params.epochDurationInSeconds),
new BigNumber(_params.rewardDelegatedStakeWeight),
new BigNumber(_params.minimumPoolStake),
new BigNumber(_params.cobbDouglasAlphaNumerator),
new BigNumber(_params.cobbDouglasAlphaDenominator),
)
.awaitTransactionSuccessAsync();
},
getAvailableRewardsBalanceAsync: async (): Promise<BigNumber> => {
const [ethBalance, wethBalance, reservedRewards] = await Promise.all([
this._web3Wrapper.getBalanceInWeiAsync(this.stakingProxyContract.address),
this.wethContract.balanceOf(this.stakingProxyContract.address).callAsync(),
this.stakingContract.wethReservedForPoolRewards().callAsync(),
]);
return BigNumber.sum(ethBalance, wethBalance).minus(reservedRewards);
},
getParamsAsync: async (): Promise<StakingParams> => {
return (_.zipObject(
[
'epochDurationInSeconds',
'rewardDelegatedStakeWeight',
'minimumPoolStake',
'cobbDouglasAlphaNumerator',
'cobbDouglasAlphaDenominator',
'wethProxyAddress',
'zrxVaultAddress',
],
await this.stakingContract.getParams().callAsync(),
) as any) as StakingParams;
},
cobbDouglasAsync: async (
totalRewards: BigNumber,
ownerFees: BigNumber,
totalFees: BigNumber,
ownerStake: BigNumber,
totalStake: BigNumber,
): Promise<BigNumber> => {
const { cobbDouglasAlphaNumerator, cobbDouglasAlphaDenominator } = await this.utils.getParamsAsync();
return this.cobbDouglasContract
.cobbDouglas(
totalRewards,
ownerFees,
totalFees,
ownerStake,
totalStake,
new BigNumber(cobbDouglasAlphaNumerator),
new BigNumber(cobbDouglasAlphaDenominator),
)
.callAsync();
},
};
private readonly _web3Wrapper: Web3Wrapper;
constructor(
env: BlockchainTestsEnvironment,
ownerAddress: string,
stakingProxyContract: StakingProxyContract,
stakingContract: TestStakingContract,
zrxVaultContract: ZrxVaultContract,
zrxTokenContract: DummyERC20TokenContract,
wethContract: WETH9Contract,
cobbDouglasContract: TestCobbDouglasContract,
) {
this._web3Wrapper = env.web3Wrapper;
this.zrxVaultContract = zrxVaultContract;
this.zrxTokenContract = zrxTokenContract;
this.wethContract = wethContract;
this.cobbDouglasContract = cobbDouglasContract;
this.stakingContractAddress = stakingContract.address;
this.stakingProxyContract = stakingProxyContract;
// disguise the staking proxy as a StakingContract
const logDecoderDependencies = _.mapValues({ ...artifacts, ...erc20Artifacts }, v => v.compilerOutput.abi);
this.stakingContract = new TestStakingContract(
stakingProxyContract.address,
env.provider,
{
...env.txDefaults,
from: ownerAddress,
to: stakingProxyContract.address,
gas: 3e6,
gasPrice: 0,
},
logDecoderDependencies,
);
}
}
/**
* Deploys and configures all staking contracts and returns a StakingApiWrapper instance, which
* holds the deployed contracts and serves as the entry point for their public functions.
*/
export async function deployAndConfigureContractsAsync(
env: BlockchainTestsEnvironment,
ownerAddress: string,
erc20Wrapper: ERC20Wrapper,
customStakingArtifact?: ContractArtifact,
): Promise<StakingApiWrapper> {
// deploy erc20 proxy
const erc20ProxyContract = await erc20Wrapper.deployProxyAsync();
// deploy zrx token
const [zrxTokenContract] = await erc20Wrapper.deployDummyTokensAsync(1, constants.DUMMY_TOKEN_DECIMALS);
await erc20Wrapper.setBalancesAndAllowancesAsync();
// deploy WETH
const wethContract = await WETH9Contract.deployFrom0xArtifactAsync(
erc20Artifacts.WETH9,
env.provider,
txDefaults,
artifacts,
);
// deploy zrx vault
const zrxVaultContract = await ZrxVaultContract.deployFrom0xArtifactAsync(
artifacts.ZrxVault,
env.provider,
env.txDefaults,
artifacts,
erc20ProxyContract.address,
zrxTokenContract.address,
);
await zrxVaultContract.addAuthorizedAddress(ownerAddress).awaitTransactionSuccessAsync();
// deploy staking contract
const stakingContract = await TestStakingContract.deployFrom0xArtifactAsync(
customStakingArtifact !== undefined ? customStakingArtifact : artifacts.TestStaking,
env.provider,
env.txDefaults,
artifacts,
wethContract.address,
zrxVaultContract.address,
);
// deploy staking proxy
const stakingProxyContract = await StakingProxyContract.deployFrom0xArtifactAsync(
artifacts.StakingProxy,
env.provider,
env.txDefaults,
artifacts,
stakingContract.address,
);
await stakingProxyContract.addAuthorizedAddress(ownerAddress).awaitTransactionSuccessAsync();
// deploy cobb douglas contract
const cobbDouglasContract = await TestCobbDouglasContract.deployFrom0xArtifactAsync(
artifacts.TestCobbDouglas,
env.provider,
txDefaults,
artifacts,
);
// configure erc20 proxy to accept calls from zrx vault
await erc20ProxyContract.addAuthorizedAddress(zrxVaultContract.address).awaitTransactionSuccessAsync();
// set staking proxy contract in zrx vault
await zrxVaultContract.setStakingProxy(stakingProxyContract.address).awaitTransactionSuccessAsync();
return new StakingApiWrapper(
env,
ownerAddress,
stakingProxyContract,
stakingContract,
zrxVaultContract,
zrxTokenContract,
wethContract,
cobbDouglasContract,
);
} | the_stack |
import * as ASTv1 from '../v1/api';
import { escapeAttrValue, escapeText, sortByLoc } from './util';
export const voidMap: {
[tagName: string]: boolean;
} = Object.create(null);
let voidTagNames =
'area base br col command embed hr img input keygen link meta param source track wbr';
voidTagNames.split(' ').forEach((tagName) => {
voidMap[tagName] = true;
});
const NON_WHITESPACE = /\S/;
export interface PrinterOptions {
entityEncoding: 'transformed' | 'raw';
/**
* Used to override the mechanism of printing a given AST.Node.
*
* This will generally only be useful to source -> source codemods
* where you would like to specialize/override the way a given node is
* printed (e.g. you would like to preserve as much of the original
* formatting as possible).
*
* When the provided override returns undefined, the default built in printing
* will be done for the AST.Node.
*
* @param ast the ast node to be printed
* @param options the options specified during the print() invocation
*/
override?(ast: ASTv1.Node, options: PrinterOptions): void | string;
}
export default class Printer {
private buffer = '';
private options: PrinterOptions;
constructor(options: PrinterOptions) {
this.options = options;
}
/*
This is used by _all_ methods on this Printer class that add to `this.buffer`,
it allows consumers of the printer to use alternate string representations for
a given node.
The primary use case for this are things like source -> source codemod utilities.
For example, ember-template-recast attempts to always preserve the original string
formatting in each AST node if no modifications are made to it.
*/
handledByOverride(node: ASTv1.Node, ensureLeadingWhitespace = false): boolean {
if (this.options.override !== undefined) {
let result = this.options.override(node, this.options);
if (typeof result === 'string') {
if (ensureLeadingWhitespace && result !== '' && NON_WHITESPACE.test(result[0])) {
result = ` ${result}`;
}
this.buffer += result;
return true;
}
}
return false;
}
Node(node: ASTv1.Node): void {
switch (node.type) {
case 'MustacheStatement':
case 'BlockStatement':
case 'PartialStatement':
case 'MustacheCommentStatement':
case 'CommentStatement':
case 'TextNode':
case 'ElementNode':
case 'AttrNode':
case 'Block':
case 'Template':
return this.TopLevelStatement(node);
case 'StringLiteral':
case 'BooleanLiteral':
case 'NumberLiteral':
case 'UndefinedLiteral':
case 'NullLiteral':
case 'PathExpression':
case 'SubExpression':
return this.Expression(node);
case 'Program':
return this.Block(node);
case 'ConcatStatement':
// should have an AttrNode parent
return this.ConcatStatement(node);
case 'Hash':
return this.Hash(node);
case 'HashPair':
return this.HashPair(node);
case 'ElementModifierStatement':
return this.ElementModifierStatement(node);
}
}
Expression(expression: ASTv1.Expression): void {
switch (expression.type) {
case 'StringLiteral':
case 'BooleanLiteral':
case 'NumberLiteral':
case 'UndefinedLiteral':
case 'NullLiteral':
return this.Literal(expression);
case 'PathExpression':
return this.PathExpression(expression);
case 'SubExpression':
return this.SubExpression(expression);
}
}
Literal(literal: ASTv1.Literal): void {
switch (literal.type) {
case 'StringLiteral':
return this.StringLiteral(literal);
case 'BooleanLiteral':
return this.BooleanLiteral(literal);
case 'NumberLiteral':
return this.NumberLiteral(literal);
case 'UndefinedLiteral':
return this.UndefinedLiteral(literal);
case 'NullLiteral':
return this.NullLiteral(literal);
}
}
TopLevelStatement(statement: ASTv1.TopLevelStatement | ASTv1.Template | ASTv1.AttrNode): void {
switch (statement.type) {
case 'MustacheStatement':
return this.MustacheStatement(statement);
case 'BlockStatement':
return this.BlockStatement(statement);
case 'PartialStatement':
return this.PartialStatement(statement);
case 'MustacheCommentStatement':
return this.MustacheCommentStatement(statement);
case 'CommentStatement':
return this.CommentStatement(statement);
case 'TextNode':
return this.TextNode(statement);
case 'ElementNode':
return this.ElementNode(statement);
case 'Block':
case 'Template':
return this.Block(statement);
case 'AttrNode':
// should have element
return this.AttrNode(statement);
}
}
Block(block: ASTv1.Block | ASTv1.Program | ASTv1.Template): void {
/*
When processing a template like:
```hbs
{{#if whatever}}
whatever
{{else if somethingElse}}
something else
{{else}}
fallback
{{/if}}
```
The AST still _effectively_ looks like:
```hbs
{{#if whatever}}
whatever
{{else}}{{#if somethingElse}}
something else
{{else}}
fallback
{{/if}}{{/if}}
```
The only way we can tell if that is the case is by checking for
`block.chained`, but unfortunately when the actual statements are
processed the `block.body[0]` node (which will always be a
`BlockStatement`) has no clue that its ancestor `Block` node was
chained.
This "forwards" the `chained` setting so that we can check
it later when processing the `BlockStatement`.
*/
if (block.chained) {
let firstChild = block.body[0] as ASTv1.BlockStatement;
firstChild.chained = true;
}
if (this.handledByOverride(block)) {
return;
}
this.TopLevelStatements(block.body);
}
TopLevelStatements(statements: ASTv1.TopLevelStatement[]): void {
statements.forEach((statement) => this.TopLevelStatement(statement));
}
ElementNode(el: ASTv1.ElementNode): void {
if (this.handledByOverride(el)) {
return;
}
this.OpenElementNode(el);
this.TopLevelStatements(el.children);
this.CloseElementNode(el);
}
OpenElementNode(el: ASTv1.ElementNode): void {
this.buffer += `<${el.tag}`;
const parts = [...el.attributes, ...el.modifiers, ...el.comments].sort(sortByLoc);
for (const part of parts) {
this.buffer += ' ';
switch (part.type) {
case 'AttrNode':
this.AttrNode(part);
break;
case 'ElementModifierStatement':
this.ElementModifierStatement(part);
break;
case 'MustacheCommentStatement':
this.MustacheCommentStatement(part);
break;
}
}
if (el.blockParams.length) {
this.BlockParams(el.blockParams);
}
if (el.selfClosing) {
this.buffer += ' /';
}
this.buffer += '>';
}
CloseElementNode(el: ASTv1.ElementNode): void {
if (el.selfClosing || voidMap[el.tag.toLowerCase()]) {
return;
}
this.buffer += `</${el.tag}>`;
}
AttrNode(attr: ASTv1.AttrNode): void {
if (this.handledByOverride(attr)) {
return;
}
let { name, value } = attr;
this.buffer += name;
if (value.type !== 'TextNode' || value.chars.length > 0) {
this.buffer += '=';
this.AttrNodeValue(value);
}
}
AttrNodeValue(value: ASTv1.AttrNode['value']): void {
if (value.type === 'TextNode') {
this.buffer += '"';
this.TextNode(value, true);
this.buffer += '"';
} else {
this.Node(value);
}
}
TextNode(text: ASTv1.TextNode, isAttr?: boolean): void {
if (this.handledByOverride(text)) {
return;
}
if (this.options.entityEncoding === 'raw') {
this.buffer += text.chars;
} else if (isAttr) {
this.buffer += escapeAttrValue(text.chars);
} else {
this.buffer += escapeText(text.chars);
}
}
MustacheStatement(mustache: ASTv1.MustacheStatement): void {
if (this.handledByOverride(mustache)) {
return;
}
this.buffer += mustache.escaped ? '{{' : '{{{';
if (mustache.strip.open) {
this.buffer += '~';
}
this.Expression(mustache.path);
this.Params(mustache.params);
this.Hash(mustache.hash);
if (mustache.strip.close) {
this.buffer += '~';
}
this.buffer += mustache.escaped ? '}}' : '}}}';
}
BlockStatement(block: ASTv1.BlockStatement): void {
if (this.handledByOverride(block)) {
return;
}
if (block.chained) {
this.buffer += block.inverseStrip.open ? '{{~' : '{{';
this.buffer += 'else ';
} else {
this.buffer += block.openStrip.open ? '{{~#' : '{{#';
}
this.Expression(block.path);
this.Params(block.params);
this.Hash(block.hash);
if (block.program.blockParams.length) {
this.BlockParams(block.program.blockParams);
}
if (block.chained) {
this.buffer += block.inverseStrip.close ? '~}}' : '}}';
} else {
this.buffer += block.openStrip.close ? '~}}' : '}}';
}
this.Block(block.program);
if (block.inverse) {
if (!block.inverse.chained) {
this.buffer += block.inverseStrip.open ? '{{~' : '{{';
this.buffer += 'else';
this.buffer += block.inverseStrip.close ? '~}}' : '}}';
}
this.Block(block.inverse);
}
if (!block.chained) {
this.buffer += block.closeStrip.open ? '{{~/' : '{{/';
this.Expression(block.path);
this.buffer += block.closeStrip.close ? '~}}' : '}}';
}
}
BlockParams(blockParams: string[]): void {
this.buffer += ` as |${blockParams.join(' ')}|`;
}
PartialStatement(partial: ASTv1.PartialStatement): void {
if (this.handledByOverride(partial)) {
return;
}
this.buffer += '{{>';
this.Expression(partial.name);
this.Params(partial.params);
this.Hash(partial.hash);
this.buffer += '}}';
}
ConcatStatement(concat: ASTv1.ConcatStatement): void {
if (this.handledByOverride(concat)) {
return;
}
this.buffer += '"';
concat.parts.forEach((part) => {
if (part.type === 'TextNode') {
this.TextNode(part, true);
} else {
this.Node(part);
}
});
this.buffer += '"';
}
MustacheCommentStatement(comment: ASTv1.MustacheCommentStatement): void {
if (this.handledByOverride(comment)) {
return;
}
this.buffer += `{{!--${comment.value}--}}`;
}
ElementModifierStatement(mod: ASTv1.ElementModifierStatement): void {
if (this.handledByOverride(mod)) {
return;
}
this.buffer += '{{';
this.Expression(mod.path);
this.Params(mod.params);
this.Hash(mod.hash);
this.buffer += '}}';
}
CommentStatement(comment: ASTv1.CommentStatement): void {
if (this.handledByOverride(comment)) {
return;
}
this.buffer += `<!--${comment.value}-->`;
}
PathExpression(path: ASTv1.PathExpression): void {
if (this.handledByOverride(path)) {
return;
}
this.buffer += path.original;
}
SubExpression(sexp: ASTv1.SubExpression): void {
if (this.handledByOverride(sexp)) {
return;
}
this.buffer += '(';
this.Expression(sexp.path);
this.Params(sexp.params);
this.Hash(sexp.hash);
this.buffer += ')';
}
Params(params: ASTv1.Expression[]): void {
// TODO: implement a top level Params AST node (just like the Hash object)
// so that this can also be overridden
if (params.length) {
params.forEach((param) => {
this.buffer += ' ';
this.Expression(param);
});
}
}
Hash(hash: ASTv1.Hash): void {
if (this.handledByOverride(hash, true)) {
return;
}
hash.pairs.forEach((pair) => {
this.buffer += ' ';
this.HashPair(pair);
});
}
HashPair(pair: ASTv1.HashPair): void {
if (this.handledByOverride(pair)) {
return;
}
this.buffer += pair.key;
this.buffer += '=';
this.Node(pair.value);
}
StringLiteral(str: ASTv1.StringLiteral): void {
if (this.handledByOverride(str)) {
return;
}
this.buffer += JSON.stringify(str.value);
}
BooleanLiteral(bool: ASTv1.BooleanLiteral): void {
if (this.handledByOverride(bool)) {
return;
}
this.buffer += bool.value;
}
NumberLiteral(number: ASTv1.NumberLiteral): void {
if (this.handledByOverride(number)) {
return;
}
this.buffer += number.value;
}
UndefinedLiteral(node: ASTv1.UndefinedLiteral): void {
if (this.handledByOverride(node)) {
return;
}
this.buffer += 'undefined';
}
NullLiteral(node: ASTv1.NullLiteral): void {
if (this.handledByOverride(node)) {
return;
}
this.buffer += 'null';
}
print(node: ASTv1.Node): string {
let { options } = this;
if (options.override) {
let result = options.override(node, options);
if (result !== undefined) {
return result;
}
}
this.buffer = '';
this.Node(node);
return this.buffer;
}
} | the_stack |
import {retain, release} from '@remote-ui/rpc';
import {
ACTION_MOUNT,
ACTION_INSERT_CHILD,
ACTION_REMOVE_CHILD,
ACTION_UPDATE_PROPS,
ACTION_UPDATE_TEXT,
KIND_COMPONENT,
KIND_FRAGMENT,
} from './types';
import type {
ActionArgumentMap,
RemoteChannel,
RemoteTextSerialization,
RemoteComponentSerialization,
RemoteFragmentSerialization,
} from './types';
import {isRemoteFragment} from './utilities';
export const ROOT_ID = Symbol('RootId');
export interface RemoteReceiverAttachableText extends RemoteTextSerialization {
version: number;
}
export interface RemoteReceiverAttachableComponent
extends Omit<RemoteComponentSerialization<any>, 'children'> {
children: RemoteReceiverAttachableChild[];
version: number;
}
export interface RemoteReceiverAttachableFragment
extends Omit<RemoteFragmentSerialization, 'children'> {
children: RemoteReceiverAttachableChild[];
version: number;
}
export interface RemoteReceiverAttachableRoot {
id: typeof ROOT_ID;
children: RemoteReceiverAttachableChild[];
version: number;
}
export type RemoteReceiverAttachableChild =
| RemoteReceiverAttachableText
| RemoteReceiverAttachableComponent;
export type RemoteReceiverAttachable =
| RemoteReceiverAttachableChild
| RemoteReceiverAttachableRoot
| RemoteReceiverAttachableFragment;
interface RemoteChannelRunner {
mount(...args: ActionArgumentMap[typeof ACTION_MOUNT]): void;
insertChild(...args: ActionArgumentMap[typeof ACTION_INSERT_CHILD]): void;
removeChild(...args: ActionArgumentMap[typeof ACTION_INSERT_CHILD]): void;
updateProps(...args: ActionArgumentMap[typeof ACTION_UPDATE_PROPS]): void;
updateText(...args: ActionArgumentMap[typeof ACTION_UPDATE_TEXT]): void;
}
export function createRemoteChannel({
mount,
insertChild,
removeChild,
updateProps,
updateText,
}: RemoteChannelRunner): RemoteChannel {
const messageMap = new Map<keyof ActionArgumentMap, (...args: any[]) => any>([
[ACTION_MOUNT, mount],
[ACTION_REMOVE_CHILD, removeChild],
[ACTION_INSERT_CHILD, insertChild],
[ACTION_UPDATE_PROPS, updateProps],
[ACTION_UPDATE_TEXT, updateText],
]);
return (type, ...args) => messageMap.get(type)!(...args);
}
export interface RemoteReceiverAttachment {
readonly root: RemoteReceiverAttachableRoot;
get<T extends RemoteReceiverAttachable>(attachable: Pick<T, 'id'>): T | null;
subscribe<T extends RemoteReceiverAttachable>(
{id}: T,
subscriber: (value: T) => void,
): () => void;
}
export interface RemoteReceiver {
readonly receive: RemoteChannel;
readonly attached: RemoteReceiverAttachment;
readonly state: 'mounted' | 'unmounted';
on(event: 'mount', handler: () => void): () => void;
flush(): Promise<void>;
}
export function createRemoteReceiver(): RemoteReceiver {
const queuedUpdates = new Set<RemoteReceiverAttachable>();
const listeners = new Map<
Parameters<RemoteReceiver['on']>[0],
Set<Parameters<RemoteReceiver['on']>[1]>
>();
const attachmentSubscribers = new Map<
string | typeof ROOT_ID,
Set<(value: RemoteReceiverAttachable) => void>
>();
let timeout: Promise<void> | null = null;
let state: RemoteReceiver['state'] = 'unmounted';
const root: RemoteReceiverAttachableRoot = {
id: ROOT_ID,
children: [],
version: 0,
};
const attachedNodes = new Map<
string | typeof ROOT_ID,
RemoteReceiverAttachable
>([[ROOT_ID, root]]);
const receive = createRemoteChannel({
mount: (children) => {
const root = attachedNodes.get(ROOT_ID) as RemoteReceiverAttachableRoot;
const normalizedChildren = children.map((child) =>
normalizeNode(child, addVersion),
);
root.version += 1;
root.children = normalizedChildren;
state = 'mounted';
for (const child of normalizedChildren) {
retain(child);
attach(child);
}
// eslint-disable-next-line promise/catch-or-return
enqueueUpdate(root).then(() => {
emit('mount');
});
},
insertChild: (id, index, child) => {
const attached = attachedNodes.get(
id ?? ROOT_ID,
) as RemoteReceiverAttachableRoot;
const normalizedChild = normalizeNode(child, addVersion);
retain(normalizedChild);
attach(normalizedChild);
const {children} = attached;
if (index === children.length) {
children.push(normalizedChild);
} else {
children.splice(index, 0, normalizedChild);
}
attached.version += 1;
enqueueUpdate(attached);
},
removeChild: (id, index) => {
const attached = attachedNodes.get(
id ?? ROOT_ID,
) as RemoteReceiverAttachableRoot;
const {children} = attached;
const [removed] = children.splice(index, 1);
attached.version += 1;
detach(removed);
// eslint-disable-next-line promise/catch-or-return
enqueueUpdate(attached).then(() => {
release(removed);
});
},
updateProps: (id, newProps) => {
const component = attachedNodes.get(
id,
) as RemoteReceiverAttachableComponent;
const oldProps = {...(component.props as any)};
retain(newProps);
Object.keys(newProps).forEach((key) => {
const newProp = (newProps as any)[key];
const oldProp = (oldProps as any)[key];
if (isRemoteReceiverAttachableFragment(oldProp)) {
detach(oldProp);
}
if (isRemoteFragmentSerialization(newProp)) {
const attachableNewProp = addVersion(newProp);
attach(attachableNewProp);
}
});
Object.assign(component.props, newProps);
component.version += 1;
// eslint-disable-next-line promise/catch-or-return
enqueueUpdate(component).then(() => {
for (const key of Object.keys(newProps)) {
release((oldProps as any)[key]);
}
});
},
updateText: (id, newText) => {
const text = attachedNodes.get(id) as RemoteReceiverAttachableText;
text.text = newText;
text.version += 1;
enqueueUpdate(text);
},
});
return {
get state() {
return state;
},
receive,
attached: {
root,
get({id}) {
return (attachedNodes.get(id) as any) ?? null;
},
subscribe({id}, subscriber) {
let subscribers = attachmentSubscribers.get(id);
if (subscribers == null) {
subscribers = new Set();
attachmentSubscribers.set(id, subscribers);
}
subscribers.add(subscriber as any);
return () => {
const subscribers = attachmentSubscribers.get(id);
if (subscribers) {
subscribers.delete(subscriber as any);
if (subscribers.size === 0) {
attachmentSubscribers.delete(id);
}
}
};
},
},
flush,
on(event, listener) {
let listenersForEvent = listeners.get(event);
if (listenersForEvent == null) {
listenersForEvent = new Set();
listeners.set(event, listenersForEvent);
}
listenersForEvent.add(listener);
return () => {
const listenersForEvent = listeners.get(event);
if (listenersForEvent) {
listenersForEvent.delete(listener);
if (listenersForEvent.size === 0) {
listeners.delete(event);
}
}
};
},
};
function flush() {
return timeout ?? Promise.resolve();
}
function emit(event: 'mount') {
const listenersForEvent = listeners.get(event);
if (listenersForEvent) {
for (const listener of listenersForEvent) {
listener();
}
}
}
function enqueueUpdate(attached: RemoteReceiverAttachable) {
timeout =
timeout ??
new Promise((resolve) => {
setTimeout(() => {
const attachedToUpdate = [...queuedUpdates];
timeout = null;
queuedUpdates.clear();
for (const attached of attachedToUpdate) {
const subscribers = attachmentSubscribers.get(attached.id);
if (subscribers) {
for (const subscriber of subscribers) {
subscriber(attached);
}
}
}
resolve();
}, 0);
});
queuedUpdates.add(attached);
return timeout;
}
function attach(
child: RemoteReceiverAttachableChild | RemoteReceiverAttachableFragment,
) {
attachedNodes.set(child.id, child);
if (child.kind === KIND_COMPONENT && 'props' in child) {
const {props = {}} = child as any;
Object.keys(props).forEach((key) => {
const prop = props[key];
if (!isRemoteReceiverAttachableFragment(prop)) return;
attach(prop);
});
}
if ('children' in child) {
for (const grandChild of child.children) {
attach(grandChild);
}
}
}
function detach(
child: RemoteReceiverAttachableChild | RemoteReceiverAttachableFragment,
) {
attachedNodes.delete(child.id);
if (child.kind === KIND_COMPONENT && 'props' in child) {
const {props = {}} = child as any;
Object.keys(props).forEach((key) => {
const prop = props[key];
if (!isRemoteReceiverAttachableFragment(prop)) return;
detach(prop);
});
}
if ('children' in child) {
for (const grandChild of child.children) {
detach(grandChild);
}
}
}
}
function addVersion<T>(
value: T,
): T extends RemoteTextSerialization
? RemoteReceiverAttachableText
: T extends RemoteComponentSerialization
? RemoteReceiverAttachableChild
: T extends RemoteFragmentSerialization
? RemoteReceiverAttachableFragment
: never {
(value as any).version = 0;
return value as any;
}
function normalizeNode<
T extends
| RemoteTextSerialization
| RemoteComponentSerialization
| RemoteFragmentSerialization,
R,
>(node: T, normalizer: (node: T) => R) {
if (node.kind === KIND_FRAGMENT || node.kind === KIND_COMPONENT) {
(node as any).children.forEach((child: T) =>
normalizeNode(child, normalizer),
);
}
if (node.kind === KIND_COMPONENT && 'props' in node) {
const {props} = node as any;
for (const key of Object.keys(props)) {
const prop = props[key];
if (!isRemoteFragmentSerialization(prop)) continue;
props[key] = normalizeNode(prop as any, normalizer);
}
}
return normalizer(node);
}
export function isRemoteFragmentSerialization(
object: unknown,
): object is RemoteFragmentSerialization {
return isRemoteFragment(object) && 'id' in object && 'children' in object;
}
export function isRemoteReceiverAttachableFragment(
object: unknown,
): object is RemoteReceiverAttachableFragment {
return isRemoteFragmentSerialization(object) && 'version' in object;
} | the_stack |
import * as vscode from "vscode";
import { Context, Direction, Positions } from "..";
/**
* Moves the given position towards the given direction as long as the given
* function returns a non-`undefined` value.
*
* @see moveWhile.backward,takeWhile.forward
*/
export function moveWith<T>(
direction: Direction,
reduce: moveWith.Reduce<T>,
startState: T,
origin: vscode.Position,
document?: vscode.TextDocument,
): vscode.Position {
return direction === Direction.Backward
? moveWith.backward(reduce, startState, origin, document)
: moveWith.forward(reduce, startState, origin, document);
}
export namespace moveWith {
/**
* A reduce function passed to `moveWith`.
*/
export interface Reduce<T> {
(character: string, state: T): T | undefined;
}
/**
* Whether the last call to `moveWith` (and variants) reached the edge of the
* document.
*/
export declare const reachedDocumentEdge: boolean;
/**
* Moves the given position backward as long as the state returned by the
* given function is not `undefined`.
*
* ### Example
*
* ```js
* assert.deepStrictEqual(
* moveWith.backward((c, i) => +c === +i - 1 ? c : undefined,
* "8", new vscode.Position(0, 8)),
* new vscode.Position(0, 7),
* );
* ```
*
* With:
* ```
* 1234578
* ```
*/
export function backward<T>(
reduce: Reduce<T>,
startState: T,
origin: vscode.Position,
document = Context.current.document,
) {
didReachDocumentEdge = false;
const currentLineText = document.lineAt(origin).text;
let state: T | undefined = startState;
for (let i = origin.character - 1; i >= 0; i--) {
if ((state = reduce(currentLineText[i], state)) === undefined) {
return new vscode.Position(origin.line, i + 1);
}
}
for (let line = origin.line - 1; line >= 0; line--) {
const lineText = document.lineAt(line).text;
if ((state = reduce("\n", state)) === undefined) {
return new vscode.Position(line + 1, 0);
}
for (let i = lineText.length - 1; i >= 0; i--) {
if ((state = reduce(lineText[i], state)) === undefined) {
return new vscode.Position(line, i + 1);
}
}
}
didReachDocumentEdge = true;
return new vscode.Position(0, 0);
}
/**
* Moves the given position forward as long as the state returned by the given
* function is not `undefined`.
*
* ### Example
*
* ```js
* assert.deepStrictEqual(
* moveWith.forward((c, i) => +c === +i + 1 ? c : undefined,
* "1", new vscode.Position(0, 8)),
* new vscode.Position(0, 7),
* );
* ```
*
* With:
* ```
* 1234578
* ```
*/
export function forward<T>(
reduce: Reduce<T>,
startState: T,
origin: vscode.Position,
document = Context.current.document,
) {
didReachDocumentEdge = false;
const currentLineText = document.lineAt(origin).text;
let state: T | undefined = startState;
for (let i = origin.character; i < currentLineText.length; i++) {
if ((state = reduce(currentLineText[i], state)) === undefined) {
return new vscode.Position(origin.line, i);
}
}
if ((state = reduce("\n", state)) === undefined) {
return new vscode.Position(origin.line, currentLineText.length);
}
for (let line = origin.line + 1; line < document.lineCount; line++) {
const lineText = document.lineAt(line).text;
for (let i = 0; i < lineText.length; i++) {
if ((state = reduce(lineText[i], state)) === undefined) {
return new vscode.Position(line, i);
}
}
if ((state = reduce("\n", state)) === undefined) {
return new vscode.Position(line, lineText.length);
}
}
didReachDocumentEdge = true;
return document.lineAt(document.lineCount - 1).range.end;
}
/**
* Same as `moveWith`, but using raw char codes.
*
* @see moveWith,byCharCode.backward,byCharCode.forward
*/
export function byCharCode<T>(
direction: Direction,
reduce: byCharCode.Reduce<T>,
startState: T,
origin: vscode.Position,
document?: vscode.TextDocument,
): vscode.Position {
return direction === Direction.Backward
? byCharCode.backward(reduce, startState, origin, document)
: byCharCode.forward(reduce, startState, origin, document);
}
export namespace byCharCode {
/**
* A reduce function passed to `moveWith.byCharCode`.
*/
export interface Reduce<T> {
(charCode: number, state: T): T | undefined;
}
/**
* Same as `moveWith.backward`, but using raw char codes.
*
* @see moveWith.backward
*/
export function backward<T>(
reduce: Reduce<T>,
startState: T,
origin: vscode.Position,
document = Context.current.document,
) {
didReachDocumentEdge = false;
const currentLineText = document.lineAt(origin).text;
let state: T | undefined = startState;
for (let i = origin.character - 1; i >= 0; i--) {
if ((state = reduce(currentLineText.charCodeAt(i), state)) === undefined) {
return new vscode.Position(origin.line, i + 1);
}
}
for (let line = origin.line - 1; line >= 0; line--) {
const lineText = document.lineAt(line).text;
if ((state = reduce(10 /* \n */, state)) === undefined) {
return new vscode.Position(line + 1, 0);
}
for (let i = lineText.length - 1; i >= 0; i--) {
if ((state = reduce(lineText.charCodeAt(i), state)) === undefined) {
return new vscode.Position(line, i + 1);
}
}
}
didReachDocumentEdge = true;
return new vscode.Position(0, 0);
}
/**
* Same as `moveWith.forward`, but using raw char codes.
*
* @see moveWith.forward
*/
export function forward<T>(
reduce: Reduce<T>,
startState: T,
origin: vscode.Position,
document = Context.current.document,
) {
didReachDocumentEdge = false;
const currentLineText = document.lineAt(origin).text;
let state: T | undefined = startState;
for (let i = origin.character; i < currentLineText.length; i++) {
if ((state = reduce(currentLineText.charCodeAt(i), state)) === undefined) {
return new vscode.Position(origin.line, i);
}
}
if ((state = reduce(10 /* \n */, state)) === undefined) {
return new vscode.Position(origin.line, currentLineText.length);
}
for (let line = origin.line + 1; line < document.lineCount; line++) {
const lineText = document.lineAt(line).text;
for (let i = 0; i < lineText.length; i++) {
if ((state = reduce(lineText.charCodeAt(i), state)) === undefined) {
return new vscode.Position(line, i);
}
}
if ((state = reduce(10 /* \n */, state)) === undefined) {
return new vscode.Position(line, lineText.length);
}
}
didReachDocumentEdge = true;
return document.lineAt(document.lineCount - 1).range.end;
}
}
}
/**
* Moves the given position towards the given direction as long as the given
* predicate is true.
*
* @see moveWhile.backward,takeWhile.forward
*/
export function moveWhile(
direction: Direction,
predicate: moveWhile.Predicate,
origin: vscode.Position,
document?: vscode.TextDocument,
): vscode.Position {
return direction === Direction.Backward
? moveWhile.backward(predicate, origin, document)
: moveWhile.forward(predicate, origin, document);
}
export namespace moveWhile {
/**
* A predicate passed to `moveWhile`.
*/
export interface Predicate {
(character: string): boolean;
}
/**
* Whether the last call to `moveWhile` (and variants) reached the edge of the
* document.
*/
export declare const reachedDocumentEdge: boolean;
/**
* Moves the given position backward as long as the given predicate is true.
*
* ### Example
*
* ```js
* assert.deepStrictEqual(
* moveWhile.backward((c) => /\w/.test(c), new vscode.Position(0, 3)),
* new vscode.Position(0, 0),
* );
*
* assert.deepStrictEqual(
* moveWhile.backward((c) => c === "c", new vscode.Position(0, 3)),
* new vscode.Position(0, 2),
* );
*
* assert.deepStrictEqual(
* moveWhile.backward((c) => c === "b", new vscode.Position(0, 3)),
* new vscode.Position(0, 3),
* );
* ```
*
* With:
* ```
* abc
* ```
*/
export function backward(
predicate: Predicate,
origin: vscode.Position,
document?: vscode.TextDocument,
): vscode.Position {
return moveWith.backward((ch) => predicate(ch) ? null : undefined, null, origin, document);
}
/**
* Moves the given position forward as long as the given predicate is true.
*
* ### Example
*
* ```js
* assert.deepStrictEqual(
* moveWhile.forward((c) => /\w/.test(c), new vscode.Position(0, 0)),
* new vscode.Position(0, 3),
* );
*
* assert.deepStrictEqual(
* moveWhile.forward((c) => c === "a", new vscode.Position(0, 0)),
* new vscode.Position(0, 1),
* );
*
* assert.deepStrictEqual(
* moveWhile.forward((c) => c === "b", new vscode.Position(0, 0)),
* new vscode.Position(0, 0),
* );
* ```
*
* With:
* ```
* abc
* ```
*/
export function forward(
predicate: Predicate,
origin: vscode.Position,
document?: vscode.TextDocument,
): vscode.Position {
return moveWith.forward((ch) => predicate(ch) ? null : undefined, null, origin, document);
}
/**
* Same as `moveWith`, but using raw char codes.
*
* @see moveWith,byCharCode.backward,byCharCode.forward
*/
export function byCharCode(
direction: Direction,
predicate: byCharCode.Predicate,
origin: vscode.Position,
document?: vscode.TextDocument,
): vscode.Position {
return direction === Direction.Backward
? byCharCode.backward(predicate, origin, document)
: byCharCode.forward(predicate, origin, document);
}
export namespace byCharCode {
/**
* A predicate passed to `moveWhile.byCharCode`.
*/
export interface Predicate {
(charCode: number): boolean;
}
/**
* Same as `moveWhile.backward`, but using raw char codes.
*
* @see moveWhile.backward
*/
export function backward(
predicate: Predicate,
origin: vscode.Position,
document?: vscode.TextDocument,
): vscode.Position {
return moveWith.byCharCode.backward(
(ch) => predicate(ch) ? null : undefined,
null,
origin,
document,
);
}
/**
* Same as `moveWhile.forward`, but using raw char codes.
*
* @see moveWhile.forward
*/
export function forward(
predicate: Predicate,
origin: vscode.Position,
document?: vscode.TextDocument,
): vscode.Position {
return moveWith.byCharCode.forward(
(ch) => predicate(ch) ? null : undefined,
null,
origin,
document,
);
}
}
}
/**
* Moves the given position line-by-line towards the given direction as long as
* the given function returns `undefined`, and returns the first non-`undefined`
* value it returns or `undefined` if the edge of the document is reached.
*
* @see lineByLine.backward,lineByLine.forward
*/
export function lineByLine<T>(
direction: Direction,
seek: lineByLine.Seek<T>,
origin: vscode.Position,
document?: vscode.TextDocument,
) {
return direction === Direction.Backward
? lineByLine.backward(seek, origin, document)
: lineByLine.forward(seek, origin, document);
}
export namespace lineByLine {
/**
* A reduce function passed to `lineByLine`.
*/
export interface Seek<T> {
(lineText: string, lineStart: vscode.Position): T | undefined;
}
/**
* Whether the last call to `lineByLine` (and variants) reached the edge of
* the document.
*/
export declare const reachedDocumentEdge: boolean;
/**
* Moves the given position backward line-by-line as long as the given
* function returns `undefined`, and returns the first non-`undefined`
* value it returns or `undefined` if the start of the document is reached.
*/
export function backward<T>(
seek: Seek<T>,
origin: vscode.Position,
document = Context.current.document,
) {
didReachDocumentEdge = false;
const originLine = document.lineAt(origin),
originLineText = originLine.text.slice(0, origin.character),
originResult = seek(originLineText, Positions.lineStart(origin.line));
if (originResult !== undefined) {
return originResult;
}
for (let line = origin.line - 1; line >= 0; line--) {
const lineText = document.lineAt(line).text,
result = seek(lineText, Positions.lineStart(line));
if (result !== undefined) {
return result;
}
}
didReachDocumentEdge = true;
return undefined;
}
/**
* Moves the given position forward line-by-line as long as the given
* function returns `undefined`, and returns the first non-`undefined`
* value it returns or `undefined` if the end of the document is reached.
*/
export function forward<T>(
seek: Seek<T>,
origin: vscode.Position,
document = Context.current.document,
) {
didReachDocumentEdge = false;
const originLine = document.lineAt(origin),
originLineText = originLine.text.slice(origin.character),
originResult = seek(originLineText, origin);
if (originResult !== undefined) {
return originResult;
}
for (let line = origin.line + 1, lineCount = document.lineCount; line < lineCount; line++) {
const lineText = document.lineAt(line).text,
result = seek(lineText, Positions.lineStart(line));
if (result !== undefined) {
return result;
}
}
didReachDocumentEdge = true;
return undefined;
}
}
/**
* Advances in the given direction as long as lines are empty, and returns the
* position closest to the origin in a non-empty line. The origin line will
* always be skipped.
*/
export function skipEmptyLines(
direction: Direction,
origin: number | vscode.Position,
document = Context.current.document,
) {
didReachDocumentEdge = false;
let line = typeof origin === "number" ? origin : origin.line;
while (line >= 0 && line < document.lineCount) {
const lineLength = document.lineAt(line).text.length;
if (lineLength > 0) {
return new vscode.Position(
line,
direction === Direction.Backward ? lineLength : 0,
);
}
line += direction;
}
didReachDocumentEdge = true;
return Positions.edge(direction, document);
}
export namespace skipEmptyLines {
/**
* Whether the last call to `skipEmptyLines` (and variants) reached the edge
* of the document.
*/
export declare const reachedDocumentEdge: boolean;
/**
* Same as `skipEmptyLines` with a `Backward` direction.
*
* @see skipEmptyLines
*/
export function backward(origin: number | vscode.Position, document?: vscode.TextDocument) {
return skipEmptyLines(Direction.Backward, origin, document);
}
/**
* Same as `skipEmptyLines` with a `Forward` direction.
*
* @see skipEmptyLines
*/
export function forward(origin: number | vscode.Position, document?: vscode.TextDocument) {
return skipEmptyLines(Direction.Forward, origin, document);
}
}
let didReachDocumentEdge = false;
const getReachedDocumentEdge = {
get() {
return didReachDocumentEdge;
},
};
for (const obj of [
lineByLine,
moveWhile,
moveWhile.byCharCode,
moveWith,
moveWith.byCharCode,
skipEmptyLines,
]) {
Object.defineProperty(obj, "reachedDocumentEdge", getReachedDocumentEdge);
} | the_stack |
import { Rule, SchematicContext, Tree, UpdateRecorder, chain } from '@angular-devkit/schematics';
import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks';
import assert from 'assert';
import * as ts from '../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
import {
NodeDependency,
getPackageJsonDependency,
removePackageJsonDependency,
} from '../../utility/dependencies';
import { allWorkspaceTargets, getWorkspace } from '../../utility/workspace';
/**
* Migrates all polyfills files of projects to remove two dependencies originally needed by Internet
* Explorer, but which are no longer needed now that support for IE has been dropped (`classlist.js`
* and `web-animations-js`).
*
* The polyfills file includes side-effectful imports of these dependencies with comments about
* their usage:
*
* ```
* /**
* * IE11 requires the following for NgClass support on SVG elements
* *\/
* import 'classlist.js';
*
* /**
* * Web Animations `@angular/platform-browser/animations`
* * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
* * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
* *\/
* import 'web-animations-js';
* ```
*
* This migration removes the `import` statements as well as any preceeding comments. It also
* removes these dependencies from `package.json` if present and schedules an `npm install` task to
* remove them from `node_modules/`.
*
* Also, the polyfills file has previously been generated with these imports commented out, to not
* include the dependencies by default, but still allow users to easily uncomment and enable them
* when required. So the migration also looks for:
*
* ```
* // import 'classlist.js'; // Run `npm install --save classlist.js`.
* // OR
* // import 'web-animations-js'; // Run `npm install --save web-animations-js`.
* ```
*
* And removes them as well. This keeps the polyfills files clean and up to date. Whitespace is
* handled by leaving all trailing whitespace alone, and deleting all the leading newlines until the
* previous non-empty line of code. This means any extra lines before a removed polyfill is dropped,
* while any extra lines after a polyfill are retained. This roughly correlates to how a real
* developer might write such a file.
*/
export default function (): Rule {
return async (tree: Tree, ctx: SchematicContext) => {
const modulesToDrop = new Set(['classlist.js', 'web-animations-js']);
// Remove modules from `package.json` dependencies.
const moduleDeps = Array.from(modulesToDrop.values())
.map((module) => getPackageJsonDependency(tree, module))
.filter((dep) => !!dep) as NodeDependency[];
for (const { name } of moduleDeps) {
removePackageJsonDependency(tree, name);
}
// Run `npm install` after removal. This isn't strictly necessary, as keeping the dependencies
// in `node_modules/` doesn't break anything. however non-polyfill usages of these dependencies
// will work while they are in `node_modules/` but then break on the next `npm install`. If any
// such usages exist, it is better for them to fail immediately after the migration instead of
// the next time the user happens to `npm install`. As an optimization, only run `npm install`
// if a dependency was actually removed.
if (moduleDeps.length > 0) {
ctx.addTask(new NodePackageInstallTask());
}
// Find all the polyfill files in the workspace.
const wksp = await getWorkspace(tree);
const polyfills = Array.from(allWorkspaceTargets(wksp))
.filter(([_, target]) => !!target.options?.polyfills)
.map(([_, target]) => target.options?.polyfills as string);
const uniquePolyfills = Array.from(new Set(polyfills));
// Drop the modules from each polyfill.
return chain(uniquePolyfills.map((polyfillPath) => dropModules(polyfillPath, modulesToDrop)));
};
}
/** Processes the given polyfill path and removes any `import` statements for the given modules. */
function dropModules(polyfillPath: string, modules: Set<string>): Rule {
return (tree: Tree, ctx: SchematicContext) => {
const sourceContent = tree.read(polyfillPath);
if (!sourceContent) {
ctx.logger.warn(
'Polyfill path from workspace configuration could not be read, does the file exist?',
{ polyfillPath },
);
return;
}
const content = sourceContent.toString('utf8');
const sourceFile = ts.createSourceFile(
polyfillPath,
content.replace(/^\uFEFF/, ''),
ts.ScriptTarget.Latest,
true /* setParentNodes */,
);
// Remove polyfills for the given module specifiers.
const recorder = tree.beginUpdate(polyfillPath);
removePolyfillImports(recorder, sourceFile, modules);
removePolyfillImportComments(recorder, sourceFile, modules);
tree.commitUpdate(recorder);
return tree;
};
}
/**
* Searches the source file for any `import '${module}';` statements and removes them along with
* any preceeding comments.
*
* @param recorder The recorder to remove from.
* @param sourceFile The source file containing the `import` statements.
* @param modules The module specifiers to remove.
*/
function removePolyfillImports(
recorder: UpdateRecorder,
sourceFile: ts.SourceFile,
modules: Set<string>,
): void {
const imports = sourceFile.statements.filter((stmt) =>
ts.isImportDeclaration(stmt),
) as ts.ImportDeclaration[];
for (const i of imports) {
// Should always be a string literal.
assert(ts.isStringLiteral(i.moduleSpecifier));
// Ignore other modules.
if (!modules.has(i.moduleSpecifier.text)) {
continue;
}
// Remove the module import statement.
recorder.remove(i.getStart(), i.getWidth());
// Remove leading comments. "Leading" comments seems to include comments within the node, so
// even though `getFullText()` returns an index before any leading comments to a node, it will
// still find and process them.
ts.forEachLeadingCommentRange(
sourceFile.getFullText(),
i.getFullStart(),
(start, end, _, hasTrailingNewLine) => {
// Include both leading **and** trailing newlines because these are comments that *preceed*
// the `import` statement, so "trailing" newlines here are actually in-between the `import`
// and it's leading comments.
const commentRangeWithoutNewLines = { start, end };
const commentRangeWithTrailingNewLines = hasTrailingNewLine
? includeTrailingNewLine(sourceFile, commentRangeWithoutNewLines)
: commentRangeWithoutNewLines;
const commentRange = includeLeadingNewLines(sourceFile, commentRangeWithTrailingNewLines);
if (!isProtectedComment(sourceFile, commentRange)) {
recorder.remove(commentRange.start, commentRange.end - commentRange.start);
}
},
);
}
}
/**
* Searches the source file for any `// import '${module}';` comments and removes them along with
* any preceeding comments.
*
* Recent `ng new` invocations generate polyfills commented out and not used by default. Ex:
* /**
* * IE11 requires the following for NgClass support on SVG elements
* *\/
* // import 'classlist.js'; // Run `npm install --save classlist.js`.
*
* This function identifies any commented out import statements for the given module specifiers and
* removes them along with immediately preceeding comments.
*
* @param recorder The recorder to remove from.
* @param sourceFile The source file containing the commented `import` statements.
* @param modules The module specifiers to remove.
*/
function removePolyfillImportComments(
recorder: UpdateRecorder,
sourceFile: ts.SourceFile,
modules: Set<string>,
): void {
// Find all comment ranges in the source file.
const commentRanges = getCommentRanges(sourceFile);
// Find the indexes of comments which contain `import` statements for the given modules.
const moduleImportCommentIndexes = filterIndex(commentRanges, ({ start, end }) => {
const comment = getCommentText(sourceFile.getFullText().slice(start, end));
return Array.from(modules.values()).some((module) => comment.startsWith(`import '${module}';`));
});
// Use the module import comment **and** it's preceding comment if present.
const commentIndexesToRemove = moduleImportCommentIndexes.flatMap((index) => {
if (index === 0) {
return [0];
} else {
return [index - 1, index];
}
});
// Get all the ranges for the comments to remove.
const commentRangesToRemove = commentIndexesToRemove
.map((index) => commentRanges[index])
// Include leading newlines but **not** trailing newlines in order to leave appropriate space
// between any remaining polyfills.
.map((range) => includeLeadingNewLines(sourceFile, range))
.filter((range) => !isProtectedComment(sourceFile, range));
// Remove the comments.
for (const { start, end } of commentRangesToRemove) {
recorder.remove(start, end - start);
}
}
/** Represents a segment of text in a source file starting and ending at the given offsets. */
interface SourceRange {
start: number;
end: number;
}
/**
* Returns whether a comment range is "protected", meaning it should **not** be deleted.
*
* There are two comments which are considered "protected":
* 1. The file overview doc comment previously generated by `ng new`.
* 2. The browser polyfills header (/***** BROWSER POLYFILLS *\/).
*/
function isProtectedComment(sourceFile: ts.SourceFile, { start, end }: SourceRange): boolean {
const comment = getCommentText(sourceFile.getFullText().slice(start, end));
const isFileOverviewDocComment = comment.startsWith(
'This file includes polyfills needed by Angular and is loaded before the app.',
);
const isBrowserPolyfillsHeader = comment.startsWith('BROWSER POLYFILLS');
return isFileOverviewDocComment || isBrowserPolyfillsHeader;
}
/** Returns all the comments in the given source file. */
function getCommentRanges(sourceFile: ts.SourceFile): SourceRange[] {
const commentRanges = [] as SourceRange[];
// Comments trailing the last node are also included in this.
ts.forEachChild(sourceFile, (node) => {
ts.forEachLeadingCommentRange(sourceFile.getFullText(), node.getFullStart(), (start, end) => {
commentRanges.push({ start, end });
});
});
return commentRanges;
}
/** Returns a `SourceRange` with any leading newlines' characters included if present. */
function includeLeadingNewLines(
sourceFile: ts.SourceFile,
{ start, end }: SourceRange,
): SourceRange {
const text = sourceFile.getFullText();
while (start > 0) {
if (start > 2 && text.slice(start - 2, start) === '\r\n') {
// Preceeded by `\r\n`, include that.
start -= 2;
} else if (start > 1 && text[start - 1] === '\n') {
// Preceeded by `\n`, include that.
start--;
} else {
// Not preceeded by any newline characters, don't include anything else.
break;
}
}
return { start, end };
}
/** Returns a `SourceRange` with the trailing newline characters included if present. */
function includeTrailingNewLine(
sourceFile: ts.SourceFile,
{ start, end }: SourceRange,
): SourceRange {
const newline = sourceFile.getFullText().slice(end, end + 2);
if (newline === '\r\n') {
return { start, end: end + 2 };
} else if (newline.startsWith('\n')) {
return { start, end: end + 1 };
} else {
throw new Error('Expected comment to end in a newline character (either `\\n` or `\\r\\n`).');
}
}
/**
* Extracts the text from a comment. Attempts to remove any extraneous syntax and trims the content.
*/
function getCommentText(commentInput: string): string {
const comment = commentInput.trim();
if (comment.startsWith('//')) {
return comment.slice('//'.length).trim();
} else if (comment.startsWith('/*')) {
const withoutPrefix = comment.replace(/\/\*+/, '');
const withoutSuffix = withoutPrefix.replace(/\*+\//, '');
const withoutNewlineAsterisks = withoutSuffix.replace(/^\s*\*\s*/, '');
return withoutNewlineAsterisks.trim();
} else {
throw new Error(`Expected a comment, but got: "${comment}".`);
}
}
/** Like `Array.prototype.filter`, but returns the index of each item rather than its value. */
function filterIndex<Item>(items: Item[], filter: (item: Item) => boolean): number[] {
return Array.from(items.entries())
.filter(([_, item]) => filter(item))
.map(([index]) => index);
} | the_stack |
import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
Platform,
RefreshControl,
SafeAreaView,
TouchableOpacity,
VirtualizedList,
} from 'react-native';
import { useNavigation, useRoute } from '@react-navigation/native';
import { HeaderBackButton } from '@react-navigation/stack';
import {
ActionSheet,
ActionSheetProps,
CustomHeader,
FooterLoadingIndicator,
LoadingOrError,
NestedComment,
PostItem,
} from '../components';
import { DEFAULT_CHANNEL } from '../constants';
import { Text } from '../core-ui';
import { client } from '../graphql/client';
import {
TOPIC_FRAGMENT,
USER_FRAGMENT,
} from '../graphql/server/getTopicDetail';
import {
errorHandler,
errorHandlerAlert,
getImage,
handleSpecialMarkdown,
LoginError,
postDetailContentHandler,
useStorage,
} from '../helpers';
import { usePostRaw, useTopicDetail, useTopicTiming } from '../hooks';
import { makeStyles, useTheme } from '../theme';
import { Post, StackNavProp, StackRouteProp } from '../types';
import { usePost } from '../utils';
// postNumber of the topic is 1
// scrollToIndex is postNumber -2 for replies because the postNumber will start at 2
// while the index in flatlist will start at 0
type PostReplyItem = { item: Post };
type OnScrollInfo = {
index: number;
highestMeasuredFrameIndex: number;
averageItemLength: number;
};
const MAX_DEFAULT_LOADED_POST_COUNT = 19;
export default function PostDetail() {
const { topicsData } = usePost();
const styles = useStyles();
const { colors, spacing } = useTheme();
const navigation = useNavigation<StackNavProp<'PostDetail'>>();
const { navigate, goBack, setOptions, setParams } = navigation;
const {
params: {
topicId,
selectedChannelId = -1,
postNumber = null,
focusedPostNumber,
prevScreen,
},
} = useRoute<StackRouteProp<'PostDetail'>>();
const storage = useStorage();
const currentUserId = storage.getItem('user')?.id;
const channels = storage.getItem('channels');
const virtualListRef = useRef<VirtualizedList<Post>>(null);
const [hasOlderPost, setHasOlderPost] = useState(true);
const [hasNewerPost, setHasNewerPost] = useState(true);
const [loadingRefresh, setLoadingRefresh] = useState(false);
const [loadingOlderPost, setLoadingOlderPost] = useState(false);
const [loadingNewerPost, setLoadingNewerPost] = useState(false);
const [loading, setLoading] = useState(true);
const [canFlagFocusPost, setCanFlagFocusPost] = useState(false);
const [canEditFocusPost, setCanEditFocusPost] = useState(false);
const [showActionSheet, setShowActionSheet] = useState(false);
const [replyLoading, setReplyLoading] = useState(false);
const [postIdOnFocus, setPostIdOnFocus] = useState(0);
const [startIndex, setStartIndex] = useState(0);
const [endIndex, setEndIndex] = useState(0);
const [stream, setStream] = useState<Array<number>>();
const [fromPost, setFromPost] = useState(false);
const [author, setAuthor] = useState('');
const [showOptions, setShowOptions] = useState(false);
const [flaggedByCommunity, setFlaggedByCommunity] = useState(false);
const [content, setContent] = useState('');
const [images, setImages] = useState<Array<string>>();
const [mentionedUsers, setmentionedUsers] = useState<Array<string>>();
const [isHidden, setHidden] = useState(false);
const ios = Platform.OS === 'ios';
useEffect(() => {
if (selectedChannelId !== -1) {
setOptions({
headerLeft: () => (
<HeaderBackButton
onPress={goBack}
style={{
paddingBottom: ios ? spacing.l : spacing.s,
}}
tintColor={colors.primary}
/>
),
});
}
}, [colors, goBack, ios, selectedChannelId, setOptions, spacing]);
const {
data,
loading: topicDetailLoading,
error,
refetch,
fetchMore,
} = useTopicDetail(
{
variables: { topicId, postPointer: postNumber },
},
'HIDE_ALERT',
);
const { postRaw } = usePostRaw({
onCompleted: ({ postRaw: { raw, listOfCooked, listOfMention } }) => {
setContent(raw);
setImages(listOfCooked);
setmentionedUsers(listOfMention);
},
onError: () => {},
});
let postDetailContentHandlerResult = useMemo(() => {
if (!data) {
return;
}
return postDetailContentHandler({
topicDetailData: data.topicDetail,
channels,
});
}, [data, channels]);
let topic = postDetailContentHandlerResult?.topic;
let posts = postDetailContentHandlerResult?.posts;
useEffect(() => {
let isItemValid = false;
if (!!(topic && topic.canEditTopic)) {
isItemValid = true;
}
if (!!(posts && posts[0].canFlag && !posts[0].hidden)) {
isItemValid = true;
}
setShowOptions(isItemValid);
}, [topic, posts]);
useEffect(() => {
const topicData = topicsData.find(
(topicData) => topicData?.topicId === topicId,
);
setContent(topicData?.content || '');
setHidden(topicData?.hidden || false);
if (posts) {
postRaw({ variables: { postId: posts[0].id } });
setHidden(posts[0].hidden || false);
}
}, [posts, topicsData, topicId, postRaw]);
const onPressViewIgnoredContent = () => {
setHidden(false);
};
useEffect(() => {
if (data) {
let topicDetailData = data.topicDetail;
let {
stream: tempStream,
firstPostIndex,
lastPostIndex,
} = postDetailContentHandler({ topicDetailData, channels });
setStream(tempStream || []);
setStartIndex(firstPostIndex);
setEndIndex(lastPostIndex);
setLoading(false);
setReplyLoading(false);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data]);
const refreshPost = async () => {
setLoadingRefresh(true);
refetch({ topicId }).then(({ data }) => {
const {
topicDetail: { postStream, title, categoryId, tags },
} = data;
const { stream, posts } = postStream;
const [firstPostId] = stream ?? [0];
const firstPost = posts.find(({ id }) => firstPostId === id);
client.writeFragment({
id: `Topic:${topicId}`,
fragment: TOPIC_FRAGMENT,
data: {
title,
excerpt: firstPost?.raw,
imageUrl: firstPost?.listOfCooked || undefined,
categoryId,
tags,
},
});
setLoadingRefresh(false);
});
};
const loadOlderPost = async () => {
if (loadingOlderPost || !hasOlderPost || !stream || topicDetailLoading) {
return;
}
setLoadingOlderPost(true);
let nextEndIndex = startIndex;
let newDataCount = Math.min(10, stream.length - nextEndIndex);
let nextStartIndex = Math.max(0, nextEndIndex - newDataCount);
let nextPosts = stream.slice(nextStartIndex, nextEndIndex);
if (!nextPosts.length) {
return;
}
await fetchMore({
variables: {
topicId,
posts: nextPosts,
},
});
setStartIndex(nextStartIndex);
setLoadingOlderPost(false);
};
const loadNewerPost = async () => {
if (loadingNewerPost || !hasNewerPost || !stream || topicDetailLoading) {
return;
}
setLoadingNewerPost(true);
let nextStartIndex = endIndex + 1;
let newDataCount = Math.min(10, stream.length - nextStartIndex);
let nextEndIndex = nextStartIndex + newDataCount;
let nextPosts = stream.slice(nextStartIndex, nextEndIndex);
if (!nextPosts.length) {
return;
}
await fetchMore({
variables: {
topicId,
posts: nextPosts,
},
});
setEndIndex(nextEndIndex - 1);
setLoadingNewerPost(false);
};
useTopicTiming(topicId, startIndex, stream);
useEffect(() => {
if (!stream || !posts) {
return;
}
setHasOlderPost(stream[0] !== posts[0].id);
setHasNewerPost(stream[stream.length - 1] !== posts[posts.length - 1].id);
}, [stream, topicId, posts]);
useEffect(() => {
async function refetchData() {
let index = 0;
if (focusedPostNumber === 1) {
await refetch({ topicId });
} else {
const result = await refetch({
topicId,
postPointer: focusedPostNumber,
});
let {
data: {
topicDetail: { postStream },
},
} = result;
const firstPostIndex =
postStream.stream?.findIndex(
(postId) => postId === postStream.posts[0].id,
) || 0;
let pointerToIndex = focusedPostNumber
? focusedPostNumber - 1 - firstPostIndex
: 0;
index = Math.min(MAX_DEFAULT_LOADED_POST_COUNT, pointerToIndex);
}
setTimeout(() => {
try {
virtualListRef.current &&
virtualListRef.current.scrollToIndex({
index,
animated: true,
});
} catch {
virtualListRef.current && virtualListRef.current.scrollToEnd();
}
}, 500);
}
const unsubscribe = navigation.addListener('focus', () => {
if (focusedPostNumber != null && prevScreen === 'PostPreview') {
setParams({ prevScreen: '' });
setReplyLoading(true);
refetchData();
}
});
return unsubscribe;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [prevScreen, focusedPostNumber]);
useEffect(() => {
if (virtualListRef.current && postNumber) {
if (posts?.slice(1).length !== 0) {
virtualListRef.current.scrollToIndex({
animated: true,
index: postNumber > 1 ? postNumber - 2 - startIndex : 0,
});
}
}
}, [virtualListRef.current?.state]); // eslint-disable-line
if (error) {
return <LoadingOrError message={errorHandler(error)} />;
}
const onPressAuthor = (username: string) => {
navigate('UserInformation', { username });
};
const renderTopicFromCache = () => {
const cacheTopic = client.readFragment({
id: `Topic:${topicId}`,
fragment: TOPIC_FRAGMENT,
});
if (cacheTopic) {
const cacheUser = client.readFragment({
id: `UserIcon:${cacheTopic.authorUserId}`,
fragment: USER_FRAGMENT,
});
const cacheFreqPoster = cacheTopic.posters?.map(
(item: { userId: number }) => {
let user = client.readFragment({
id: `UserIcon:${item.userId}`,
fragment: USER_FRAGMENT,
});
const { id, username, avatar } = user;
return {
id,
username,
avatar: getImage(avatar),
};
},
);
const channels = storage.getItem('channels');
const channel = channels?.find(
(channel) => channel.id === cacheTopic.categoryId,
);
const { title, excerpt, hidden, imageUrl, tags } = cacheTopic;
const { username, avatar } = cacheUser;
let tempPost = {
id: 0,
topicId,
title,
content: excerpt,
hidden,
username,
avatar: getImage(avatar),
images: [imageUrl] ?? undefined,
viewCount: 0,
replyCount: 0,
likeCount: 0,
isLiked: false,
channel: channel ?? DEFAULT_CHANNEL,
tags,
createdAt: '',
freqPosters: cacheFreqPoster ?? [],
};
return (
<PostItem
data={tempPost}
postList={false}
nonclickable
onPressAuthor={onPressAuthor}
content={content}
isHidden={isHidden}
/>
);
}
return null;
};
if (!data || !topic) {
if (loading) {
return renderTopicFromCache() ?? <LoadingOrError loading />;
}
return <LoadingOrError message={t('Post is not available')} />;
}
if (replyLoading) {
return <LoadingOrError message={t('Finishing your Reply')} loading />;
}
const navToFlag = (
postId = postIdOnFocus,
isPost = fromPost,
flaggedAuthor = author,
) => {
navigate('FlagPost', { postId, isPost, flaggedAuthor });
};
const navToPost = (postId = postIdOnFocus) => {
if (!topic) {
return;
}
const {
firstPostId,
id,
title,
selectedChanelId: selectedChannelId,
selectedTag: selectedTagsIds,
} = topic;
if (stream && postId === stream[0]) {
navigate('NewPost', {
editPostId: firstPostId,
editTopicId: id,
selectedChannelId,
selectedTagsIds,
oldContent: getPost(firstPostId)?.content,
oldTitle: title,
oldChannel: selectedChannelId,
oldTags: selectedTagsIds,
editedUser: {
username: getPost(postId)?.username || '',
avatar: getPost(postId)?.avatar || '',
},
});
} else {
navigate('PostReply', {
topicId,
title,
editPostId: postId,
oldContent: getPost(postId)?.content,
focusedPostNumber: (getPost(postId)?.postNumber || 2) - 1,
editedUser: {
username: getPost(postId)?.username || '',
avatar: getPost(postId)?.avatar || '',
},
});
}
};
const onPressMore = (
id?: number,
canFlag = !!(posts && posts[0].canFlag),
canEdit = !!(topic && topic.canEditTopic),
flaggedByCommunity = !!(posts && posts[0].hidden),
fromPost = true,
author?: string,
) => {
if (currentUserId && topic) {
if (!id || typeof id !== 'number') {
id = topic.firstPostId;
}
setPostIdOnFocus(id);
setCanEditFocusPost(canEdit);
setCanFlagFocusPost(canFlag);
setFlaggedByCommunity(flaggedByCommunity);
setShowActionSheet(true);
if (author) {
setAuthor(author);
}
if (!fromPost) {
setFromPost(false);
} else {
setFromPost(true);
}
} else {
errorHandlerAlert(LoginError, navigate);
}
};
const actionItemOptions = () => {
let options: ActionSheetProps['options'] = [];
ios && options.push({ label: t('Cancel') });
canEditFocusPost && options.push({ label: t('Edit Post') });
!flaggedByCommunity &&
options.push({
label: canFlagFocusPost ? t('Flag') : t('Flagged'),
disabled: !canFlagFocusPost,
});
return options;
};
const actionItemOnPress = (btnIndex: number) => {
switch (btnIndex) {
case 0: {
return canEditFocusPost ? navToPost() : navToFlag();
}
case 1: {
return canEditFocusPost && !flaggedByCommunity && navToFlag();
}
}
};
const getPost = (postId?: number) => {
if (!posts) {
return;
}
return postId === -1 || postIdOnFocus === -1
? undefined
: posts.find(({ id }) => id === (postId || postIdOnFocus)) || posts[0];
};
const getReplyPost = (postNumberReplied: number) => {
if (!posts) {
return;
}
return posts.find(({ postNumber }) => postNumberReplied === postNumber);
};
const onPressReply = (id = -1) => {
if (currentUserId) {
if (stream && topic) {
navigate('PostReply', {
topicId,
title: topic.title,
post: getPost(id),
focusedPostNumber: stream.length,
});
}
} else {
errorHandlerAlert(LoginError, navigate);
}
};
let arrayCommentLikeCount = posts
? posts.slice(1).map((val) => {
return val.likeCount;
})
: [];
let sumCommentLikeCount = arrayCommentLikeCount.reduce((a, b) => a + b, 0);
let currentPost = topicsData.filter((val) => {
return val.topicId === topicId;
});
const getItem = (data: Array<Post>, index: number) => data[index];
const getItemCount = (data: Array<Post>) => data.length;
const keyExtractor = ({ id }: Post) => `post-${id}`;
const renderItem = ({ item }: PostReplyItem) => {
const { replyToPostNumber, canEdit, canFlag, hidden, id, username } = item;
const replyPost =
replyToPostNumber !== -1
? getReplyPost(replyToPostNumber ?? 1)
: undefined;
let isItemValid = false;
if (canEdit) {
isItemValid = true;
}
if (canFlag && !hidden) {
isItemValid = true;
}
return (
<NestedComment
data={item}
replyTo={replyPost}
key={id}
style={styles.lowerContainer}
showOptions={isItemValid}
onPressReply={() => onPressReply(id)}
onPressMore={() =>
onPressMore(id, canFlag, canEdit, hidden, false, username)
}
onPressAuthor={onPressAuthor}
/>
);
};
const onScrollHandler = ({ index }: OnScrollInfo) => {
setTimeout(
() =>
virtualListRef.current?.scrollToIndex({
animated: true,
index,
}),
50,
);
};
return (
<>
<SafeAreaView style={styles.container}>
{showOptions && (
<CustomHeader
title=""
rightIcon="More"
onPressRight={onPressMore}
noShadow
/>
)}
<VirtualizedList
ref={virtualListRef}
refreshControl={
<RefreshControl
refreshing={
(loadingRefresh || topicDetailLoading) && !loadingNewerPost
}
onRefresh={refreshPost}
tintColor={colors.primary}
/>
}
data={posts && posts.slice(1)}
getItem={getItem}
getItemCount={getItemCount}
renderItem={renderItem}
keyExtractor={keyExtractor}
initialNumToRender={5}
maxToRenderPerBatch={7}
windowSize={10}
ListHeaderComponent={
posts && stream && posts[0].id === stream[0] && topic ? (
<PostItem
data={{
...posts[0],
likeCount:
currentPost.length !== 0
? currentPost[0].likeCount - sumCommentLikeCount
: 0,
content: handleSpecialMarkdown(posts[0].content),
title: topic.title,
tags: topic.selectedTag,
viewCount: topic.viewCount,
replyCount: topic.replyCount,
}}
postList={false}
nonclickable
onPressAuthor={onPressAuthor}
content={content}
images={images}
mentionedUsers={mentionedUsers}
isHidden={isHidden}
onPressViewIgnoredContent={onPressViewIgnoredContent}
/>
) : (
renderTopicFromCache()
)
}
onRefresh={hasOlderPost ? loadOlderPost : refreshPost}
refreshing={
(loadingRefresh || loadingOlderPost || topicDetailLoading) &&
!loadingNewerPost
}
onEndReachedThreshold={0.1}
onEndReached={loadNewerPost}
ListFooterComponent={
<FooterLoadingIndicator isHidden={!hasNewerPost} />
}
style={styles.scrollViewContainer}
initialScrollIndex={0}
onScrollToIndexFailed={onScrollHandler}
/>
<TouchableOpacity
style={styles.inputCommentContainer}
onPress={() => onPressReply(-1)}
>
<Text style={styles.inputComment}>{t('Write your reply here')}</Text>
</TouchableOpacity>
</SafeAreaView>
<TouchableOpacity>
{stream && (
<ActionSheet
visible={showActionSheet}
options={actionItemOptions()}
cancelButtonIndex={ios ? 0 : undefined}
actionItemOnPress={actionItemOnPress}
onClose={() => {
setShowActionSheet(false);
}}
style={!ios && styles.androidModalContainer}
/>
)}
</TouchableOpacity>
</>
);
}
const useStyles = makeStyles(({ colors, spacing }) => ({
container: {
flex: 1,
backgroundColor: colors.background,
},
scrollViewContainer: {
backgroundColor: colors.backgroundDarker,
},
lowerContainer: {
paddingHorizontal: spacing.xxl,
backgroundColor: colors.backgroundDarker,
},
inputComment: {
justifyContent: 'flex-end',
alignItems: 'center',
color: colors.textLighter,
borderWidth: 1,
borderColor: colors.border,
marginTop: spacing.s,
marginBottom: spacing.xxl,
backgroundColor: colors.backgroundDarker,
borderRadius: 4,
padding: spacing.m,
},
inputCommentContainer: {
backgroundColor: colors.background,
paddingTop: spacing.l,
marginHorizontal: spacing.xxl,
},
androidModalContainer: {
paddingHorizontal: spacing.xxxl,
},
})); | the_stack |
* lowfer API
* lowfer API documentation
*
* The version of the OpenAPI document: 0.0.1
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import * as globalImportUrl from 'url';
import { Configuration } from './configuration';
import globalAxios, { AxiosPromise, AxiosInstance } from 'axios';
// Some imports not used depending on template conditions
// @ts-ignore
import {
BASE_PATH,
COLLECTION_FORMATS,
RequestArgs,
BaseAPI,
RequiredError
} from './base';
/**
*
* @export
* @interface ArchitectureListItemView
*/
export interface ArchitectureListItemView {
/**
*
* @type {string}
* @memberof ArchitectureListItemView
*/
name?: string;
}
/**
*
* @export
* @interface ArchitectureListView
*/
export interface ArchitectureListView {
/**
*
* @type {Array<ArchitectureListItemView>}
* @memberof ArchitectureListView
*/
architectures?: Array<ArchitectureListItemView>;
}
/**
*
* @export
* @interface ComponentListItemView
*/
export interface ComponentListItemView {
/**
*
* @type {string}
* @memberof ComponentListItemView
*/
name?: string;
}
/**
*
* @export
* @interface ComponentListView
*/
export interface ComponentListView {
/**
*
* @type {Array<ComponentListItemView>}
* @memberof ComponentListView
*/
components?: Array<ComponentListItemView>;
}
/**
*
* @export
* @interface ComponentTypeListItemView
*/
export interface ComponentTypeListItemView {
/**
*
* @type {string}
* @memberof ComponentTypeListItemView
*/
label?: string;
/**
*
* @type {string}
* @memberof ComponentTypeListItemView
*/
name?: string;
}
/**
*
* @export
* @interface ComponentTypeListView
*/
export interface ComponentTypeListView {
/**
*
* @type {Array<ComponentTypeListItemView>}
* @memberof ComponentTypeListView
*/
componentTypes?: Array<ComponentTypeListItemView>;
}
/**
*
* @export
* @interface EncodedArchitectureView
*/
export interface EncodedArchitectureView {
/**
*
* @type {string}
* @memberof EncodedArchitectureView
*/
encoded?: string;
/**
*
* @type {string}
* @memberof EncodedArchitectureView
*/
error?: string;
}
/**
*
* @export
* @interface GraphvizView
*/
export interface GraphvizView {
/**
*
* @type {string}
* @memberof GraphvizView
*/
dot?: string;
}
/**
*
* @export
* @interface IssueView
*/
export interface IssueView {
/**
*
* @type {string}
* @memberof IssueView
*/
description?: string;
/**
*
* @type {EncodedArchitectureView}
* @memberof IssueView
*/
encodedArchitecture?: EncodedArchitectureView;
/**
*
* @type {RuleView}
* @memberof IssueView
*/
rule?: RuleView;
/**
*
* @type {string}
* @memberof IssueView
*/
severity?: IssueViewSeverityEnum;
/**
*
* @type {string}
* @memberof IssueView
*/
summary?: string;
/**
*
* @type {string}
* @memberof IssueView
*/
type?: IssueViewTypeEnum;
}
/**
* @export
* @enum {string}
*/
export enum IssueViewSeverityEnum {
CRITICAL = 'CRITICAL',
MAJOR = 'MAJOR',
MINOR = 'MINOR'
}
/**
* @export
* @enum {string}
*/
export enum IssueViewTypeEnum {
MAINTENANCE = 'MAINTENANCE',
SCALING = 'SCALING',
SECURITY = 'SECURITY'
}
/**
*
* @export
* @interface JWTToken
*/
export interface JWTToken {
/**
*
* @type {string}
* @memberof JWTToken
*/
idToken?: string;
}
/**
*
* @export
* @interface LoginVM
*/
export interface LoginVM {
/**
*
* @type {string}
* @memberof LoginVM
*/
password: string;
/**
*
* @type {boolean}
* @memberof LoginVM
*/
rememberMe?: boolean;
/**
*
* @type {string}
* @memberof LoginVM
*/
username: string;
}
/**
*
* @export
* @interface MaintainerListItemView
*/
export interface MaintainerListItemView {
/**
*
* @type {string}
* @memberof MaintainerListItemView
*/
name?: string;
}
/**
*
* @export
* @interface MaintainerListView
*/
export interface MaintainerListView {
/**
*
* @type {Array<MaintainerListItemView>}
* @memberof MaintainerListView
*/
maintainers?: Array<MaintainerListItemView>;
}
/**
*
* @export
* @interface RuleView
*/
export interface RuleView {
/**
*
* @type {string}
* @memberof RuleView
*/
label?: string;
/**
*
* @type {string}
* @memberof RuleView
*/
name?: string;
}
/**
*
* @export
* @interface UserVM
*/
export interface UserVM {
/**
*
* @type {boolean}
* @memberof UserVM
*/
activated?: boolean;
/**
*
* @type {Array<string>}
* @memberof UserVM
*/
authorities?: Array<string>;
/**
*
* @type {string}
* @memberof UserVM
*/
login?: string;
}
/**
* AccountResourceApi - axios parameter creator
* @export
*/
export const AccountResourceApiAxiosParamCreator = function (
configuration?: Configuration
) {
return {
/**
*
* @summary getAccount
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getAccountUsingGET(options: any = {}): RequestArgs {
const localVarPath = `/api/account`;
const localVarUrlObj = globalImportUrl.parse(localVarPath, true);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = {
method: 'GET',
...baseOptions,
...options
};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarUrlObj.query = {
...localVarUrlObj.query,
...localVarQueryParameter,
...options.query
};
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = {
...localVarHeaderParameter,
...options.headers
};
return {
url: globalImportUrl.format(localVarUrlObj),
options: localVarRequestOptions
};
}
};
};
/**
* AccountResourceApi - functional programming interface
* @export
*/
export const AccountResourceApiFp = function (configuration?: Configuration) {
return {
/**
*
* @summary getAccount
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getAccountUsingGET(
options?: any
): (axios?: AxiosInstance, basePath?: string) => AxiosPromise<UserVM> {
const localVarAxiosArgs = AccountResourceApiAxiosParamCreator(
configuration
).getAccountUsingGET(options);
return (
axios: AxiosInstance = globalAxios,
basePath: string = BASE_PATH
) => {
const axiosRequestArgs = {
...localVarAxiosArgs.options,
url: basePath + localVarAxiosArgs.url
};
return axios.request(axiosRequestArgs);
};
}
};
};
/**
* AccountResourceApi - factory interface
* @export
*/
export const AccountResourceApiFactory = function (
configuration?: Configuration,
basePath?: string,
axios?: AxiosInstance
) {
return {
/**
*
* @summary getAccount
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getAccountUsingGET(options?: any) {
return AccountResourceApiFp(configuration).getAccountUsingGET(options)(
axios,
basePath
);
}
};
};
/**
* AccountResourceApi - object-oriented interface
* @export
* @class AccountResourceApi
* @extends {BaseAPI}
*/
export class AccountResourceApi extends BaseAPI {
/**
*
* @summary getAccount
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AccountResourceApi
*/
public getAccountUsingGET(options?: any) {
return AccountResourceApiFp(this.configuration).getAccountUsingGET(options)(
this.axios,
this.basePath
);
}
}
/**
* ArchitectureResourceApi - axios parameter creator
* @export
*/
export const ArchitectureResourceApiAxiosParamCreator = function (
configuration?: Configuration
) {
return {
/**
*
* @summary downloadGraphviz
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {'TOP_TO_BOTTOM' | 'BOTTOM_TO_TOP' | 'LEFT_TO_RIGHT' | 'RIGHT_TO_LEFT'} [direction] direction
* @param {boolean} [hideAggregates] hide-aggregates
* @param {boolean} [internalOnly] internal-only
* @param {string} [maintainer] maintainer
* @param {string} [style] style
* @param {'DEPENDENCIES' | 'DATA_FLOW'} [type] type
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
downloadGraphvizUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
direction?:
| 'TOP_TO_BOTTOM'
| 'BOTTOM_TO_TOP'
| 'LEFT_TO_RIGHT'
| 'RIGHT_TO_LEFT',
hideAggregates?: boolean,
internalOnly?: boolean,
maintainer?: string,
style?: string,
type?: 'DEPENDENCIES' | 'DATA_FLOW',
options: any = {}
): RequestArgs {
const localVarPath = `/api/graphviz`;
const localVarUrlObj = globalImportUrl.parse(localVarPath, true);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = {
method: 'GET',
...baseOptions,
...options
};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
if (architectureEncoded !== undefined) {
localVarQueryParameter['architecture-encoded'] = architectureEncoded;
}
if (architectureName !== undefined) {
localVarQueryParameter['architecture-name'] = architectureName;
}
if (componentName !== undefined) {
localVarQueryParameter['component-name'] = componentName;
}
if (componentType !== undefined) {
localVarQueryParameter['component-type'] = componentType;
}
if (direction !== undefined) {
localVarQueryParameter['direction'] = direction;
}
if (hideAggregates !== undefined) {
localVarQueryParameter['hide-aggregates'] = hideAggregates;
}
if (internalOnly !== undefined) {
localVarQueryParameter['internal-only'] = internalOnly;
}
if (maintainer !== undefined) {
localVarQueryParameter['maintainer'] = maintainer;
}
if (style !== undefined) {
localVarQueryParameter['style'] = style;
}
if (type !== undefined) {
localVarQueryParameter['type'] = type;
}
localVarUrlObj.query = {
...localVarUrlObj.query,
...localVarQueryParameter,
...options.query
};
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = {
...localVarHeaderParameter,
...options.headers
};
return {
url: globalImportUrl.format(localVarUrlObj),
options: localVarRequestOptions
};
},
/**
*
* @summary getArchitectures
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getArchitecturesUsingGET(options: any = {}): RequestArgs {
const localVarPath = `/api/architectures`;
const localVarUrlObj = globalImportUrl.parse(localVarPath, true);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = {
method: 'GET',
...baseOptions,
...options
};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarUrlObj.query = {
...localVarUrlObj.query,
...localVarQueryParameter,
...options.query
};
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = {
...localVarHeaderParameter,
...options.headers
};
return {
url: globalImportUrl.format(localVarUrlObj),
options: localVarRequestOptions
};
},
/**
*
* @summary getComponentTypes
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {string} [maintainer] maintainer
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getComponentTypesUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
maintainer?: string,
options: any = {}
): RequestArgs {
const localVarPath = `/api/component-types`;
const localVarUrlObj = globalImportUrl.parse(localVarPath, true);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = {
method: 'GET',
...baseOptions,
...options
};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
if (architectureEncoded !== undefined) {
localVarQueryParameter['architecture-encoded'] = architectureEncoded;
}
if (architectureName !== undefined) {
localVarQueryParameter['architecture-name'] = architectureName;
}
if (componentName !== undefined) {
localVarQueryParameter['component-name'] = componentName;
}
if (componentType !== undefined) {
localVarQueryParameter['component-type'] = componentType;
}
if (maintainer !== undefined) {
localVarQueryParameter['maintainer'] = maintainer;
}
localVarUrlObj.query = {
...localVarUrlObj.query,
...localVarQueryParameter,
...options.query
};
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = {
...localVarHeaderParameter,
...options.headers
};
return {
url: globalImportUrl.format(localVarUrlObj),
options: localVarRequestOptions
};
},
/**
*
* @summary getComponents
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {string} [maintainer] maintainer
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getComponentsUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
maintainer?: string,
options: any = {}
): RequestArgs {
const localVarPath = `/api/components`;
const localVarUrlObj = globalImportUrl.parse(localVarPath, true);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = {
method: 'GET',
...baseOptions,
...options
};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
if (architectureEncoded !== undefined) {
localVarQueryParameter['architecture-encoded'] = architectureEncoded;
}
if (architectureName !== undefined) {
localVarQueryParameter['architecture-name'] = architectureName;
}
if (componentName !== undefined) {
localVarQueryParameter['component-name'] = componentName;
}
if (componentType !== undefined) {
localVarQueryParameter['component-type'] = componentType;
}
if (maintainer !== undefined) {
localVarQueryParameter['maintainer'] = maintainer;
}
localVarUrlObj.query = {
...localVarUrlObj.query,
...localVarQueryParameter,
...options.query
};
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = {
...localVarHeaderParameter,
...options.headers
};
return {
url: globalImportUrl.format(localVarUrlObj),
options: localVarRequestOptions
};
},
/**
*
* @summary getIssues
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {string} [maintainer] maintainer
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getIssuesUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
maintainer?: string,
options: any = {}
): RequestArgs {
const localVarPath = `/api/issues`;
const localVarUrlObj = globalImportUrl.parse(localVarPath, true);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = {
method: 'GET',
...baseOptions,
...options
};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
if (architectureEncoded !== undefined) {
localVarQueryParameter['architecture-encoded'] = architectureEncoded;
}
if (architectureName !== undefined) {
localVarQueryParameter['architecture-name'] = architectureName;
}
if (componentName !== undefined) {
localVarQueryParameter['component-name'] = componentName;
}
if (componentType !== undefined) {
localVarQueryParameter['component-type'] = componentType;
}
if (maintainer !== undefined) {
localVarQueryParameter['maintainer'] = maintainer;
}
localVarUrlObj.query = {
...localVarUrlObj.query,
...localVarQueryParameter,
...options.query
};
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = {
...localVarHeaderParameter,
...options.headers
};
return {
url: globalImportUrl.format(localVarUrlObj),
options: localVarRequestOptions
};
},
/**
*
* @summary getMaintainers
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {string} [maintainer] maintainer
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getMaintainersUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
maintainer?: string,
options: any = {}
): RequestArgs {
const localVarPath = `/api/maintainers`;
const localVarUrlObj = globalImportUrl.parse(localVarPath, true);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = {
method: 'GET',
...baseOptions,
...options
};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
if (architectureEncoded !== undefined) {
localVarQueryParameter['architecture-encoded'] = architectureEncoded;
}
if (architectureName !== undefined) {
localVarQueryParameter['architecture-name'] = architectureName;
}
if (componentName !== undefined) {
localVarQueryParameter['component-name'] = componentName;
}
if (componentType !== undefined) {
localVarQueryParameter['component-type'] = componentType;
}
if (maintainer !== undefined) {
localVarQueryParameter['maintainer'] = maintainer;
}
localVarUrlObj.query = {
...localVarUrlObj.query,
...localVarQueryParameter,
...options.query
};
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = {
...localVarHeaderParameter,
...options.headers
};
return {
url: globalImportUrl.format(localVarUrlObj),
options: localVarRequestOptions
};
}
};
};
/**
* ArchitectureResourceApi - functional programming interface
* @export
*/
export const ArchitectureResourceApiFp = function (
configuration?: Configuration
) {
return {
/**
*
* @summary downloadGraphviz
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {'TOP_TO_BOTTOM' | 'BOTTOM_TO_TOP' | 'LEFT_TO_RIGHT' | 'RIGHT_TO_LEFT'} [direction] direction
* @param {boolean} [hideAggregates] hide-aggregates
* @param {boolean} [internalOnly] internal-only
* @param {string} [maintainer] maintainer
* @param {string} [style] style
* @param {'DEPENDENCIES' | 'DATA_FLOW'} [type] type
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
downloadGraphvizUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
direction?:
| 'TOP_TO_BOTTOM'
| 'BOTTOM_TO_TOP'
| 'LEFT_TO_RIGHT'
| 'RIGHT_TO_LEFT',
hideAggregates?: boolean,
internalOnly?: boolean,
maintainer?: string,
style?: string,
type?: 'DEPENDENCIES' | 'DATA_FLOW',
options?: any
): (
axios?: AxiosInstance,
basePath?: string
) => AxiosPromise<GraphvizView> {
const localVarAxiosArgs = ArchitectureResourceApiAxiosParamCreator(
configuration
).downloadGraphvizUsingGET(
architectureEncoded,
architectureName,
componentName,
componentType,
direction,
hideAggregates,
internalOnly,
maintainer,
style,
type,
options
);
return (
axios: AxiosInstance = globalAxios,
basePath: string = BASE_PATH
) => {
const axiosRequestArgs = {
...localVarAxiosArgs.options,
url: basePath + localVarAxiosArgs.url
};
return axios.request(axiosRequestArgs);
};
},
/**
*
* @summary getArchitectures
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getArchitecturesUsingGET(
options?: any
): (
axios?: AxiosInstance,
basePath?: string
) => AxiosPromise<ArchitectureListView> {
const localVarAxiosArgs = ArchitectureResourceApiAxiosParamCreator(
configuration
).getArchitecturesUsingGET(options);
return (
axios: AxiosInstance = globalAxios,
basePath: string = BASE_PATH
) => {
const axiosRequestArgs = {
...localVarAxiosArgs.options,
url: basePath + localVarAxiosArgs.url
};
return axios.request(axiosRequestArgs);
};
},
/**
*
* @summary getComponentTypes
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {string} [maintainer] maintainer
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getComponentTypesUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
maintainer?: string,
options?: any
): (
axios?: AxiosInstance,
basePath?: string
) => AxiosPromise<ComponentTypeListView> {
const localVarAxiosArgs = ArchitectureResourceApiAxiosParamCreator(
configuration
).getComponentTypesUsingGET(
architectureEncoded,
architectureName,
componentName,
componentType,
maintainer,
options
);
return (
axios: AxiosInstance = globalAxios,
basePath: string = BASE_PATH
) => {
const axiosRequestArgs = {
...localVarAxiosArgs.options,
url: basePath + localVarAxiosArgs.url
};
return axios.request(axiosRequestArgs);
};
},
/**
*
* @summary getComponents
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {string} [maintainer] maintainer
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getComponentsUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
maintainer?: string,
options?: any
): (
axios?: AxiosInstance,
basePath?: string
) => AxiosPromise<ComponentListView> {
const localVarAxiosArgs = ArchitectureResourceApiAxiosParamCreator(
configuration
).getComponentsUsingGET(
architectureEncoded,
architectureName,
componentName,
componentType,
maintainer,
options
);
return (
axios: AxiosInstance = globalAxios,
basePath: string = BASE_PATH
) => {
const axiosRequestArgs = {
...localVarAxiosArgs.options,
url: basePath + localVarAxiosArgs.url
};
return axios.request(axiosRequestArgs);
};
},
/**
*
* @summary getIssues
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {string} [maintainer] maintainer
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getIssuesUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
maintainer?: string,
options?: any
): (
axios?: AxiosInstance,
basePath?: string
) => AxiosPromise<Array<IssueView>> {
const localVarAxiosArgs = ArchitectureResourceApiAxiosParamCreator(
configuration
).getIssuesUsingGET(
architectureEncoded,
architectureName,
componentName,
componentType,
maintainer,
options
);
return (
axios: AxiosInstance = globalAxios,
basePath: string = BASE_PATH
) => {
const axiosRequestArgs = {
...localVarAxiosArgs.options,
url: basePath + localVarAxiosArgs.url
};
return axios.request(axiosRequestArgs);
};
},
/**
*
* @summary getMaintainers
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {string} [maintainer] maintainer
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getMaintainersUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
maintainer?: string,
options?: any
): (
axios?: AxiosInstance,
basePath?: string
) => AxiosPromise<MaintainerListView> {
const localVarAxiosArgs = ArchitectureResourceApiAxiosParamCreator(
configuration
).getMaintainersUsingGET(
architectureEncoded,
architectureName,
componentName,
componentType,
maintainer,
options
);
return (
axios: AxiosInstance = globalAxios,
basePath: string = BASE_PATH
) => {
const axiosRequestArgs = {
...localVarAxiosArgs.options,
url: basePath + localVarAxiosArgs.url
};
return axios.request(axiosRequestArgs);
};
}
};
};
/**
* ArchitectureResourceApi - factory interface
* @export
*/
export const ArchitectureResourceApiFactory = function (
configuration?: Configuration,
basePath?: string,
axios?: AxiosInstance
) {
return {
/**
*
* @summary downloadGraphviz
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {'TOP_TO_BOTTOM' | 'BOTTOM_TO_TOP' | 'LEFT_TO_RIGHT' | 'RIGHT_TO_LEFT'} [direction] direction
* @param {boolean} [hideAggregates] hide-aggregates
* @param {boolean} [internalOnly] internal-only
* @param {string} [maintainer] maintainer
* @param {string} [style] style
* @param {'DEPENDENCIES' | 'DATA_FLOW'} [type] type
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
downloadGraphvizUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
direction?:
| 'TOP_TO_BOTTOM'
| 'BOTTOM_TO_TOP'
| 'LEFT_TO_RIGHT'
| 'RIGHT_TO_LEFT',
hideAggregates?: boolean,
internalOnly?: boolean,
maintainer?: string,
style?: string,
type?: 'DEPENDENCIES' | 'DATA_FLOW',
options?: any
) {
return ArchitectureResourceApiFp(configuration).downloadGraphvizUsingGET(
architectureEncoded,
architectureName,
componentName,
componentType,
direction,
hideAggregates,
internalOnly,
maintainer,
style,
type,
options
)(axios, basePath);
},
/**
*
* @summary getArchitectures
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getArchitecturesUsingGET(options?: any) {
return ArchitectureResourceApiFp(configuration).getArchitecturesUsingGET(
options
)(axios, basePath);
},
/**
*
* @summary getComponentTypes
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {string} [maintainer] maintainer
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getComponentTypesUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
maintainer?: string,
options?: any
) {
return ArchitectureResourceApiFp(configuration).getComponentTypesUsingGET(
architectureEncoded,
architectureName,
componentName,
componentType,
maintainer,
options
)(axios, basePath);
},
/**
*
* @summary getComponents
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {string} [maintainer] maintainer
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getComponentsUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
maintainer?: string,
options?: any
) {
return ArchitectureResourceApiFp(configuration).getComponentsUsingGET(
architectureEncoded,
architectureName,
componentName,
componentType,
maintainer,
options
)(axios, basePath);
},
/**
*
* @summary getIssues
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {string} [maintainer] maintainer
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getIssuesUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
maintainer?: string,
options?: any
) {
return ArchitectureResourceApiFp(configuration).getIssuesUsingGET(
architectureEncoded,
architectureName,
componentName,
componentType,
maintainer,
options
)(axios, basePath);
},
/**
*
* @summary getMaintainers
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {string} [maintainer] maintainer
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getMaintainersUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
maintainer?: string,
options?: any
) {
return ArchitectureResourceApiFp(configuration).getMaintainersUsingGET(
architectureEncoded,
architectureName,
componentName,
componentType,
maintainer,
options
)(axios, basePath);
}
};
};
/**
* ArchitectureResourceApi - object-oriented interface
* @export
* @class ArchitectureResourceApi
* @extends {BaseAPI}
*/
export class ArchitectureResourceApi extends BaseAPI {
/**
*
* @summary downloadGraphviz
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {'TOP_TO_BOTTOM' | 'BOTTOM_TO_TOP' | 'LEFT_TO_RIGHT' | 'RIGHT_TO_LEFT'} [direction] direction
* @param {boolean} [hideAggregates] hide-aggregates
* @param {boolean} [internalOnly] internal-only
* @param {string} [maintainer] maintainer
* @param {string} [style] style
* @param {'DEPENDENCIES' | 'DATA_FLOW'} [type] type
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ArchitectureResourceApi
*/
public downloadGraphvizUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
direction?:
| 'TOP_TO_BOTTOM'
| 'BOTTOM_TO_TOP'
| 'LEFT_TO_RIGHT'
| 'RIGHT_TO_LEFT',
hideAggregates?: boolean,
internalOnly?: boolean,
maintainer?: string,
style?: string,
type?: 'DEPENDENCIES' | 'DATA_FLOW',
options?: any
) {
return ArchitectureResourceApiFp(
this.configuration
).downloadGraphvizUsingGET(
architectureEncoded,
architectureName,
componentName,
componentType,
direction,
hideAggregates,
internalOnly,
maintainer,
style,
type,
options
)(this.axios, this.basePath);
}
/**
*
* @summary getArchitectures
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ArchitectureResourceApi
*/
public getArchitecturesUsingGET(options?: any) {
return ArchitectureResourceApiFp(
this.configuration
).getArchitecturesUsingGET(options)(this.axios, this.basePath);
}
/**
*
* @summary getComponentTypes
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {string} [maintainer] maintainer
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ArchitectureResourceApi
*/
public getComponentTypesUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
maintainer?: string,
options?: any
) {
return ArchitectureResourceApiFp(
this.configuration
).getComponentTypesUsingGET(
architectureEncoded,
architectureName,
componentName,
componentType,
maintainer,
options
)(this.axios, this.basePath);
}
/**
*
* @summary getComponents
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {string} [maintainer] maintainer
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ArchitectureResourceApi
*/
public getComponentsUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
maintainer?: string,
options?: any
) {
return ArchitectureResourceApiFp(this.configuration).getComponentsUsingGET(
architectureEncoded,
architectureName,
componentName,
componentType,
maintainer,
options
)(this.axios, this.basePath);
}
/**
*
* @summary getIssues
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {string} [maintainer] maintainer
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ArchitectureResourceApi
*/
public getIssuesUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
maintainer?: string,
options?: any
) {
return ArchitectureResourceApiFp(this.configuration).getIssuesUsingGET(
architectureEncoded,
architectureName,
componentName,
componentType,
maintainer,
options
)(this.axios, this.basePath);
}
/**
*
* @summary getMaintainers
* @param {string} [architectureEncoded] architecture-encoded
* @param {string} [architectureName] architecture-name
* @param {string} [componentName] component-name
* @param {string} [componentType] component-type
* @param {string} [maintainer] maintainer
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ArchitectureResourceApi
*/
public getMaintainersUsingGET(
architectureEncoded?: string,
architectureName?: string,
componentName?: string,
componentType?: string,
maintainer?: string,
options?: any
) {
return ArchitectureResourceApiFp(this.configuration).getMaintainersUsingGET(
architectureEncoded,
architectureName,
componentName,
componentType,
maintainer,
options
)(this.axios, this.basePath);
}
}
/**
* UserJwtControllerApi - axios parameter creator
* @export
*/
export const UserJwtControllerApiAxiosParamCreator = function (
configuration?: Configuration
) {
return {
/**
*
* @summary authorize
* @param {LoginVM} loginVM loginVM
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
authorizeUsingPOST(loginVM: LoginVM, options: any = {}): RequestArgs {
// verify required parameter 'loginVM' is not null or undefined
if (loginVM === null || loginVM === undefined) {
throw new RequiredError(
'loginVM',
'Required parameter loginVM was null or undefined when calling authorizeUsingPOST.'
);
}
const localVarPath = `/api/authenticate`;
const localVarUrlObj = globalImportUrl.parse(localVarPath, true);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = {
method: 'POST',
...baseOptions,
...options
};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
localVarUrlObj.query = {
...localVarUrlObj.query,
...localVarQueryParameter,
...options.query
};
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = {
...localVarHeaderParameter,
...options.headers
};
const needsSerialization =
<any>'LoginVM' !== 'string' ||
localVarRequestOptions.headers['Content-Type'] === 'application/json';
localVarRequestOptions.data = needsSerialization
? JSON.stringify(loginVM !== undefined ? loginVM : {})
: loginVM || '';
return {
url: globalImportUrl.format(localVarUrlObj),
options: localVarRequestOptions
};
}
};
};
/**
* UserJwtControllerApi - functional programming interface
* @export
*/
export const UserJwtControllerApiFp = function (configuration?: Configuration) {
return {
/**
*
* @summary authorize
* @param {LoginVM} loginVM loginVM
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
authorizeUsingPOST(
loginVM: LoginVM,
options?: any
): (axios?: AxiosInstance, basePath?: string) => AxiosPromise<JWTToken> {
const localVarAxiosArgs = UserJwtControllerApiAxiosParamCreator(
configuration
).authorizeUsingPOST(loginVM, options);
return (
axios: AxiosInstance = globalAxios,
basePath: string = BASE_PATH
) => {
const axiosRequestArgs = {
...localVarAxiosArgs.options,
url: basePath + localVarAxiosArgs.url
};
return axios.request(axiosRequestArgs);
};
}
};
};
/**
* UserJwtControllerApi - factory interface
* @export
*/
export const UserJwtControllerApiFactory = function (
configuration?: Configuration,
basePath?: string,
axios?: AxiosInstance
) {
return {
/**
*
* @summary authorize
* @param {LoginVM} loginVM loginVM
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
authorizeUsingPOST(loginVM: LoginVM, options?: any) {
return UserJwtControllerApiFp(configuration).authorizeUsingPOST(
loginVM,
options
)(axios, basePath);
}
};
};
/**
* UserJwtControllerApi - object-oriented interface
* @export
* @class UserJwtControllerApi
* @extends {BaseAPI}
*/
export class UserJwtControllerApi extends BaseAPI {
/**
*
* @summary authorize
* @param {LoginVM} loginVM loginVM
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserJwtControllerApi
*/
public authorizeUsingPOST(loginVM: LoginVM, options?: any) {
return UserJwtControllerApiFp(this.configuration).authorizeUsingPOST(
loginVM,
options
)(this.axios, this.basePath);
}
} | the_stack |
import * as React from 'react';
import styles from './PageTransformatorAdmin.module.scss';
import { IPageTransformatorAdminProps, IPageTransformatorAdminState } from './IPageTransformatorAdminProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { sp, Site } from '@pnp/sp';
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { DefaultButton, PrimaryButton, MessageBarButton } from 'office-ui-fabric-react/lib/Button';
import { MessageBar, MessageBarType } from 'office-ui-fabric-react/lib/MessageBar';
import { UserCustomAction } from '@pnp/sp/src/usercustomactions';
export default class PageTransformatorAdmin extends React.Component<IPageTransformatorAdminProps, IPageTransformatorAdminState> {
private SITEPAGESFEATUREID: string = 'B6917CB1-93A0-4B97-A84D-7CF49975D4EC';
private CAPNPMODERNIZESITEPAGESECB: string = "CA_PnP_Modernize_SitePages_ECB";
private CAPNPMODERNIZESITEPAGES: string = "CA_PnP_Modernize_SitePages_RIBBON";
private CAPNPMODERNIZEWIKIPAGE: string = "CA_PnP_Modernize_WikiPage_RIBBON";
private CAPPNPMODERNIZEWEBPARTPAGE: string = "CA_PnP_Modernize_WebPartPage_RIBBON";
private CAPNPCLASSICPAGEBANNER: string = "CA_PnP_Modernize_ClassicBanner";
constructor(props: IPageTransformatorAdminProps, state: IPageTransformatorAdminState) {
super(props);
this.state = {
siteUrl: "",
buttonsDisabled: true,
resultMessage: null,
resultMessageType: MessageBarType.info
};
sp.setup({
spfxContext: this.props.context,
});
this.onSiteUrlChange = this.onSiteUrlChange.bind(this);
}
private enableClick = (): void => {
const centerUrl = this.props.context.pageContext.site.serverRelativeUrl;
let site = new Site(this.getTenantUrl() + this.state.siteUrl);
const sitePageLibraryCA: any = {
Description: "Create a modern version of this page.",
Name: this.CAPNPMODERNIZESITEPAGESECB,
Location: "EditControlBlock",
RegistrationType: 1,
RegistrationId: "119",
Rights: { High: "0", Low: "4" },
Title: "Create modern version",
Url: `${centerUrl}/SitePages/modernize.aspx?SiteUrl=/${this.state.siteUrl}&ListId={ListId}&ItemId={ItemId}`
};
// Wiki Page library user custom actions
const wikiPageLibraryCA: any = {
Description: "Create a modern version of this page.",
Name: this.CAPNPMODERNIZESITEPAGES,
Location: "CommandUI.Ribbon",
RegistrationType: 1,
RegistrationId: "119",
Rights: { High: "0", Low: "4" },
Title: "Create modern version",
CommandUIExtension: `<CommandUIExtension><CommandUIDefinitions>
<CommandUIDefinition Location="Ribbon.Documents.Copies.Controls._children">
<Button
Id="Ribbon.Documents.Copies.ModernizePage"
Command="SharePointPnP.Cmd.ModernizePage"
Image16by16="${centerUrl}/siteassets/modernize16x16.png"
Image32by32="${centerUrl}/siteassets/modernize32x32.png"
LabelText="Create modern version"
Description="Create a modern version of this page."
ToolTipTitle="Create modern version"
ToolTipDescription="Create a modern version of this page."
TemplateAlias="o1"
Sequence="15"/>
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command="SharePointPnP.Cmd.ModernizePage"
CommandAction="${centerUrl}/SitePages/modernize.aspx?SiteUrl=/${this.state.siteUrl}&ListId={SelectedListId}&ItemId={SelectedItemId}"
EnabledScript="javascript:SP.ListOperation.Selection.getSelectedItems().length == 1;" />
</CommandUIHandlers></CommandUIExtension>`
};
// Wiki page ribbon user custom action
const wikiPageRibbonCA: any = {
Description: "Create a modern version of this page.",
Name: this.CAPNPMODERNIZEWIKIPAGE,
Location: "CommandUI.Ribbon",
Title: "Create modern version",
Rights: { High: "0", Low: "4" },
CommandUIExtension: `<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition Location="Ribbon.WikiPageTab.PageActions.Controls._children">
<Button
Id="Ribbon.WikiPageTab.PageActions.ModernizeWikiPage"
Command="SharePointPnP.Cmd.ModernizeWikiPage"
Image16by16="${centerUrl}/siteassets/modernize16x16.png"
Image32by32="${centerUrl}/siteassets/modernize32x32.png"
LabelText="Create modern version"
Description="Create a modern version of this page."
ToolTipTitle="Create modern version"
ToolTipDescription="Create a modern version of this page."
TemplateAlias="o1"
Sequence="1500"/>
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command="SharePointPnP.Cmd.ModernizeWikiPage"
CommandAction="javascript:function redirect(){ var url = '${centerUrl}/SitePages/modernize.aspx?SiteUrl=/${this.state.siteUrl}&ListId=' + _spPageContextInfo.listId + '&ItemId=' + _spPageContextInfo.pageItemId; window.location = url; } redirect();" />
</CommandUIHandlers>
</CommandUIExtension>`
};
// Web part page ribbon user custom action
const webpartPageRibbonCA: any = {
Description: "Create a modern version of this page.",
Name: this.CAPPNPMODERNIZEWEBPARTPAGE,
Location: "CommandUI.Ribbon",
Title: "Create modern version",
Rights: { High: "0", Low: "4" },
CommandUIExtension: `<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition Location="Ribbon.WebPartPage.Actions.Controls._children">
<Button
Id="Ribbon.WebPartPage.Actions.ModernizeWebPartPage"
Command="SharePointPnP.Cmd.ModernizeWebPartPage"
Image16by16="${centerUrl}/siteassets/modernize16x16.png"
Image32by32="${centerUrl}/siteassets/modernize32x32.png"
LabelText="Create modern version"
Description="Create a modern version of this page."
ToolTipTitle="Create modern version"
ToolTipDescription="Create a modern version of this page."
TemplateAlias="o1"
Sequence="1500"/>
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command="SharePointPnP.Cmd.ModernizeWebPartPage"
CommandAction="javascript:function redirect(){ var url = '${centerUrl}/SitePages/modernize.aspx?SiteUrl=/${this.state.siteUrl}&ListId=' + _spPageContextInfo.listId + '&ItemId=' + _spPageContextInfo.pageItemId; window.location = url; } redirect();" />
</CommandUIHandlers>
</CommandUIExtension>`
};
// Classic page banner user custom action
const classicPageBannerCA: any = {
Description: "Shows a banner on the classic pages.",
Name: this.CAPNPCLASSICPAGEBANNER,
Location: "ScriptLink",
//RegistrationType: 1,
Title: "Shows a banner on the classic pages",
ScriptSrc: `${this.getTenantUrl()}${centerUrl}/SiteAssets/pnppagetransformationclassicbanner.js?rev=beta.1`
};
Promise.all([
this.activateSitePagesFeatureIfNeeded(site),
this.addCustomActionIfNeeded(site, sitePageLibraryCA),
this.addCustomActionIfNeeded(site, wikiPageLibraryCA),
this.addCustomActionIfNeeded(site, wikiPageRibbonCA),
this.addCustomActionIfNeeded(site, webpartPageRibbonCA),
this.addCustomActionIfNeeded(site, classicPageBannerCA)
]).then(() => {
this.setState((current) => ({ ...current, resultMessage: "Modernization functionality added to site", resultMessageType: MessageBarType.success }));
}).catch(() => {
this.setState((current) => ({ ...current, resultMessage: "Unable to add mo0dernization functionality to site", resultMessageType: MessageBarType.error }));
});
}
private disableClick = (): void => {
const centerUrl = this.props.context.pageContext.site.serverRelativeUrl;
let site = new Site(this.getTenantUrl() + this.state.siteUrl);
Promise.all([
this.activateSitePagesFeatureIfNeeded(site),
this.removeCustomActionIfNeeded(site, this.CAPNPMODERNIZESITEPAGESECB),
this.removeCustomActionIfNeeded(site, this.CAPNPMODERNIZESITEPAGES),
this.removeCustomActionIfNeeded(site, this.CAPNPMODERNIZEWIKIPAGE),
this.removeCustomActionIfNeeded(site, this.CAPPNPMODERNIZEWEBPARTPAGE),
this.removeCustomActionIfNeeded(site, this.CAPNPCLASSICPAGEBANNER)
]).then(() => {
this.setState((current) => ({ ...current, resultMessage: "Modernization functionality removed from site", resultMessageType: MessageBarType.success }));
}).catch(() => {
this.setState((current) => ({ ...current, resultMessage: "Unable to remove modernization functionality from site", resultMessageType: MessageBarType.error }));
});
}
private activateSitePagesFeatureIfNeeded(site: Site): Promise<void> {
if (!site.rootWeb.features.getById(this.SITEPAGESFEATUREID)) {
site.rootWeb.features.add(this.SITEPAGESFEATUREID);
}
return new Promise<void>((resolve) => { resolve(); });
}
private addCustomActionIfNeeded(site: Site, customAction: any): Promise<void> {
return new Promise<void>((resolve) => {
site.userCustomActions.filter(`Name eq '${customAction.Name}'`).get().then((customActions: any[]) => {
if (customActions.length == 0) {
site.userCustomActions.add(customAction).then(_ => { resolve(); });
} else {
resolve();
}
});
});
}
private removeCustomActionIfNeeded(site: Site, name: string): Promise<void> {
return new Promise<void>((resolve) => {
site.userCustomActions.filter(`Name eq '${name}'`).get().then((customActions: any[]) => {
if (customActions.length == 1) {
site.userCustomActions.getById(customActions[0].Id).delete().then(_ => { resolve(); });
} else {
resolve();
}
});
resolve();
});
}
private getTenantUrl(): string {
const siteUrl = this.props.context.pageContext.site.absoluteUrl;
const slashPos = siteUrl.indexOf("/", 9);
if (slashPos > 0) {
return siteUrl.substring(0, slashPos) + "/";
} else {
return siteUrl + "/";
}
}
private onSiteUrlChange = (text: string): void => {
this.setState({ siteUrl: text, buttonsDisabled: this.state.siteUrl === "", resultMessage: null });
}
public render(): React.ReactElement<IPageTransformatorAdminProps> {
return (
<div className={styles.pageTransformatorAdmin}>
<span className="ms-font-xxl">Enable Site for Page Transformation</span>
<TextField label="Url of Site" prefix={this.getTenantUrl()} value={this.state.siteUrl} onChanged={this.onSiteUrlChange} />
<div className={styles.actions}>
<PrimaryButton text="Enable" onClick={this.enableClick} disabled={this.state.buttonsDisabled}></PrimaryButton>
<PrimaryButton text="Disable" onClick={this.disableClick} disabled={this.state.buttonsDisabled}></PrimaryButton>
</div>
<div className={styles.messages}>
{this.state.resultMessage != null && <MessageBar
messageBarType={this.state.resultMessageType}
isMultiline={false}
>{this.state.resultMessage}</MessageBar>}
</div>
</div >
);
}
} | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* The resource provider operation details.
*/
export interface ResourceProviderOperationDisplay {
/**
* Name of the resource provider.
*/
provider?: string;
/**
* Name of the resource type.
*/
resource?: string;
/**
* Name of the resource provider operation.
*/
operation?: string;
/**
* Description of the resource provider operation.
*/
description?: string;
}
/**
* The resource provider operation definition.
*/
export interface ResourceProviderOperationDefinition {
/**
* The resource provider operation name.
*/
name?: string;
display?: ResourceProviderOperationDisplay;
}
/**
* Data of a property change.
*/
export interface PropertyChange {
/**
* Possible values include: 'Add', 'Remove', 'Update'
*/
changeType?: ChangeType;
/**
* The change category. Possible values include: 'User', 'System'
*/
changeCategory?: ChangeCategory;
/**
* The json path of the changed property.
*/
jsonPath?: string;
/**
* The enhanced display name of the json path. E.g., the json path value[0].properties will be
* translated to something meaningful like slots["Staging"].properties.
*/
displayName?: string;
/**
* Possible values include: 'Noisy', 'Normal', 'Important'
*/
level?: Level;
/**
* The description of the changed property.
*/
description?: string;
/**
* The value of the property before the change.
*/
oldValue?: string;
/**
* The value of the property after the change.
*/
newValue?: string;
/**
* The boolean indicating whether the oldValue and newValue are masked. The values are masked if
* it contains sensitive information that the user doesn't have access to.
*/
isDataMasked?: boolean;
}
/**
* The properties of a change.
*/
export interface ChangeProperties {
/**
* The resource id that the change is attached to.
*/
resourceId?: string;
/**
* The time when the change is detected.
*/
timeStamp?: Date;
/**
* The list of identities who might initiated the change.
* The identity could be user name (email address) or the object ID of the Service Principal.
*/
initiatedByList?: string[];
/**
* Possible values include: 'Add', 'Remove', 'Update'
*/
changeType?: ChangeType;
/**
* The list of detailed changes at json property level.
*/
propertyChanges?: PropertyChange[];
}
/**
* Common fields that are returned in the response for all Azure Resource Manager resources
* @summary Resource
*/
export interface Resource extends BaseResource {
/**
* Fully qualified resource ID for the resource. Ex -
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The name of the resource
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
* "Microsoft.Storage/storageAccounts"
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* The resource model definition for a Azure Resource Manager proxy resource. It will not have tags
* and a location
* @summary Proxy Resource
*/
export interface ProxyResource extends Resource {
}
/**
* The detected change.
*/
export interface Change extends ProxyResource {
properties?: ChangeProperties;
}
/**
* The resource model definition for an Azure Resource Manager tracked top level resource which has
* 'tags' and a 'location'
* @summary Tracked Resource
*/
export interface TrackedResource extends Resource {
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
/**
* The geo-location where the resource lives
*/
location: string;
}
/**
* The resource model definition for an Azure Resource Manager resource with an etag.
* @summary Entity Resource
*/
export interface AzureEntityResource extends Resource {
/**
* Resource Etag.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly etag?: string;
}
/**
* The resource management error additional info.
*/
export interface ErrorAdditionalInfo {
/**
* The additional info type.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* The additional info.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly info?: any;
}
/**
* The error detail.
*/
export interface ErrorDetail {
/**
* The error code.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly code?: string;
/**
* The error message.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly message?: string;
/**
* The error target.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly target?: string;
/**
* The error details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly details?: ErrorDetail[];
/**
* The error additional info.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly additionalInfo?: ErrorAdditionalInfo[];
}
/**
* Common error response for all Azure Resource Manager APIs to return error details for failed
* operations. (This also follows the OData error response format.).
* @summary Error response
*/
export interface ErrorResponse {
/**
* The error object.
*/
error?: ErrorDetail;
}
/**
* Optional Parameters.
*/
export interface OperationsListOptionalParams extends msRest.RequestOptionsBase {
/**
* A skip token is used to continue retrieving items after an operation returns a partial result.
* If a previous response contains a nextLink element, the value of the nextLink element will
* include a skipToken parameter that specifies a starting point to use for subsequent calls.
*/
skipToken?: string;
}
/**
* Optional Parameters.
*/
export interface OperationsListNextOptionalParams extends msRest.RequestOptionsBase {
/**
* A skip token is used to continue retrieving items after an operation returns a partial result.
* If a previous response contains a nextLink element, the value of the nextLink element will
* include a skipToken parameter that specifies a starting point to use for subsequent calls.
*/
skipToken?: string;
}
/**
* Optional Parameters.
*/
export interface ResourceChangesListOptionalParams extends msRest.RequestOptionsBase {
/**
* A skip token is used to continue retrieving items after an operation returns a partial result.
* If a previous response contains a nextLink element, the value of the nextLink element will
* include a skipToken parameter that specifies a starting point to use for subsequent calls.
*/
skipToken?: string;
}
/**
* Optional Parameters.
*/
export interface ResourceChangesListNextOptionalParams extends msRest.RequestOptionsBase {
/**
* A skip token is used to continue retrieving items after an operation returns a partial result.
* If a previous response contains a nextLink element, the value of the nextLink element will
* include a skipToken parameter that specifies a starting point to use for subsequent calls.
*/
skipToken?: string;
}
/**
* Optional Parameters.
*/
export interface ChangesListChangesByResourceGroupOptionalParams extends msRest.RequestOptionsBase {
/**
* A skip token is used to continue retrieving items after an operation returns a partial result.
* If a previous response contains a nextLink element, the value of the nextLink element will
* include a skipToken parameter that specifies a starting point to use for subsequent calls.
*/
skipToken?: string;
}
/**
* Optional Parameters.
*/
export interface ChangesListChangesBySubscriptionOptionalParams extends msRest.RequestOptionsBase {
/**
* A skip token is used to continue retrieving items after an operation returns a partial result.
* If a previous response contains a nextLink element, the value of the nextLink element will
* include a skipToken parameter that specifies a starting point to use for subsequent calls.
*/
skipToken?: string;
}
/**
* Optional Parameters.
*/
export interface ChangesListChangesByResourceGroupNextOptionalParams extends msRest.RequestOptionsBase {
/**
* A skip token is used to continue retrieving items after an operation returns a partial result.
* If a previous response contains a nextLink element, the value of the nextLink element will
* include a skipToken parameter that specifies a starting point to use for subsequent calls.
*/
skipToken?: string;
}
/**
* Optional Parameters.
*/
export interface ChangesListChangesBySubscriptionNextOptionalParams extends msRest.RequestOptionsBase {
/**
* A skip token is used to continue retrieving items after an operation returns a partial result.
* If a previous response contains a nextLink element, the value of the nextLink element will
* include a skipToken parameter that specifies a starting point to use for subsequent calls.
*/
skipToken?: string;
}
/**
* An interface representing AzureChangeAnalysisManagementClientOptions.
*/
export interface AzureChangeAnalysisManagementClientOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* @interface
* The resource provider operation list.
* @extends Array<ResourceProviderOperationDefinition>
*/
export interface ResourceProviderOperationList extends Array<ResourceProviderOperationDefinition> {
/**
* The URI that can be used to request the next page for list of Azure operations.
*/
nextLink?: string;
}
/**
* @interface
* The list of detected changes.
* @extends Array<Change>
*/
export interface ChangeList extends Array<Change> {
/**
* The URI that can be used to request the next page of changes.
*/
nextLink?: string;
}
/**
* Defines values for ChangeType.
* Possible values include: 'Add', 'Remove', 'Update'
* @readonly
* @enum {string}
*/
export type ChangeType = 'Add' | 'Remove' | 'Update';
/**
* Defines values for Level.
* Possible values include: 'Noisy', 'Normal', 'Important'
* @readonly
* @enum {string}
*/
export type Level = 'Noisy' | 'Normal' | 'Important';
/**
* Defines values for ChangeCategory.
* Possible values include: 'User', 'System'
* @readonly
* @enum {string}
*/
export type ChangeCategory = 'User' | 'System';
/**
* Contains response data for the list operation.
*/
export type OperationsListResponse = ResourceProviderOperationList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ResourceProviderOperationList;
};
};
/**
* Contains response data for the listNext operation.
*/
export type OperationsListNextResponse = ResourceProviderOperationList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ResourceProviderOperationList;
};
};
/**
* Contains response data for the list operation.
*/
export type ResourceChangesListResponse = ChangeList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ChangeList;
};
};
/**
* Contains response data for the listNext operation.
*/
export type ResourceChangesListNextResponse = ChangeList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ChangeList;
};
};
/**
* Contains response data for the listChangesByResourceGroup operation.
*/
export type ChangesListChangesByResourceGroupResponse = ChangeList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ChangeList;
};
};
/**
* Contains response data for the listChangesBySubscription operation.
*/
export type ChangesListChangesBySubscriptionResponse = ChangeList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ChangeList;
};
};
/**
* Contains response data for the listChangesByResourceGroupNext operation.
*/
export type ChangesListChangesByResourceGroupNextResponse = ChangeList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ChangeList;
};
};
/**
* Contains response data for the listChangesBySubscriptionNext operation.
*/
export type ChangesListChangesBySubscriptionNextResponse = ChangeList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ChangeList;
};
}; | the_stack |
import {
addressBook,
ChallengeRegistry,
ConditionalTransactionCommitment,
SetStateCommitment,
CounterfactualApp,
} from "@connext/contracts";
import {
AppIdentity,
AppInstanceJson,
WatcherEvents,
IChannelSigner,
ILoggerService,
IWatcher,
IStoreService,
MinimalTransaction,
SignedCancelChallengeRequest,
StateChannelJSON,
WatcherEvent,
WatcherEventData,
WatcherInitOptions,
ChallengeUpdatedEventPayload,
StateProgressedEventPayload,
StoredAppChallenge,
SetStateCommitmentJSON,
StoredAppChallengeStatus,
ConditionalTransactionCommitmentJSON,
ChallengeInitiatedResponse,
ChallengeEvents,
ContractAddressBook,
IOnchainTransactionService,
} from "@connext/types";
import {
// ConsoleLogger,
ChannelSigner,
getSignerAddressFromPublicIdentifier,
nullLogger,
toBN,
stringify,
bigNumberifyJson,
delay,
} from "@connext/utils";
import { Contract, providers, constants, utils } from "ethers";
import { Evt } from "evt";
import { ChainListener } from "./chainListener";
const { Zero, HashZero } = constants;
const { Interface, defaultAbiCoder } = utils;
// Block of first challenge registry deployed to each chain
// testnets added to address-book at commit 8a868a48, mainnet at commit 097802b6
const FIRST_POSSIBLE_BLOCKS = {
"1": 8354797,
"3": 5693645,
"4": 4467523,
"42": 11231793,
};
/**
* Watchers will watch for contract events and respond to disputes on behalf
* of channel participants. They can also be used to initiate disputes.
*
* To use the watcher class, call `await Watcher.init(opts)`, this will
* automatically begin the dispute response process.
*/
type EvtContainer = {
[event in WatcherEvent]: Evt<WatcherEventData[WatcherEvent]>;
};
const jitter = async (maxDelay: number = 500): Promise<void> =>
delay(Math.floor(Math.random() * (maxDelay + 1)));
export class Watcher implements IWatcher {
private log: ILoggerService;
private readonly evts: EvtContainer;
private registries: { [chainId: number]: Contract };
public enabled: boolean = false;
// Use `await Watcher.init(opts)` instead of the constructor directly
private constructor(
private readonly signer: IChannelSigner,
private readonly providers: { [chainId: number]: providers.JsonRpcProvider },
private readonly context: ContractAddressBook,
private readonly store: IStoreService,
private readonly listener: ChainListener,
log: ILoggerService,
private readonly transactionService?: IOnchainTransactionService,
) {
this.log = log.newContext("Watcher");
const registries = {};
Object.entries(this.providers).forEach(([chainId, provider]) => {
registries[chainId] = new Contract(
this.context[chainId].ChallengeRegistry,
ChallengeRegistry.abi,
provider,
);
});
this.registries = registries;
// Create all evt instances for watcher events
const evts = {} as any;
Object.keys(WatcherEvents).forEach((event: string) => {
const typedIndex = event as WatcherEvent;
evts[event] = Evt.create<WatcherEventData[typeof typedIndex]>();
});
this.evts = evts;
}
/////////////////////////////////////
//// Static methods
// used to create a new watcher instance from the passed
// in options (which are cast to the proper values)
public static init = async (opts: WatcherInitOptions): Promise<Watcher> => {
const {
logger,
signer: providedSigner,
providers: givenProviders,
context,
store,
transactionService,
} = opts;
const log =
logger && typeof (logger as ILoggerService).newContext === "function"
? (logger as ILoggerService).newContext("WatcherInit")
: nullLogger;
log.debug(`Creating new Watcher`);
const chainProviders = {};
Object.entries(givenProviders).forEach(([chainId, p]) => {
chainProviders[chainId] =
typeof p === "string" ? new providers.JsonRpcProvider(p, chainId) : p;
});
const signer =
typeof providedSigner === "string" ? new ChannelSigner(providedSigner) : providedSigner;
const listener = new ChainListener(chainProviders, context, log);
const watcher = new Watcher(
signer,
chainProviders,
context,
store,
listener,
log,
transactionService,
);
await watcher.enable();
return watcher;
};
/////////////////////////////////////
//// Public methods
// will begin an onchain dispute. emits a `DisputeInitiated` event if
// the initiation was successful, otherwise emits a `DisputeFailed`
// event
public initiate = async (appInstanceId: string): Promise<ChallengeInitiatedResponse> => {
this.log.info(`Initiating challenge of ${appInstanceId}`);
const channel = await this.store.getStateChannelByAppIdentityHash(appInstanceId);
if (!channel || !channel.freeBalanceAppInstance) {
throw new Error(`Could not find channel with free balance for app ${appInstanceId}`);
}
const freeBalanceId = channel.freeBalanceAppInstance.identityHash;
this.log.info(`Initiating challenge for free balance ${freeBalanceId}`);
const freeBalanceChallenge = await this.startAppChallenge(freeBalanceId, channel.chainId);
this.log.debug(`Dispute of free balance started, tx: ${freeBalanceChallenge.hash}`);
const appChallenge = await this.startAppChallenge(appInstanceId, channel.chainId);
this.log.debug(`Dispute of app started, tx: ${appChallenge.hash}`);
return {
freeBalanceChallenge,
appChallenge,
};
};
public cancel = async (
appInstanceId: string,
req: SignedCancelChallengeRequest,
): Promise<providers.TransactionResponse> => {
this.log.info(
`Cancelling challenge for ${appInstanceId} at nonce ${toBN(req.versionNumber).toString()}`,
);
const channel = await this.store.getStateChannelByAppIdentityHash(appInstanceId);
const app = await this.store.getAppInstance(appInstanceId);
if (!app || !channel) {
throw new Error(`Could not find channel/app for app id: ${appInstanceId}`);
}
const response = await this.cancelChallenge(app, channel, req);
if (typeof response === "string") {
throw new Error(`Could not cancel challenge for ${appInstanceId}. ${response}`);
}
this.log.info(`Challenge cancelled with: ${response.hash}`);
return response;
};
// begins responding to events and starts all listeners
// also catches up to current block from latest processed
public enable = async (): Promise<void> => {
if (this.enabled) {
this.log.info(`Watcher is already enabled`);
return;
}
// catch up to current block
for (const chainId of Object.keys(this.providers)) {
const provider = this.providers[chainId];
const saved = await this.store.getLatestProcessedBlock();
const deployHash = addressBook[chainId]?.ChallengeRegistry?.txHash;
const deployTx = deployHash && await provider.getTransaction(deployHash);
const imported = deployTx?.block || 0;
const hardcoded = FIRST_POSSIBLE_BLOCKS[chainId] || 0;
// Use the latest block out of above options
const startFrom = [saved, imported, hardcoded].reduce((cur, acc) => cur > acc ? cur : acc, 0);
const current = await provider.getBlockNumber();
if (startFrom < current) {
this.log.info(`Processing missed events from blocks ${startFrom} - ${current}`);
// register any missed events
await this.catchupFrom(startFrom);
}
// register listener for any future events
this.log.debug(`Enabling listener`);
await this.listener.enable();
this.registerListeners();
}
this.enabled = true;
this.log.info(`Watcher enabled`);
};
// pauses all listeners and responses
public disable = async (): Promise<void> => {
if (!this.enabled) {
this.log.info(`Watcher is already disabled`);
return;
}
for (const chainId of Object.keys(this.providers)) {
const current = await this.providers[chainId].getBlockNumber();
this.log.info(`Setting latest processed block to ${current}`);
await this.store.updateLatestProcessedBlock(current);
}
this.log.debug(`Disabling listener`);
await this.listener.disable();
this.removeListeners();
this.off();
this.enabled = false;
this.log.info(`Watcher disabled`);
};
/////////////////////////////////////
//// Listener methods
public emit<T extends WatcherEvent>(event: T, data: WatcherEventData[T]): void {
this.evts[event].post(data);
}
public on<T extends WatcherEvent>(
event: T,
callback: (data: WatcherEventData[T]) => Promise<void>,
providedFilter?: (payload: WatcherEventData[T]) => boolean,
): void {
this.log.debug(`Registering callback for ${event}`);
const filter = (data: WatcherEventData[T]) => {
if (providedFilter) {
return providedFilter(data);
}
return true;
};
this.evts[event as any].attach(filter, callback);
}
public once<T extends WatcherEvent>(
event: T,
callback: (data: WatcherEventData[T]) => Promise<void>,
providedFilter?: (payload: WatcherEventData[T]) => boolean,
timeout?: number,
): void {
this.log.debug(`Registering callback for ${event}`);
const filter = (data: WatcherEventData[T]) => {
if (providedFilter) {
return providedFilter(data);
}
return true;
};
this.evts[event as any].attachOnce(filter, timeout || 60_000, callback);
}
public waitFor<T extends WatcherEvent>(
event: T,
timeout: number,
providedFilter?: (payload: WatcherEventData[T]) => boolean,
): Promise<WatcherEventData[T]> {
const filter = (data: WatcherEventData[T]) => {
if (providedFilter) {
return providedFilter(data);
}
return true;
};
return this.evts[event as any].waitFor(filter, timeout);
}
public off(): void {
Object.keys(this.evts).forEach((k) => {
this.evts[k].detach();
});
}
/////////////////////////////////////
//// Private methods
// will insert + respond to any events that have occurred from
// the latest processed block to the provided block
private catchupFrom = async (starting: number): Promise<void> => {
for (const chainId of Object.keys(this.providers)) {
this.log.info(`Processing events from ${starting} on ${chainId}`);
const current = await this.providers[chainId].getBlockNumber();
if (starting > current) {
throw new Error(
`Cannot process future blocks (current: ${current}, starting: ${starting})`,
);
}
// ensure events will not be processed twice
if (this.enabled) {
throw new Error(
`Cannot process past events while listener is still active, call 'disable', then 'enable'`,
);
}
// have listener process and emit all events from block --> now
this.registerListeners();
await this.listener.parseLogsFrom(starting);
await this.store.updateLatestProcessedBlock(current);
// cleanup any listeners
this.removeListeners();
this.log.info(`Done processing events in blocks ${starting} - ${current}`);
}
};
// should check every block for challenges that should be advanced,
// and respond to any listener emitted chain events
private registerListeners = () => {
Object.keys(this.providers).forEach((chainId) => {
this.log.info(`Registering listener for ${ChallengeEvents.ChallengeUpdated}`);
this.listener.attach(
ChallengeEvents.ChallengeUpdated,
async (event: ChallengeUpdatedEventPayload) => {
await jitter();
await this.processChallengeUpdated(event);
// parrot listener event
this.emit(WatcherEvents.CHALLENGE_UPDATED_EVENT, event);
},
);
this.log.info(`Registering listener for ${ChallengeEvents.StateProgressed}`);
this.listener.attach(
ChallengeEvents.StateProgressed,
async (event: StateProgressedEventPayload) => {
// add events to store + process
await this.processStateProgressed(event);
// parrot listener event
this.emit(WatcherEvents.STATE_PROGRESSED_EVENT, event);
},
);
this.log.info(`Registering listener for new blocks`);
this.providers[chainId].on("block", async (blockNumber: number) => {
this.log.debug(`Provider found a new block: ${blockNumber}`);
await this.advanceDisputes();
await this.store.updateLatestProcessedBlock(blockNumber);
});
});
};
private removeListeners = () => {
this.listener.detach();
Object.values(this.providers).forEach((provider) => provider.removeAllListeners());
};
private startAppChallenge = async (
appInstanceId: string,
chainId: number,
): Promise<providers.TransactionResponse> => {
this.log.debug(`Starting challenge for ${appInstanceId}`);
const challenge = (await this.store.getAppChallenge(appInstanceId)) || {
identityHash: appInstanceId,
appStateHash: HashZero,
versionNumber: Zero,
finalizesAt: Zero,
status: StoredAppChallengeStatus.NO_CHALLENGE,
chainId,
};
const response = await this.respondToChallenge(challenge);
if (typeof response === "string") {
throw new Error(`Could not initiate challenge for ${appInstanceId}. ${response}`);
}
this.log.info(`Challenge initiated with: ${response.hash}`);
return response;
};
private advanceDisputes = async () => {
const active = (await this.store.getActiveChallenges()).filter(
(c) => c.status !== StoredAppChallengeStatus.PENDING_TRANSITION,
);
this.log.debug(`Found ${active.length} active challenges: ${stringify(active)}`);
for (const challenge of active) {
await this.updateChallengeStatus(StoredAppChallengeStatus.PENDING_TRANSITION, challenge);
this.log.debug(`Advancing ${challenge.identityHash} dispute`);
try {
const response = await this.respondToChallenge(challenge);
if (typeof response === "string") {
this.log.info(response);
// something went wrong, remove pending status
await this.updateChallengeStatus(challenge.status, challenge);
continue;
}
} catch (e) {
// something went wrong, remove pending status
await this.updateChallengeStatus(challenge.status, challenge);
this.log.warn(
`Failed to respond to challenge: ${
e?.body?.error?.message || e.message
}. Challenge: ${stringify(challenge)}`,
);
}
}
};
private processStateProgressed = async (event: StateProgressedEventPayload) => {
this.log.info(`Processing state progressed event: ${stringify(event)}`);
await this.store.createStateProgressedEvent(event);
this.log.debug(`Saved event to store, adding action to app`);
await this.store.addOnchainAction(event.identityHash, this.providers[event.chainId]);
const app = await this.store.getAppInstance(event.identityHash);
this.log.debug(`Action added, updated app: ${stringify(app)}`);
};
private processChallengeUpdated = async (event: ChallengeUpdatedEventPayload) => {
this.log.info(`Processing challenge updated event: ${stringify(event)}`);
await this.store.createChallengeUpdatedEvent(event);
const existing = await this.store.getAppChallenge(event.identityHash);
if (
existing &&
toBN(existing.versionNumber).gt(event.versionNumber) &&
!toBN(event.versionNumber).isZero()
) {
return;
}
try {
await this.store.saveAppChallenge(event);
this.log.debug(`Saved challenge to store: ${stringify(event)}`);
} catch (e) {
this.log.error(`Failed to save challenge to store: ${stringify(event)}`);
}
};
private respondToChallenge = async (
challengeJson: StoredAppChallenge,
): Promise<providers.TransactionResponse | string> => {
this.log.info(`Respond to challenge called with: ${stringify(challengeJson)}`);
const challenge = bigNumberifyJson(challengeJson) as StoredAppChallenge;
const current = await this.providers[challenge.chainId].getBlockNumber();
let tx: providers.TransactionResponse | string;
if (challenge.finalizesAt.lte(current) && !challenge.finalizesAt.isZero()) {
this.log.info(
`Challenge timeout elapsed (finalizesAt: ${challenge.finalizesAt.toString()}, current: ${current})`,
);
tx = await this.respondToChallengeAfterTimeout(challenge!);
} else {
this.log.info(
`Challenge timeout not elapsed or 0 (finalizesAt: ${challenge.finalizesAt.toString()}, current: ${current})`,
);
tx = await this.respondToChallengeBeforeTimeout(challenge!);
}
return tx;
};
// takes in a challenge and advances it if possible based on the set state
// commitments available in the store. this function will error if the dispute
// must be advanced to a different state (ie a timeout has elapsed), and
// should only be used to progress a challenge
private respondToChallengeBeforeTimeout = async (
challenge: StoredAppChallenge,
): Promise<providers.TransactionResponse | string> => {
const { identityHash, versionNumber, status } = challenge;
// verify app and channel records
const app = await this.store.getAppInstance(identityHash);
const channel = await this.store.getStateChannelByAppIdentityHash(identityHash);
if (!app || !channel) {
throw new Error(`Could not find app or channel in store for app id: ${identityHash}`);
}
// make sure that challenge is up to date with our commitments
if (versionNumber.gte(app.latestVersionNumber)) {
// no actions available
const msg = `Latest set-state commitment version number ${toBN(
app.latestVersionNumber,
).toString()} is the same as challenge version number ${versionNumber.toString()}, doing nothing`;
return msg;
}
// get sorted commitments for s0 and s1
const [latest, prev] = await this.getSortedSetStateCommitments(app.identityHash);
const canPlayAction = await this.canPlayAction(app, challenge);
switch (status) {
case StoredAppChallengeStatus.NO_CHALLENGE: {
if (canPlayAction) {
this.log.debug(`Calling set and progress state for challenge`);
return this.setAndProgressState(app, channel, challenge, [latest, prev]);
} else if (latest.signatures.filter((x) => !!x).length === 2) {
this.log.debug(`Calling set state for challenge`);
return this.setState(app, channel, challenge, latest);
} else {
const msg = `No double signed set state commitment found with higher nonce then ${versionNumber.toString()}, doing nothing`;
this.log.debug(msg);
return msg;
}
}
case StoredAppChallengeStatus.IN_DISPUTE: {
if (!canPlayAction) {
this.log.debug(`Calling set state for challenge`);
return this.setState(app, channel, challenge, latest);
}
// if there is no state to set, but there is an action to play
// call `progressState`
if (toBN(prev.versionNumber).eq(challenge.versionNumber)) {
this.log.debug(`Calling progress state for challenge`);
return this.progressState(app, channel, [latest, prev]);
}
// if there is a state that is set and immediately finalized,
// call `setAndProgressState`
if (
toBN(prev.stateTimeout).isZero() &&
challenge.versionNumber.lt(prev.versionNumber._hex)
) {
this.log.debug(`Calling set and progress state for challenge`);
return this.setAndProgressState(app, channel, challenge, [latest, prev]);
}
const msg = `Cannot progress challenge, must wait out timeout. Challenge: ${stringify(
challenge,
)}`;
this.log.debug(msg);
return msg;
}
case StoredAppChallengeStatus.IN_ONCHAIN_PROGRESSION: {
if (canPlayAction) {
this.log.debug(`Calling progress state for challenge`);
return this.progressState(app, channel, [latest, prev]);
}
return `Cannot progress challenge, must wait out timeout. Challenge: ${stringify(
challenge,
)}`;
}
case StoredAppChallengeStatus.PENDING_TRANSITION: {
const msg = `Challenge has pending transaction, waiting to resolve before responding`;
this.log.debug(msg);
return msg;
}
case StoredAppChallengeStatus.EXPLICITLY_FINALIZED:
case StoredAppChallengeStatus.OUTCOME_SET:
case StoredAppChallengeStatus.CONDITIONAL_SENT: {
throw new Error(
`Challenge is in the wrong status for response during timeout: ${stringify(challenge)}`,
);
}
default: {
throw new Error(`Unrecognized challenge status. Challenge: ${stringify(challenge)}`);
}
}
};
// should advance (call `setOutcome`, `progressState`, etc.) any active
// disputes with an elapsed timeout
private respondToChallengeAfterTimeout = async (
challenge: StoredAppChallenge,
): Promise<providers.TransactionResponse | string> => {
const { identityHash, status } = challenge;
// verify app and channel records
const app = await this.store.getAppInstance(identityHash);
const channel = await this.store.getStateChannelByAppIdentityHash(identityHash);
if (!app || !channel) {
throw new Error(`Could not find app or channel in store for app id: ${identityHash}`);
}
const canPlayAction = await this.canPlayAction(app, challenge);
switch (status) {
case StoredAppChallengeStatus.NO_CHALLENGE: {
throw new Error(
`Timed out challenge should never have a no challenge status. Challenge: ${stringify(
challenge,
)}`,
);
}
case StoredAppChallengeStatus.IN_DISPUTE: {
// check if there is a valid action to play
if (canPlayAction) {
this.log.info(
`Onchain state set, progressing to nonce ${challenge.versionNumber.add(1).toString()}`,
);
return this.progressState(
app,
channel,
await this.getSortedSetStateCommitments(app.identityHash),
);
} else {
this.log.info(`Onchain state finalized, no actions to progress, setting outcome`);
return this.setOutcome(app, channel);
}
}
case StoredAppChallengeStatus.IN_ONCHAIN_PROGRESSION: {
this.log.info(`Onchain progression finalized, setting outcome`);
return this.setOutcome(app, channel);
}
case StoredAppChallengeStatus.EXPLICITLY_FINALIZED: {
this.log.info(`Challenge explicitly finalized, setting outcome`);
return this.setOutcome(app, channel);
}
case StoredAppChallengeStatus.OUTCOME_SET: {
// check that free balance app has been disputed
const isFreeBalance = await this.isFreeBalanceApp(identityHash);
if (isFreeBalance) {
const setup = await this.store.getSetupCommitment(channel.multisigAddress);
if (!setup) {
throw new Error(
`Could not find setup transaction for channel ${channel.multisigAddress}`,
);
}
return this.executeEffectOfFreeBalance(channel, setup);
}
const conditional = await this.store.getConditionalTransactionCommitment(identityHash);
if (!conditional) {
const msg = `Cannot find conditional transaction for app: ${identityHash}, cannot finalize`;
this.log.debug(msg);
return msg;
}
this.log.info(`Sending conditional transaction`);
return this.executeEffectOfInterpretedApp(app, channel, conditional);
}
case StoredAppChallengeStatus.CONDITIONAL_SENT: {
const msg = `Conditional transaction for challenge has already been sent. App: ${identityHash}`;
this.log.info(msg);
return msg;
}
case StoredAppChallengeStatus.PENDING_TRANSITION: {
const msg = `Challenge has pending transaction, waiting to resolve before responding`;
this.log.debug(msg);
return msg;
}
default: {
throw new Error(`Unrecognized challenge status. Challenge: ${stringify(challenge)}`);
}
}
};
//////// Private contract methods
private setState = async (
app: AppInstanceJson,
channel: StateChannelJSON,
challenge: StoredAppChallenge,
setStateCommitment: SetStateCommitmentJSON,
): Promise<providers.TransactionResponse | string> => {
this.log.info(
`Calling 'setState' for ${setStateCommitment.appIdentityHash} at nonce ${toBN(
setStateCommitment.versionNumber,
).toString()}`,
);
this.log.debug(`Setting state with commitment: ${stringify(setStateCommitment)}`);
const commitment = SetStateCommitment.fromJson(setStateCommitment);
const response = await this.sendContractTransaction(
await commitment.getSignedTransaction(),
channel.chainId,
channel.multisigAddress,
);
if (typeof response === "string") {
this.emit(WatcherEvents.CHALLENGE_PROGRESSION_FAILED_EVENT, {
appInstanceId: commitment.appIdentityHash,
error: response,
multisigAddress: channel.multisigAddress,
challenge,
params: { setStateCommitment, app, channel },
});
} else {
response.wait().then((receipt) => {
this.emit(WatcherEvents.CHALLENGE_PROGRESSED_EVENT, {
appInstanceId: commitment.appIdentityHash,
transaction: receipt,
multisigAddress: channel.multisigAddress,
});
});
}
return response;
};
private executeEffectOfFreeBalance = async (
channel: StateChannelJSON,
setup: MinimalTransaction,
): Promise<providers.TransactionResponse | string> => {
// make sure all ssociated apps has already tried to execute its effect
const appIds = channel.appInstances.map(([id]) => id);
for (const identityHash of appIds) {
const challenge = await this.getChallengeOrThrow(identityHash);
if (challenge.status !== StoredAppChallengeStatus.CONDITIONAL_SENT) {
const msg = `Make sure all apps have sent conditional transactions before sending free balance`;
return msg;
}
}
const challenge = await this.getChallengeOrThrow(channel.freeBalanceAppInstance!.identityHash);
const response = await this.sendContractTransaction(
setup,
channel.chainId,
channel.multisigAddress,
);
if (typeof response === "string") {
this.emit(WatcherEvents.CHALLENGE_COMPLETION_FAILED_EVENT, {
appInstanceId: channel!.freeBalanceAppInstance!.identityHash,
error: response,
multisigAddress: channel.multisigAddress,
challenge,
params: { setup, channel },
});
} else {
response.wait().then(async (receipt) => {
await this.updateChallengeStatus(StoredAppChallengeStatus.CONDITIONAL_SENT, challenge!);
this.emit(WatcherEvents.CHALLENGE_COMPLETED_EVENT, {
appInstanceId: channel!.freeBalanceAppInstance!.identityHash,
transaction: receipt,
multisigAddress: channel.multisigAddress,
});
});
}
return response;
};
private executeEffectOfInterpretedApp = async (
app: AppInstanceJson,
channel: StateChannelJSON,
conditional: ConditionalTransactionCommitmentJSON,
): Promise<providers.TransactionResponse | string> => {
this.log.info(`Sending conditional transaction for ${app.identityHash}`);
const challenge = await this.getChallengeOrThrow(app.identityHash);
const commitment = ConditionalTransactionCommitment.fromJson(conditional);
const response = await this.sendContractTransaction(
await commitment.getSignedTransaction(),
channel.chainId,
channel.multisigAddress,
);
if (typeof response === "string") {
this.emit(WatcherEvents.CHALLENGE_COMPLETION_FAILED_EVENT, {
appInstanceId: app.identityHash,
error: response,
multisigAddress: channel.multisigAddress,
challenge,
params: { conditional, app, channel },
});
} else {
response.wait().then(async (receipt) => {
// update challenge of app and free balance
const appChallenge = await this.store.getAppChallenge(app.identityHash);
await this.updateChallengeStatus(StoredAppChallengeStatus.CONDITIONAL_SENT, appChallenge!);
this.emit(WatcherEvents.CHALLENGE_COMPLETED_EVENT, {
appInstanceId: app.identityHash,
transaction: receipt,
multisigAddress: channel.multisigAddress,
});
});
}
return response;
};
private progressState = async (
app: AppInstanceJson,
channel: StateChannelJSON,
sortedCommitments: SetStateCommitmentJSON[],
): Promise<providers.TransactionResponse | string> => {
const challenge = await this.getChallengeOrThrow(app.identityHash);
this.log.info(
`Calling 'progressState' for ${app.identityHash} at currrent nonce ${toBN(
challenge.versionNumber,
).toString()}`,
);
const [latest] = sortedCommitments.map(SetStateCommitment.fromJson);
const action = defaultAbiCoder.encode([app.abiEncodings.actionEncoding!], [app.latestAction]);
const state = defaultAbiCoder.encode([app.abiEncodings.stateEncoding], [app.latestState]);
const tx = {
to: this.registries[channel.chainId].address,
value: 0,
data: new Interface(ChallengeRegistry.abi).encodeFunctionData("progressState", [
this.getAppIdentity(app, channel.multisigAddress),
await latest.getSignedAppChallengeUpdate(),
state,
action,
]),
};
const response = await this.sendContractTransaction(
tx,
channel.chainId,
channel.multisigAddress,
);
if (typeof response === "string") {
this.emit(WatcherEvents.CHALLENGE_PROGRESSION_FAILED_EVENT, {
appInstanceId: app.identityHash,
error: response,
multisigAddress: channel.multisigAddress,
challenge,
params: { commitments: sortedCommitments, app, channel },
});
} else {
response.wait().then((receipt) =>
this.emit(WatcherEvents.CHALLENGE_PROGRESSED_EVENT, {
appInstanceId: app.identityHash,
transaction: receipt,
multisigAddress: channel.multisigAddress,
}),
);
}
return response;
};
private setAndProgressState = async (
app: AppInstanceJson,
channel: StateChannelJSON,
challenge: StoredAppChallenge,
sortedCommitments: SetStateCommitmentJSON[],
): Promise<providers.TransactionResponse | string> => {
this.log.info(
`Calling 'setAndProgressState' for ${app.identityHash} with expected final nonce of ${toBN(
sortedCommitments[0].versionNumber,
).toString()}`,
);
const [latest, prev] = sortedCommitments.map(SetStateCommitment.fromJson);
const action = defaultAbiCoder.encode([app.abiEncodings.actionEncoding!], [app.latestAction]);
const state = defaultAbiCoder.encode([app.abiEncodings.stateEncoding], [app.latestState]);
const tx = {
to: this.registries[channel.chainId].address,
value: 0,
data: new Interface(ChallengeRegistry.abi).encodeFunctionData("setAndProgressState", [
this.getAppIdentity(app, channel.multisigAddress),
await prev.getSignedAppChallengeUpdate(),
await latest.getSignedAppChallengeUpdate(),
state,
action,
]),
};
const response = await this.sendContractTransaction(
tx,
channel.chainId,
channel.multisigAddress,
);
if (typeof response === "string") {
this.emit(WatcherEvents.CHALLENGE_PROGRESSION_FAILED_EVENT, {
appInstanceId: app.identityHash,
error: response,
multisigAddress: channel.multisigAddress,
challenge,
params: { commitments: sortedCommitments, app, channel },
});
} else {
response.wait().then((receipt) =>
this.emit(WatcherEvents.CHALLENGE_PROGRESSED_EVENT, {
appInstanceId: app.identityHash,
transaction: receipt,
multisigAddress: channel.multisigAddress,
}),
);
}
return response;
};
private setOutcome = async (
app: AppInstanceJson,
channel: StateChannelJSON,
): Promise<providers.TransactionResponse | string> => {
const challenge = await this.getChallengeOrThrow(app.identityHash);
this.log.info(
`Calling 'setOutcome' for ${app.identityHash} at nonce ${toBN(
challenge.versionNumber,
).toString()}`,
);
// NOTE: The `addOnchainAction` store method does not have the ability to
// sign any commitments or new states. Instead, the app / set-state
// commitment will have emitted action / sigs added to it. The channel
// participants are expected to subscribe to events and update their own
// apps and commitments if desired. Log a warning if values are out of
// sync, and proceed to set outcome
if (!toBN(challenge.versionNumber).eq(toBN(app.latestVersionNumber))) {
this.log.warn(
`Stored app is not up to date with onchain challenges, calling set outcome regardless since state is finalized onchain`,
);
this.log.debug(`Stored app: ${stringify(app)}`);
}
// derive final state from action on app
const encodedState = defaultAbiCoder.encode(
[app.abiEncodings.stateEncoding],
[app.latestState],
);
const encodedFinalState = !!app.latestAction
? await new Contract(
app.appDefinition,
CounterfactualApp.abi,
this.providers[channel.chainId],
).applyAction(
encodedState,
defaultAbiCoder.encode([app.abiEncodings.actionEncoding!], [app.latestAction]),
)
: encodedState;
const tx = {
to: this.registries[channel.chainId].address,
value: 0,
data: new Interface(ChallengeRegistry.abi).encodeFunctionData("setOutcome", [
this.getAppIdentity(app, channel.multisigAddress),
encodedFinalState,
]),
};
const response = await this.sendContractTransaction(
tx,
channel.chainId,
channel.multisigAddress,
);
if (typeof response === "string") {
this.emit(WatcherEvents.CHALLENGE_OUTCOME_FAILED_EVENT, {
appInstanceId: app.identityHash,
error: response,
multisigAddress: channel.multisigAddress,
challenge,
params: { app, channel },
});
} else {
response.wait().then((receipt) =>
this.emit(WatcherEvents.CHALLENGE_OUTCOME_SET_EVENT, {
appInstanceId: app.identityHash,
transaction: receipt,
multisigAddress: channel.multisigAddress,
}),
);
}
return response;
};
private cancelChallenge = async (
app: AppInstanceJson,
channel: StateChannelJSON,
req: SignedCancelChallengeRequest,
): Promise<providers.TransactionResponse | string> => {
const challenge = await this.getChallengeOrThrow(app.identityHash);
this.log.debug(
`Calling 'cancelChallenge' for ${app.identityHash} at nonce ${toBN(
challenge.versionNumber,
).toString()}`,
);
const tx = {
to: this.registries[channel.chainId].address,
value: 0,
data: new Interface(ChallengeRegistry.abi).encodeFunctionData("cancelDispute", [
this.getAppIdentity(app, channel.multisigAddress),
req,
]),
};
const response = await this.sendContractTransaction(
tx,
channel.chainId,
channel.multisigAddress,
);
if (typeof response === "string") {
this.emit(WatcherEvents.CHALLENGE_CANCELLATION_FAILED_EVENT, {
appInstanceId: app.identityHash,
error: response,
multisigAddress: channel.multisigAddress,
challenge,
params: { req, app, channel },
});
} else {
response.wait().then((receipt) => {
this.emit(WatcherEvents.CHALLENGE_CANCELLED_EVENT, {
appInstanceId: app.identityHash,
transaction: receipt,
multisigAddress: channel.multisigAddress,
});
});
}
return response;
};
//////// Private helper functions
private sendContractTransaction = async (
transaction: MinimalTransaction,
chainId: number,
multisigAddress: string,
): Promise<providers.TransactionResponse | string> => {
if (this.transactionService) {
const response = await this.transactionService.sendTransaction(
transaction,
chainId,
multisigAddress,
);
this.log.info(`Transaction sent, waiting for ${response.hash} to be mined`);
response.wait().then((r) => this.log.info(`Tx ${response.hash} mined`));
return response;
}
const signer = this.getConnectedSigner(chainId);
const KNOWN_ERRORS = ["the tx doesn't have the correct nonce"];
const MAX_RETRIES = 3;
const errors: { [k: number]: string } = [];
for (let attempt = 1; attempt < MAX_RETRIES + 1; attempt += 1) {
this.log.debug(`Attempt ${attempt}/${MAX_RETRIES} to send transaction to ${transaction.to}`);
let response: providers.TransactionResponse;
try {
response = await signer.sendTransaction({
...transaction,
nonce: await this.providers[chainId].getTransactionCount(signer.address),
});
this.log.info(`Transaction sent, waiting for ${response.hash} to be mined`);
response.wait().then((r) => this.log.info(`Tx ${response.hash} mined`));
return response;
} catch (e) {
const message = e?.body?.error?.message || e.message;
errors[attempt] = message;
const knownErr = KNOWN_ERRORS.find((err) => message.includes(err));
if (!knownErr) {
// unknown error, do not retry
this.log.error(`Failed to send transaction: ${message}`);
const msg = `Error sending transaction: ${message}`;
return msg;
}
// known error, retry
this.log.warn(
`Sending transaction attempt ${attempt}/${MAX_RETRIES} failed: ${message}. Retrying.`,
);
}
}
return `Failed to send transaction (errors indexed by attempt): ${stringify(errors)}`;
};
private getConnectedSigner = (chainId: number): IChannelSigner => {
return this.signer.connect(this.providers[chainId]) as IChannelSigner;
};
private getAppIdentity = (app: AppInstanceJson, multisigAddress: string): AppIdentity => {
return {
channelNonce: toBN(app.appSeqNo),
participants: [
getSignerAddressFromPublicIdentifier(app.initiatorIdentifier),
getSignerAddressFromPublicIdentifier(app.responderIdentifier),
],
multisigAddress,
appDefinition: app.appDefinition,
defaultTimeout: toBN(app.defaultTimeout),
};
};
private getChallengeOrThrow = async (identityHash: string): Promise<StoredAppChallenge> => {
const challenge = await this.store.getAppChallenge(identityHash);
if (!challenge) {
throw new Error(`Could not find challenge for app ${identityHash}`);
}
return challenge;
};
// returns true IFF:
// - there is a singly signed commitment for s1
// - there is a doubly signed commitment for s0
// - app has action corresponding to s0 --> s1 transition
// - the challenge may still be progressed (s0 finalized, s1 playable)
private canPlayAction = async (
app: AppInstanceJson,
challenge: StoredAppChallenge,
): Promise<boolean> => {
// make sure the app has an action
if (!app.latestAction) {
return false;
}
const { identityHash, versionNumber } = challenge;
// make sure there are valid commitments
const [latest, prev] = await this.getSortedSetStateCommitments(identityHash);
// valid IFF latest is single signed, with higher version number then
// challenge
const validLatestCommitment =
!!latest &&
latest.signatures.filter((x) => !!x).length === 1 &&
toBN(latest.versionNumber).gt(versionNumber);
// must be double signed, have eq or greater nonce then existing,
// and nonce == latest.nonce - 1
const validPreviousCommitment =
!!prev &&
prev.signatures.filter((x) => !!x).length === 2 &&
toBN(prev.versionNumber).gte(versionNumber) &&
toBN(prev.versionNumber).add(1).eq(latest.versionNumber._hex);
if (!validLatestCommitment || !validPreviousCommitment) {
return false;
}
// must also be progressable (state progression window not elapsed)
const current = await this.providers[challenge.chainId].getBlockNumber();
// handle empty challenge case (in initiate) by using current block
// as the `finalizesAt`
const noLongerProgressable = toBN(
challenge.finalizesAt.isZero() ? current : challenge.finalizesAt,
).add(app.defaultTimeout);
return toBN(current).lt(noLongerProgressable);
};
private updateChallengeStatus = async (
status: StoredAppChallengeStatus,
challenge: StoredAppChallenge,
) => {
this.log.debug(`Transitioning challenge status from ${challenge.status} to ${status}`);
try {
return await this.store.saveAppChallenge({
...challenge,
status,
});
} catch (e) {
this.log.error(`Failed to updateChallengeStatus: ${e.message}`);
}
};
private isFreeBalanceApp = async (identityHash: string): Promise<boolean> => {
const channel = await this.store.getStateChannelByAppIdentityHash(identityHash);
if (!channel || !channel.freeBalanceAppInstance) {
return false;
}
return channel.freeBalanceAppInstance.identityHash === identityHash;
};
private getSortedSetStateCommitments = async (
identityHash: string,
): Promise<SetStateCommitmentJSON[]> => {
const unsorted = await this.store.getSetStateCommitments(identityHash);
return unsorted.sort((a, b) => toBN(b.versionNumber).sub(toBN(a.versionNumber)).toNumber());
};
} | the_stack |
import { decodeAddress, getApplicationAddress } from "algosdk";
import { assert } from "chai";
import { bobAcc } from "../../../../algob/test/mocks/account";
import { AccountStore } from "../../../src/account";
import { RUNTIME_ERRORS } from "../../../src/errors/errors-list";
import { Runtime } from "../../../src/index";
import { Interpreter } from "../../../src/interpreter/interpreter";
import { ALGORAND_ACCOUNT_MIN_BALANCE, MaxTEALVersion } from "../../../src/lib/constants";
import { AccountStoreI, ExecutionMode } from "../../../src/types";
import { expectRuntimeError } from "../../helpers/runtime-errors";
import { elonMuskAccount, johnAccount } from "../../mocks/account";
import { accInfo } from "../../mocks/stateful";
import { elonAddr, johnAddr, TXN_OBJ } from "../../mocks/txn";
export function setDummyAccInfo (acc: AccountStoreI): void {
acc.appsLocalState = accInfo[0].appsLocalState;
acc.appsTotalSchema = accInfo[0].appsTotalSchema;
acc.createdApps = accInfo[0].createdApps;
}
describe("TEALv5: Inner Transactions", function () {
const elonPk = decodeAddress(elonAddr).publicKey;
let tealCode: string;
let interpreter: Interpreter;
// setup 1st account (to be used as sender)
const elonAcc: AccountStoreI = new AccountStore(0, elonMuskAccount); // setup test account
setDummyAccInfo(elonAcc);
// setup 2nd account
const johnAcc = new AccountStore(0, johnAccount);
// setup 2nd account
const bobAccount = new AccountStore(1000000, bobAcc);
// setup application account
const appAccAddr = getApplicationAddress(TXN_OBJ.apid);
const applicationAccount = new AccountStore(
ALGORAND_ACCOUNT_MIN_BALANCE,
{ addr: appAccAddr, sk: new Uint8Array(0) });
const reset = (): void => {
while (interpreter.stack.length() !== 0) { interpreter.stack.pop(); }
interpreter.subTxn = undefined;
interpreter.runtime.ctx.pooledApplCost = 0;
interpreter.instructions = [];
interpreter.innerTxns = [];
interpreter.instructionIndex = 0;
interpreter.runtime.ctx.tx = { ...TXN_OBJ, snd: Buffer.from(elonPk) };
interpreter.runtime.ctx.gtxs = [interpreter.runtime.ctx.tx];
interpreter.runtime.ctx.isInnerTx = false;
// set new tx receipt
interpreter.runtime.ctx.state.txReceipts.set(TXN_OBJ.txID, {
txn: TXN_OBJ,
txID: TXN_OBJ.txID
});
};
const setUpInterpreter = (): void => {
interpreter = new Interpreter();
interpreter.runtime = new Runtime([elonAcc, johnAcc, bobAccount, applicationAccount]);
interpreter.tealVersion = MaxTEALVersion;
reset();
};
const executeTEAL = (tealCode: string): void => {
// reset interpreter
reset();
interpreter.execute(tealCode, ExecutionMode.APPLICATION, interpreter.runtime, 0);
};
this.beforeAll(setUpInterpreter);
describe("TestActionTypes", function () {
it("should fail: itxn_submit without itxn_begin", function () {
tealCode = `
itxn_submit
int 1
`;
expectRuntimeError(
() => executeTEAL(tealCode),
RUNTIME_ERRORS.TEAL.ITXN_SUBMIT_WITHOUT_ITXN_BEGIN
);
});
it("should fail: itxn_field without itxn_begin", function () {
tealCode = `
int pay
itxn_field TypeEnum
itxn_submit
int 1
`;
expectRuntimeError(
() => executeTEAL(tealCode),
RUNTIME_ERRORS.TEAL.ITXN_FIELD_WITHOUT_ITXN_BEGIN
);
});
it("should fail: Invalid inner transaction type", function () {
tealCode = `
itxn_begin
itxn_submit
int 1
`;
assert.throws(
() => executeTEAL(tealCode), `unsupported type for itxn_submit`);
tealCode = `
itxn_begin
byte "pya"
itxn_field Type
itxn_submit
int 1
`;
assert.throws(
() => executeTEAL(tealCode), `Type does not represent 'pay', 'axfer', 'acfg' or 'afrz'`);
});
it("should fail: Type arg not a byte array", function () {
// mixed up the int form for the byte form
tealCode = `
itxn_begin
int pay
itxn_field Type
itxn_submit
int 1
`;
expectRuntimeError(
() => executeTEAL(tealCode),
RUNTIME_ERRORS.TEAL.INVALID_TYPE
);
});
it("should fail: not a uint64", function () {
// mixed up the byte form for the int form (vice versa of above)
tealCode = `
itxn_begin
byte "pay"
itxn_field TypeEnum
itxn_submit
int 1
`;
expectRuntimeError(
() => executeTEAL(tealCode),
RUNTIME_ERRORS.TEAL.INVALID_TYPE
);
});
it("should fail: invalid types (good, but not allowed in tealv5)", function () {
// good types, not alllowed yet
tealCode = `
itxn_begin
byte "keyreg"
itxn_field Type
itxn_submit
int 1
`;
expectRuntimeError(
() => executeTEAL(tealCode),
RUNTIME_ERRORS.TEAL.ITXN_FIELD_ERR
);
tealCode = `
itxn_begin
byte "appl"
itxn_field Type
itxn_submit
int 1
`;
expectRuntimeError(
() => executeTEAL(tealCode),
RUNTIME_ERRORS.TEAL.ITXN_FIELD_ERR
);
});
it("should fail: invalid types (good, but not allowed in tealv5) for TypeEnum", function () {
// good types, not alllowed yet for type enums
tealCode = `
itxn_begin
int keyreg
itxn_field TypeEnum
itxn_submit
int 1
`;
expectRuntimeError(
() => executeTEAL(tealCode),
RUNTIME_ERRORS.TEAL.ITXN_FIELD_ERR
);
tealCode = `
itxn_begin
int appl
itxn_field TypeEnum
itxn_submit
int 1
`;
expectRuntimeError(
() => executeTEAL(tealCode),
RUNTIME_ERRORS.TEAL.ITXN_FIELD_ERR
);
tealCode = `
itxn_begin
int 42
itxn_field TypeEnum
itxn_submit
int 1
`;
expectRuntimeError(
() => executeTEAL(tealCode),
RUNTIME_ERRORS.TEAL.ITXN_FIELD_ERR
);
tealCode = `
itxn_begin
int 0
itxn_field TypeEnum
itxn_submit
int 1
`;
expectRuntimeError(
() => executeTEAL(tealCode),
RUNTIME_ERRORS.TEAL.ITXN_FIELD_ERR
);
});
it(`should fail: "insufficient balance" because app account is charged fee`, function () {
// set application account balance to minimum
applicationAccount.amount = BigInt(ALGORAND_ACCOUNT_MIN_BALANCE);
// (defaults make these 0 pay|axfer to zero address, from app account)
tealCode = `
itxn_begin
byte "pay"
itxn_field Type
itxn_submit
int 1
`;
expectRuntimeError(
() => executeTEAL(tealCode),
RUNTIME_ERRORS.TRANSACTION.INSUFFICIENT_ACCOUNT_BALANCE
);
tealCode = `
itxn_begin
byte "axfer"
itxn_field Type
itxn_submit
int 1
`;
expectRuntimeError(
() => executeTEAL(tealCode),
RUNTIME_ERRORS.TRANSACTION.INSUFFICIENT_ACCOUNT_BALANCE
);
tealCode = `
itxn_begin
int pay
itxn_field TypeEnum
itxn_submit
int 1
`;
expectRuntimeError(
() => executeTEAL(tealCode),
RUNTIME_ERRORS.TRANSACTION.INSUFFICIENT_ACCOUNT_BALANCE
);
tealCode = `
itxn_begin
int axfer
itxn_field TypeEnum
itxn_submit
int 1
`;
expectRuntimeError(
() => executeTEAL(tealCode),
RUNTIME_ERRORS.TRANSACTION.INSUFFICIENT_ACCOUNT_BALANCE
);
tealCode = `
itxn_begin
int acfg
itxn_field TypeEnum
itxn_submit
int 1
`;
expectRuntimeError(
() => executeTEAL(tealCode),
RUNTIME_ERRORS.TRANSACTION.INSUFFICIENT_ACCOUNT_BALANCE
);
});
it(`should pass if app account is funded`, function () {
// increase balance
const acc = interpreter.runtime.ctx.state.accounts.get(appAccAddr);
if (acc) { acc.amount = BigInt(ALGORAND_ACCOUNT_MIN_BALANCE) * 10n; }
// default receiver is zeroAddr, amount is 0
tealCode = `
itxn_begin
byte "pay"
itxn_field Type
itxn_submit
int 1
`;
assert.doesNotThrow(() => executeTEAL(tealCode));
tealCode = `
itxn_begin
int pay
itxn_field TypeEnum
itxn_submit
int 1
`;
assert.doesNotThrow(() => executeTEAL(tealCode));
tealCode = `
itxn_begin
byte "axfer"
itxn_field Type
int 1
`;
assert.doesNotThrow(() => executeTEAL(tealCode));
});
it(`should pass: if app account is funded, without itxn_submit`, function () {
tealCode = `
itxn_begin
byte "axfer"
itxn_field Type
int 1
`;
assert.doesNotThrow(() => executeTEAL(tealCode));
tealCode = `
itxn_begin
int pay
itxn_field TypeEnum
int 1
`;
assert.doesNotThrow(() => executeTEAL(tealCode));
tealCode = `
itxn_begin
byte "acfg"
itxn_field Type
int 1
`;
assert.doesNotThrow(() => executeTEAL(tealCode));
tealCode = `
itxn_begin
int acfg
itxn_field TypeEnum
int 1
`;
assert.doesNotThrow(() => executeTEAL(tealCode));
tealCode = `
itxn_begin
byte "afrz"
itxn_field Type
int 1
`;
assert.doesNotThrow(() => executeTEAL(tealCode));
tealCode = `
itxn_begin
int afrz
itxn_field TypeEnum
int 1
`;
assert.doesNotThrow(() => executeTEAL(tealCode));
});
});
describe("TestFieldTypes", function () {
it(`should fail: not an address`, function () {
tealCode = `
itxn_begin
byte "pay"
itxn_field Sender
`;
expectRuntimeError(() => executeTEAL(tealCode), RUNTIME_ERRORS.TEAL.ADDR_NOT_VALID);
tealCode = `
itxn_begin
int 7
itxn_field Receiver
`;
expectRuntimeError(() => executeTEAL(tealCode), RUNTIME_ERRORS.TEAL.INVALID_TYPE);
tealCode = `
itxn_begin
byte ""
itxn_field CloseRemainderTo
`;
expectRuntimeError(() => executeTEAL(tealCode), RUNTIME_ERRORS.TEAL.ADDR_NOT_VALID);
tealCode = `
itxn_begin
byte ""
itxn_field AssetSender
`;
expectRuntimeError(() => executeTEAL(tealCode), RUNTIME_ERRORS.TEAL.ADDR_NOT_VALID);
});
it(`should fail: invalid ref, not an account`, function () {
// can't really tell if it's an addres, so 32 bytes gets further
tealCode = `
itxn_begin
byte "01234567890123456789012345678901"
itxn_field AssetReceiver
`;
expectRuntimeError(() => executeTEAL(tealCode),
RUNTIME_ERRORS.TEAL.ADDR_NOT_FOUND_IN_TXN_ACCOUNT);
// but a b32 string rep is not an account
tealCode = `
itxn_begin
byte "GAYTEMZUGU3DOOBZGAYTEMZUGU3DOOBZGAYTEMZUGU3DOOBZGAYZIZD42E"
itxn_field AssetCloseTo
`;
expectRuntimeError(() => executeTEAL(tealCode), RUNTIME_ERRORS.TEAL.ADDR_NOT_VALID);
});
it(`should fail: not a uint64`, function () {
tealCode = `
itxn_begin
byte "pay"
itxn_field Fee
`;
expectRuntimeError(() => executeTEAL(tealCode), RUNTIME_ERRORS.TEAL.INVALID_TYPE);
tealCode = `
itxn_begin
byte 0x01
itxn_field Amount
`;
expectRuntimeError(() => executeTEAL(tealCode), RUNTIME_ERRORS.TEAL.INVALID_TYPE);
tealCode = `
itxn_begin
byte 0x01
itxn_field XferAsset
`;
expectRuntimeError(() => executeTEAL(tealCode), RUNTIME_ERRORS.TEAL.INVALID_TYPE);
tealCode = `
itxn_begin
byte 0x01
itxn_field AssetAmount
`;
expectRuntimeError(() => executeTEAL(tealCode), RUNTIME_ERRORS.TEAL.INVALID_TYPE);
});
});
describe("TestAppPay", function () {
let pay: string;
this.beforeAll(() => {
pay = `
itxn_begin
itxn_field Amount
itxn_field Receiver
itxn_field Sender
int pay
itxn_field TypeEnum
itxn_submit
int 1
`;
});
it(`should assert sender, application balance 0 before pay`, function () {
// set sender.balance == 0
const elonAcc = interpreter.runtime.ctx.state.accounts.get(elonAddr);
if (elonAcc) { elonAcc.amount = 0n; }
const acc = interpreter.runtime.ctx.state.accounts.get(appAccAddr);
if (acc) { acc.amount = 0n; }
const checkBal = `
txn Sender
balance
int 0
==
`;
// verify sender(of top level tx) balance
assert.doesNotThrow(() => executeTEAL(checkBal));
const checkAppBal = `
global CurrentApplicationAddress
balance
int 0
==
`;
// verify app balance
assert.doesNotThrow(() => executeTEAL(checkAppBal));
});
// /*
// * This would be a good test for rekeying support (sender should only be contract).
// * atm, sender in runtime can be diff (as we don't have a secret key validation)
// it(`should fail: unauthorized transaction`, function () {
// const unauthorizedCode = `
// txn Sender
// txn Accounts 1
// int 100
// ` + pay;
// executeTEAL(unauthorizedCode);
// });
// */
it(`should fail: insufficient balance`, function () {
const teal = `
global CurrentApplicationAddress
txn Accounts 1
int 100
` + pay;
expectRuntimeError(
() => executeTEAL(teal),
RUNTIME_ERRORS.TRANSACTION.INSUFFICIENT_ACCOUNT_BALANCE
);
});
// TODO: check if this should indeed fail (if receiver account.balance < minBalance)
it(`should pass: after increasing app account's balance`, function () {
const acc = interpreter.runtime.ctx.state.accounts.get(appAccAddr);
if (acc) { acc.amount = 1000000n; }
const teal = `
global CurrentApplicationAddress
txn Accounts 1
int 100
` + pay;
assert.doesNotThrow(() => executeTEAL(teal));
const testSenderBal = `
global CurrentApplicationAddress
balance
int 998900
==
`;
assert.doesNotThrow(() => executeTEAL(testSenderBal));
const testReceiverBal = `
txn Accounts 1
balance
int 100
==
`;
assert.doesNotThrow(() => executeTEAL(testReceiverBal));
});
it(`should test pay with closeRemTo`, function () {
const acc = interpreter.runtime.ctx.state.accounts.get(elonAddr);
if (acc) { acc.amount = 1000000n; }
const teal = `
itxn_begin
int pay
itxn_field TypeEnum
txn Receiver
itxn_field CloseRemainderTo
itxn_submit
int 1
`;
executeTEAL(teal);
// verify app account's balance == 0
const verifyBal = `
global CurrentApplicationAddress
balance
!
`;
assert.doesNotThrow(() => executeTEAL(verifyBal));
// assert receiver got most of the ALGO (minus fees)
assert.equal(interpreter.runtime.ctx.getAccount(johnAddr)?.amount, 998000n);
});
});
describe("TestAppAssetOptIn", function () {
let axfer: string;
this.beforeAll(() => {
axfer = `
itxn_begin
int axfer
itxn_field TypeEnum
int 1
itxn_field XferAsset
int 2
itxn_field AssetAmount
txn Sender
itxn_field AssetReceiver
itxn_submit
int 1
`;
});
it(`should fail: invalid ASA Ref`, function () {
TXN_OBJ.apas = []; // remove foreign assets refs
expectRuntimeError(
() => executeTEAL(axfer),
RUNTIME_ERRORS.TEAL.INVALID_ASA_REFERENCE
);
});
it(`should fail: ref is passed but bal == 0`, function () {
TXN_OBJ.apas = [1, 9]; // set foreign asset
expectRuntimeError(
() => executeTEAL(axfer),
RUNTIME_ERRORS.TRANSACTION.INSUFFICIENT_ACCOUNT_BALANCE
);
});
it(`should fail: not opted in`, function () {
// increase app balance
const acc = interpreter.runtime.ctx.state.accounts.get(appAccAddr);
if (acc) { acc.amount = 1000000n; }
// sufficient bal, but not optedIn
expectRuntimeError(
() => executeTEAL(axfer),
RUNTIME_ERRORS.TRANSACTION.ASA_NOT_OPTIN
);
});
it(`should test ASA optin, asa transfer`, function () {
const optin = `
itxn_begin
int axfer
itxn_field TypeEnum
int 9
itxn_field XferAsset
int 0
itxn_field AssetAmount
global CurrentApplicationAddress
itxn_field AssetReceiver
itxn_submit
int 1
`;
// does not exist
expectRuntimeError(
() => executeTEAL(optin),
RUNTIME_ERRORS.ASA.ASSET_NOT_FOUND
);
let assetID = 0;
const elonAcc = interpreter.runtime.ctx.state.accounts.get(elonAddr);
if (elonAcc) {
assetID = interpreter.runtime.ctx.deployASADef(
'test-asa',
{ total: 10, decimals: 0, unitName: "TASA" },
elonAddr,
{ creator: { ...elonAcc.account, name: 'elon' } }
).assetID;
}
// passes
assert.doesNotThrow(() => executeTEAL(optin));
// opted in, but balance=0
expectRuntimeError(
() => executeTEAL(axfer),
RUNTIME_ERRORS.TRANSACTION.INSUFFICIENT_ACCOUNT_ASSETS
);
// increase asa balance to 5
const holding = interpreter.runtime.ctx.state.accounts.get(appAccAddr)?.getAssetHolding(assetID);
if (holding) { holding.amount = 5n; }
executeTEAL(axfer);
executeTEAL(axfer);
expectRuntimeError(
() => executeTEAL(axfer), // already withdrawn 4, cannot withdraw 2 more
RUNTIME_ERRORS.TRANSACTION.INSUFFICIENT_ACCOUNT_ASSETS
);
const verifyHolding = `
global CurrentApplicationAddress
int 1
asset_holding_get AssetBalance
assert
int 1
==
`;
// verify ASA transfer
assert.doesNotThrow(() => executeTEAL(verifyHolding));
});
it(`should test ASA close`, function () {
const close = `
itxn_begin
int axfer
itxn_field TypeEnum
int 1
itxn_field XferAsset
int 0
itxn_field AssetAmount
txn Sender
itxn_field AssetReceiver
txn Sender
itxn_field AssetCloseTo
itxn_submit
int 1
`;
assert.doesNotThrow(() => executeTEAL(close));
const verifyClose = `
global CurrentApplicationAddress
int 1
asset_holding_get AssetBalance
!
assert
!
`;
// verify ASA close
assert.doesNotThrow(() => executeTEAL(verifyClose));
});
});
describe("TestAppAxfer", function () {
let axfer: string;
let assetID1: number;
let assetID2: number;
this.beforeAll(() => {
const elonAcc = interpreter.runtime.ctx.state.accounts.get(elonAddr);
if (elonAcc) {
// in foreign-assets
assetID1 = interpreter.runtime.ctx.deployASADef(
'test-asa-1',
{ total: 11, decimals: 0, unitName: "TASA1" },
elonAddr,
{ creator: { ...elonAcc.account, name: 'elon' } }
).assetID;
// not in foreign-assets
assetID2 = interpreter.runtime.ctx.deployASADef(
'test-asa-2',
{ total: 22, decimals: 0, unitName: "TASA2" },
elonAddr,
{ creator: { ...elonAcc.account, name: 'elon' } }
).assetID;
}
axfer = `
itxn_begin
int ${assetID1}
itxn_field XferAsset
itxn_field AssetAmount
itxn_field AssetReceiver
itxn_field Sender
int axfer
itxn_field TypeEnum
itxn_submit
`;
TXN_OBJ.apas = [assetID1];
});
it(`should fail: invalid ASA Ref`, function () {
const teal = `
txn Sender
int ${assetID2}
asset_holding_get AssetBalance
assert
int 0
==
`;
expectRuntimeError(
() => executeTEAL(teal),
RUNTIME_ERRORS.TEAL.INVALID_ASA_REFERENCE
);
});
it(`should fail: Sender not opted-in`, function () {
const teal = `
txn Accounts 1
int ${assetID1}
asset_holding_get AssetBalance
assert
int 0
==
`;
// assert failed
expectRuntimeError(
() => executeTEAL(teal),
RUNTIME_ERRORS.TEAL.TEAL_ENCOUNTERED_ERR
);
});
it(`should fail: app account not opted in`, function () {
const teal = `
global CurrentApplicationAddress
int ${assetID1}
asset_holding_get AssetBalance
assert
int 0
==
`;
// assert failed
expectRuntimeError(
() => executeTEAL(teal),
RUNTIME_ERRORS.TEAL.TEAL_ENCOUNTERED_ERR
);
});
it(`should create new holding in appAccount`, function () {
interpreter.runtime.ctx.optIntoASA(assetID1, appAccAddr, {});
// increase asa balance to 5
const holding =
interpreter.runtime.ctx.state.accounts.get(appAccAddr)?.getAssetHolding(assetID1);
if (holding) { holding.amount = 3000n; }
const verifyHolding = `
global CurrentApplicationAddress
int ${assetID1}
asset_holding_get AssetBalance
assert
int 3000
==
`;
assert.doesNotThrow(() => executeTEAL(verifyHolding));
});
it(`should fail: receiver not optedin`, function () {
TXN_OBJ.apat = [Buffer.from(decodeAddress(johnAddr).publicKey)];
const teal = `
global CurrentApplicationAddress
txn Accounts 1
int 100
` + axfer;
expectRuntimeError(
() => executeTEAL(teal),
RUNTIME_ERRORS.TRANSACTION.ASA_NOT_OPTIN
);
});
it(`should fail: insufficient balance`, function () {
// optin by txn Account1
interpreter.runtime.ctx.optIntoASA(assetID1, johnAddr, {});
const teal = `
global CurrentApplicationAddress
txn Accounts 1
int 100000
` + axfer;
expectRuntimeError(
() => executeTEAL(teal),
RUNTIME_ERRORS.TRANSACTION.INSUFFICIENT_ACCOUNT_ASSETS
);
});
it(`should fail: invalid asset reference for app account`, function () {
// changing to random
TXN_OBJ.apas = [1211, 323];
const teal = `
global CurrentApplicationAddress
txn Accounts 1
int 100000
` + axfer;
expectRuntimeError(
() => executeTEAL(teal),
RUNTIME_ERRORS.TEAL.INVALID_ASA_REFERENCE
);
TXN_OBJ.apas = [assetID1]; // restore
});
it(`should fail: asset id not passed`, function () {
const noid = `
global CurrentApplicationAddress
txn Accounts 1
int 100
itxn_begin
itxn_field AssetAmount
itxn_field AssetReceiver
itxn_field Sender
int axfer
itxn_field TypeEnum
itxn_submit
int 1
`;
// defaults to 0, which is not opted in
expectRuntimeError(
() => executeTEAL(noid),
RUNTIME_ERRORS.TRANSACTION.ASA_NOT_OPTIN
);
});
it(`should pass: inner transaction axfer`, function () {
const teal = `
global CurrentApplicationAddress
txn Accounts 1
int 100
` + axfer + `
int 1
`;
assert.doesNotThrow(() => executeTEAL(teal));
// 100 spent by app
const verifySenderBalCode = `
global CurrentApplicationAddress
int ${assetID1}
asset_holding_get AssetBalance
assert
int 2900
==
`;
assert.doesNotThrow(() => executeTEAL(verifySenderBalCode));
// 100 received by txn.accounts 1
const verifyReceiverBalCode = `
txn Accounts 1
int ${assetID1}
asset_holding_get AssetBalance
assert
int 100
==
`;
assert.doesNotThrow(() => executeTEAL(verifyReceiverBalCode));
});
});
describe("TestBadField", () => {
it(`should fail if fields are invalid`, function () {
const pay = `
global CurrentApplicationAddress
txn Accounts 1
int 100
itxn_begin
int 7
itxn_field AssetAmount
itxn_field Amount
itxn_field Receiver
itxn_field Sender
int pay
itxn_field TypeEnum
txn Receiver
// NOT ALLOWED
itxn_field RekeyTo
itxn_submit
`;
expectRuntimeError(
() => executeTEAL(pay),
RUNTIME_ERRORS.TEAL.ITXN_FIELD_ERR
);
});
});
describe("TestNumInner", () => {
it(`should fail number of inner transactions > 16`, function () {
const pay = `
itxn_begin
int 1
itxn_field Amount
txn Accounts 1
itxn_field Receiver
int pay
itxn_field TypeEnum
itxn_submit
`;
assert.doesNotThrow(() => executeTEAL(pay + `int 1`));
assert.doesNotThrow(() => executeTEAL(pay + pay + `int 1`));
assert.doesNotThrow(() => executeTEAL(pay + pay + pay + pay + pay + pay + pay + pay + `int 1`));
let heavyCode = ``;
for (let i = 0; i <= 17; ++i) { heavyCode += pay; }
expectRuntimeError(
() => executeTEAL(heavyCode),
RUNTIME_ERRORS.GENERAL.MAX_INNER_TRANSACTIONS_EXCEEDED
);
});
});
describe("TestAssetCreate", () => {
it(`should test asset creation inner transaction`, function () {
const create = `
itxn_begin
int acfg
itxn_field TypeEnum
int 1000000
itxn_field ConfigAssetTotal
int 3
itxn_field ConfigAssetDecimals
byte "oz"
itxn_field ConfigAssetUnitName
byte "Gold"
itxn_field ConfigAssetName
byte "https://gold.rush/"
itxn_field ConfigAssetURL
itxn_submit
int 1
`;
assert.doesNotThrow(() => executeTEAL(create));
});
});
describe("TestAssetFreeze", () => {
it(`should test asset freeze inner transaction (flow test)`, function () {
const lastAssetID = interpreter.runtime.ctx.createdAssetID;
const create = `
itxn_begin
int acfg
itxn_field TypeEnum
int 1000000
itxn_field ConfigAssetTotal
int 3
itxn_field ConfigAssetDecimals
byte "oz"
itxn_field ConfigAssetUnitName
byte "Gold"
itxn_field ConfigAssetName
byte "https://gold.rush/"
itxn_field ConfigAssetURL
global CurrentApplicationAddress
itxn_field ConfigAssetFreeze
itxn_submit
int 1
`;
assert.doesNotThrow(() => executeTEAL(create));
const createdAssetID = interpreter.runtime.ctx.createdAssetID;
assert.equal(createdAssetID, lastAssetID + 1);
const freeze = `
itxn_begin
int afrz
itxn_field TypeEnum
int ${createdAssetID}
itxn_field FreezeAsset
txn ApplicationArgs 0
btoi
itxn_field FreezeAssetFrozen
txn Accounts 1
itxn_field FreezeAssetAccount
itxn_submit
int 1
`;
TXN_OBJ.apas = [];
expectRuntimeError(
() => executeTEAL(freeze),
RUNTIME_ERRORS.TEAL.INVALID_ASA_REFERENCE
);
TXN_OBJ.apas = [createdAssetID];
TXN_OBJ.apaa = [Buffer.from(new Uint8Array([1]))];
// does not hold Asset
expectRuntimeError(
() => executeTEAL(freeze),
RUNTIME_ERRORS.TRANSACTION.ASA_NOT_OPTIN
);
// should freeze now
interpreter.runtime.optIntoASA(createdAssetID, johnAddr, {});
assert.doesNotThrow(() => executeTEAL(freeze));
// verify freeze
let johnHolding = interpreter.runtime.getAssetHolding(createdAssetID, johnAddr);
assert.isDefined(johnHolding);
assert.equal(johnHolding["is-frozen"], true);
// unfreeze
TXN_OBJ.apaa = [Buffer.from(new Uint8Array([0]))];
assert.doesNotThrow(() => executeTEAL(freeze));
// verify unfreeze
johnHolding = interpreter.runtime.getAssetHolding(createdAssetID, johnAddr);
assert.equal(johnHolding["is-frozen"], false);
});
});
describe("Log", () => {
it(`should log bytes to current transaction receipt`, function () {
const txnInfo = interpreter.runtime.getTxReceipt(TXN_OBJ.txID);
assert.isUndefined(txnInfo?.logs); // no logs before
const log = `#pragma version 5
int 1
// log 30 times "a"
loop:
byte "a"
log
int 1
+
dup
int 30
<=
bnz loop
byte "b"
log
byte "c"
log
`;
assert.doesNotThrow(() => executeTEAL(log));
const logs = interpreter.runtime.getTxReceipt(TXN_OBJ.txID)?.logs as string[];
assert.isDefined(logs);
for (let i = 0; i < 30; ++i) { assert.equal(logs[i], "a"); }
assert.equal(logs[30], "b");
assert.equal(logs[31], "c");
});
it(`should throw error if log count exceeds threshold`, function () {
const log = `#pragma version 5
int 1
// log 33 times "a" (exceeds threshold of 32)
loop:
byte "a"
log
int 1
+
dup
int 33
<=
bnz loop
byte "b"
log
byte "c"
log
`;
expectRuntimeError(
() => executeTEAL(log),
RUNTIME_ERRORS.TEAL.LOGS_COUNT_EXCEEDED_THRESHOLD
);
});
it(`should throw error if logs "length" exceeds threshold`, function () {
const log = `#pragma version 5
int 1
// too long
loop:
byte "abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd"
log
int 1
+
dup
int 30
<=
bnz loop
byte "b"
log
byte "c"
log
`;
expectRuntimeError(
() => executeTEAL(log),
RUNTIME_ERRORS.TEAL.LOGS_LENGTH_EXCEEDED_THRESHOLD
);
});
});
}); | the_stack |
import { expect } from 'chai';
import debug from 'debug';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: No types available
import TCP from 'libp2p-tcp';
import {
makeLogFileName,
NimWaku,
NOISE_KEY_1,
NOISE_KEY_2,
} from '../../test_utils';
import { delay } from '../delay';
import { DefaultPubSubTopic, Waku } from '../waku';
import { WakuMessage } from '../waku_message';
const log = debug('waku:test');
const TestContentTopic = '/test/1/waku-relay/utf8';
describe('Waku Relay [node only]', () => {
// Node needed as we don't have a way to connect 2 js waku
// nodes in the browser yet
describe('2 js nodes', () => {
afterEach(function () {
if (this.currentTest?.state === 'failed') {
console.log(`Test failed, log file name is ${makeLogFileName(this)}`);
}
});
let waku1: Waku;
let waku2: Waku;
beforeEach(async function () {
this.timeout(10000);
log('Starting JS Waku instances');
[waku1, waku2] = await Promise.all([
Waku.create({ staticNoiseKey: NOISE_KEY_1 }),
Waku.create({
staticNoiseKey: NOISE_KEY_2,
libp2p: { addresses: { listen: ['/ip4/0.0.0.0/tcp/0/ws'] } },
}),
]);
log("Instances started, adding waku2 to waku1's address book");
waku1.addPeerToAddressBook(waku2.libp2p.peerId, waku2.libp2p.multiaddrs);
log('Wait for mutual pubsub subscription');
await Promise.all([
new Promise((resolve) =>
waku1.libp2p.pubsub.once('pubsub:subscription-change', () =>
resolve(null)
)
),
new Promise((resolve) =>
waku2.libp2p.pubsub.once('pubsub:subscription-change', () =>
resolve(null)
)
),
]);
log('before each hook done');
});
afterEach(async function () {
this.timeout(5000);
await waku1.stop();
await waku2.stop();
});
it('Subscribe', async function () {
log('Getting subscribers');
const subscribers1 =
waku1.libp2p.pubsub.getSubscribers(DefaultPubSubTopic);
const subscribers2 =
waku2.libp2p.pubsub.getSubscribers(DefaultPubSubTopic);
log('Asserting mutual subscription');
expect(subscribers1).to.contain(waku2.libp2p.peerId.toB58String());
expect(subscribers2).to.contain(waku1.libp2p.peerId.toB58String());
});
it('Register correct protocols', async function () {
const protocols = Array.from(waku1.libp2p.upgrader.protocols.keys());
expect(protocols).to.contain('/vac/waku/relay/2.0.0');
expect(protocols.findIndex((value) => value.match(/sub/))).to.eq(-1);
});
it('Publish', async function () {
this.timeout(10000);
const messageText = 'JS to JS communication works';
const messageTimestamp = new Date('1995-12-17T03:24:00');
const message = await WakuMessage.fromUtf8String(
messageText,
TestContentTopic,
{
timestamp: messageTimestamp,
}
);
const receivedMsgPromise: Promise<WakuMessage> = new Promise(
(resolve) => {
waku2.relay.addObserver(resolve);
}
);
await waku1.relay.send(message);
const receivedMsg = await receivedMsgPromise;
expect(receivedMsg.contentTopic).to.eq(message.contentTopic);
expect(receivedMsg.version).to.eq(message.version);
expect(receivedMsg.payloadAsUtf8).to.eq(messageText);
expect(receivedMsg.timestamp?.valueOf()).to.eq(
messageTimestamp.valueOf()
);
});
it('Filter on content topics', async function () {
this.timeout(10000);
const fooMessageText = 'Published on content topic foo';
const barMessageText = 'Published on content topic bar';
const fooMessage = await WakuMessage.fromUtf8String(
fooMessageText,
'foo'
);
const barMessage = await WakuMessage.fromUtf8String(
barMessageText,
'bar'
);
const receivedBarMsgPromise: Promise<WakuMessage> = new Promise(
(resolve) => {
waku2.relay.addObserver(resolve, ['bar']);
}
);
const allMessages: WakuMessage[] = [];
waku2.relay.addObserver((wakuMsg) => {
allMessages.push(wakuMsg);
});
await waku1.relay.send(fooMessage);
await waku1.relay.send(barMessage);
const receivedBarMsg = await receivedBarMsgPromise;
expect(receivedBarMsg.contentTopic).to.eq(barMessage.contentTopic);
expect(receivedBarMsg.version).to.eq(barMessage.version);
expect(receivedBarMsg.payloadAsUtf8).to.eq(barMessageText);
expect(allMessages.length).to.eq(2);
expect(allMessages[0].contentTopic).to.eq(fooMessage.contentTopic);
expect(allMessages[0].version).to.eq(fooMessage.version);
expect(allMessages[0].payloadAsUtf8).to.eq(fooMessageText);
expect(allMessages[1].contentTopic).to.eq(barMessage.contentTopic);
expect(allMessages[1].version).to.eq(barMessage.version);
expect(allMessages[1].payloadAsUtf8).to.eq(barMessageText);
});
it('Delete observer', async function () {
this.timeout(10000);
const messageText =
'Published on content topic with added then deleted observer';
const message = await WakuMessage.fromUtf8String(
messageText,
'added-then-deleted-observer'
);
// The promise **fails** if we receive a message on this observer.
const receivedMsgPromise: Promise<WakuMessage> = new Promise(
(resolve, reject) => {
waku2.relay.addObserver(reject, ['added-then-deleted-observer']);
waku2.relay.deleteObserver(reject, ['added-then-deleted-observer']);
setTimeout(resolve, 500);
}
);
await waku1.relay.send(message);
await receivedMsgPromise;
// If it does not throw then we are good.
});
});
describe('Custom pubsub topic', () => {
it('Publish', async function () {
this.timeout(10000);
const pubSubTopic = '/some/pubsub/topic';
// 1 and 2 uses a custom pubsub
const [waku1, waku2, waku3] = await Promise.all([
Waku.create({
pubSubTopic: pubSubTopic,
staticNoiseKey: NOISE_KEY_1,
}),
Waku.create({
pubSubTopic: pubSubTopic,
staticNoiseKey: NOISE_KEY_2,
libp2p: { addresses: { listen: ['/ip4/0.0.0.0/tcp/0/ws'] } },
}),
Waku.create({
staticNoiseKey: NOISE_KEY_2,
}),
]);
waku1.addPeerToAddressBook(waku2.libp2p.peerId, waku2.libp2p.multiaddrs);
waku3.addPeerToAddressBook(waku2.libp2p.peerId, waku2.libp2p.multiaddrs);
await Promise.all([
new Promise((resolve) =>
waku1.libp2p.pubsub.once('pubsub:subscription-change', () =>
resolve(null)
)
),
new Promise((resolve) =>
waku2.libp2p.pubsub.once('pubsub:subscription-change', () =>
resolve(null)
)
),
// No subscription change expected for Waku 3
]);
const messageText = 'Communicating using a custom pubsub topic';
const message = await WakuMessage.fromUtf8String(
messageText,
TestContentTopic
);
const waku2ReceivedMsgPromise: Promise<WakuMessage> = new Promise(
(resolve) => {
waku2.relay.addObserver(resolve);
}
);
// The promise **fails** if we receive a message on the default
// pubsub topic.
const waku3NoMsgPromise: Promise<WakuMessage> = new Promise(
(resolve, reject) => {
waku3.relay.addObserver(reject);
setTimeout(resolve, 1000);
}
);
await waku1.relay.send(message);
const waku2ReceivedMsg = await waku2ReceivedMsgPromise;
await waku3NoMsgPromise;
expect(waku2ReceivedMsg.payloadAsUtf8).to.eq(messageText);
});
});
describe('Interop: Nim', function () {
describe('Nim connects to js', function () {
let waku: Waku;
let nimWaku: NimWaku;
beforeEach(async function () {
this.timeout(30_000);
log('Create waku node');
waku = await Waku.create({
staticNoiseKey: NOISE_KEY_1,
libp2p: {
addresses: { listen: ['/ip4/0.0.0.0/tcp/0'] },
modules: { transport: [TCP] },
},
});
const multiAddrWithId = waku.getLocalMultiaddrWithID();
nimWaku = new NimWaku(makeLogFileName(this));
log('Starting nim-waku');
await nimWaku.start({ staticnode: multiAddrWithId });
log('Waiting for heartbeat');
await new Promise((resolve) =>
waku.libp2p.pubsub.once('gossipsub:heartbeat', resolve)
);
});
afterEach(async function () {
this.timeout(5000);
nimWaku ? nimWaku.stop() : null;
waku ? await waku.stop() : null;
});
it('nim subscribes to js', async function () {
const nimPeerId = await nimWaku.getPeerId();
const subscribers =
waku.libp2p.pubsub.getSubscribers(DefaultPubSubTopic);
expect(subscribers).to.contain(nimPeerId.toB58String());
});
it('Js publishes to nim', async function () {
this.timeout(5000);
const messageText = 'This is a message';
const message = await WakuMessage.fromUtf8String(
messageText,
TestContentTopic
);
await waku.relay.send(message);
let msgs: WakuMessage[] = [];
while (msgs.length === 0) {
await delay(200);
msgs = await nimWaku.messages();
}
expect(msgs[0].contentTopic).to.equal(message.contentTopic);
expect(msgs[0].version).to.equal(message.version);
expect(msgs[0].payloadAsUtf8).to.equal(messageText);
});
it('Nim publishes to js', async function () {
this.timeout(5000);
const messageText = 'Here is another message.';
const message = await WakuMessage.fromUtf8String(
messageText,
TestContentTopic
);
const receivedMsgPromise: Promise<WakuMessage> = new Promise(
(resolve) => {
waku.relay.addObserver(resolve);
}
);
await nimWaku.sendMessage(message);
const receivedMsg = await receivedMsgPromise;
expect(receivedMsg.contentTopic).to.eq(message.contentTopic);
expect(receivedMsg.version).to.eq(message.version);
expect(receivedMsg.payloadAsUtf8).to.eq(messageText);
});
});
describe('Js connects to nim', function () {
let waku: Waku;
let nimWaku: NimWaku;
beforeEach(async function () {
this.timeout(30_000);
waku = await Waku.create({
staticNoiseKey: NOISE_KEY_1,
libp2p: { modules: { transport: [TCP] } },
});
nimWaku = new NimWaku(this.test?.ctx?.currentTest?.title + '');
await nimWaku.start();
await waku.dial(await nimWaku.getMultiaddrWithId());
// Wait for identify protocol to finish
await new Promise((resolve) => {
waku.libp2p.peerStore.once('change:protocols', resolve);
});
// Wait for one heartbeat to ensure mesh is updated
await new Promise((resolve) => {
waku.libp2p.pubsub.once('gossipsub:heartbeat', resolve);
});
});
afterEach(async function () {
nimWaku ? nimWaku.stop() : null;
waku ? await waku.stop() : null;
});
it('nim subscribes to js', async function () {
let subscribers: string[] = [];
while (subscribers.length === 0) {
await delay(200);
subscribers = waku.libp2p.pubsub.getSubscribers(DefaultPubSubTopic);
}
const nimPeerId = await nimWaku.getPeerId();
expect(subscribers).to.contain(nimPeerId.toB58String());
});
it('Js publishes to nim', async function () {
this.timeout(30000);
const messageText = 'This is a message';
const message = await WakuMessage.fromUtf8String(
messageText,
TestContentTopic
);
await delay(1000);
await waku.relay.send(message);
let msgs: WakuMessage[] = [];
while (msgs.length === 0) {
console.log('Waiting for messages');
await delay(200);
msgs = await nimWaku.messages();
}
expect(msgs[0].contentTopic).to.equal(message.contentTopic);
expect(msgs[0].version).to.equal(message.version);
expect(msgs[0].payloadAsUtf8).to.equal(messageText);
});
it('Nim publishes to js', async function () {
await delay(200);
const messageText = 'Here is another message.';
const message = await WakuMessage.fromUtf8String(
messageText,
TestContentTopic
);
const receivedMsgPromise: Promise<WakuMessage> = new Promise(
(resolve) => {
waku.relay.addObserver(resolve);
}
);
await nimWaku.sendMessage(message);
const receivedMsg = await receivedMsgPromise;
expect(receivedMsg.contentTopic).to.eq(message.contentTopic);
expect(receivedMsg.version).to.eq(message.version);
expect(receivedMsg.payloadAsUtf8).to.eq(messageText);
});
});
describe.skip('js to nim to js', function () {
let waku1: Waku;
let waku2: Waku;
let nimWaku: NimWaku;
afterEach(async function () {
nimWaku ? nimWaku.stop() : null;
await Promise.all([
waku1 ? await waku1.stop() : null,
waku2 ? await waku2.stop() : null,
]);
});
it('Js publishes, other Js receives', async function () {
this.timeout(60_000);
[waku1, waku2] = await Promise.all([
Waku.create({
staticNoiseKey: NOISE_KEY_1,
libp2p: { modules: { transport: [TCP] } },
}),
Waku.create({
staticNoiseKey: NOISE_KEY_2,
libp2p: { modules: { transport: [TCP] } },
}),
]);
nimWaku = new NimWaku(makeLogFileName(this));
await nimWaku.start();
const nimWakuMultiaddr = await nimWaku.getMultiaddrWithId();
await Promise.all([
waku1.dial(nimWakuMultiaddr),
waku2.dial(nimWakuMultiaddr),
]);
// Wait for identify protocol to finish
await Promise.all([
new Promise((resolve) =>
waku1.libp2p.peerStore.once('change:protocols', resolve)
),
new Promise((resolve) =>
waku2.libp2p.peerStore.once('change:protocols', resolve)
),
]);
await Promise.all([
new Promise((resolve) =>
waku1.libp2p.pubsub.once('gossipsub:heartbeat', resolve)
),
new Promise((resolve) =>
waku2.libp2p.pubsub.once('gossipsub:heartbeat', resolve)
),
]);
await delay(2000);
// Check that the two JS peers are NOT directly connected
expect(
waku1.libp2p.peerStore.peers.has(waku2.libp2p.peerId.toB58String())
).to.be.false;
expect(
waku2.libp2p.peerStore.peers.has(waku1.libp2p.peerId.toB58String())
).to.be.false;
const msgStr = 'Hello there!';
const message = await WakuMessage.fromUtf8String(
msgStr,
TestContentTopic
);
const waku2ReceivedMsgPromise: Promise<WakuMessage> = new Promise(
(resolve) => {
waku2.relay.addObserver(resolve);
}
);
await waku1.relay.send(message);
console.log('Waiting for message');
const waku2ReceivedMsg = await waku2ReceivedMsgPromise;
expect(waku2ReceivedMsg.payloadAsUtf8).to.eq(msgStr);
});
});
});
}); | the_stack |
import playerAPI from '../../core/player-api-decorator';
import { VideoEvent } from '../../constants';
import {
IPlaybackEngineAPI,
IPlaybackEngine,
IPlaybackEngineDependencies,
IVideoOutput,
PlayableMediaSource,
CrossOriginValue,
PreloadType,
IEngineDebugInfo,
} from './types';
import { IEventEmitter } from '../event-emitter/types';
import { IPlayerConfig } from '../../core/config';
//TODO: Find source of problem with native HLS on Safari, when playing state triggered but actual playing is delayed
class Engine implements IPlaybackEngine {
static moduleName = 'engine';
static dependencies = ['eventEmitter', 'config', 'nativeOutput'];
private _eventEmitter: IEventEmitter;
private _config: IPlayerConfig;
private _output: IVideoOutput;
private _defaultOutput: IVideoOutput;
constructor({
eventEmitter,
nativeOutput,
config,
}: IPlaybackEngineDependencies) {
this._eventEmitter = eventEmitter;
this._config = config;
this._defaultOutput = nativeOutput;
this._output = nativeOutput;
this._applyConfig(this._config);
}
private _applyConfig(config: IPlayerConfig = {}) {
const {
preload,
autoplay,
loop,
muted,
volume,
playsinline,
crossOrigin,
src,
} = config;
this.setPreload(preload);
this.setAutoplay(autoplay);
this.setLoop(loop);
this.setMute(muted);
this.setVolume(volume);
this.setPlaysinline(playsinline);
this.setCrossOrigin(crossOrigin);
if (src) {
this.setSrc(src);
}
}
getElement() {
return this._output.getElement();
}
get isDynamicContent() {
return this._output.isDynamicContent;
}
get isDynamicContentEnded() {
return this._output.isDynamicContentEnded;
}
get isSeekAvailable() {
return this._output.isSeekAvailable;
}
get isMetadataLoaded() {
return this._output.isMetadataLoaded;
}
get isPreloadActive() {
return this._output.isPreloadActive;
}
get isAutoPlayActive() {
return this._output.isAutoPlayActive;
}
get isSyncWithLive(): boolean {
return this._output.isSyncWithLive;
}
/**
* Method for setting source of video to player.
* @param src Array with multiple sources
* @param callback
* @example
* player.setSrc([
* 'https://my-url/video.mp4',
* 'https://my-url/video.webm',
* 'https://my-url/video.m3u8'
* ]);
* @note
* Read more about [video source](/video-source)
*/
@playerAPI()
setSrc(src: PlayableMediaSource, callback?: Function) {
if (src === this.getSrc()) {
return;
}
this._output.setSrc(src, callback);
}
/**
* Return current source of video
* @example
* player.getSrc(); // ['https://my-url/video.mp4']
*/
@playerAPI()
getSrc(): PlayableMediaSource {
return this._output.src;
}
@playerAPI()
reset() {
this.pause();
this.seekTo(0);
this._eventEmitter.emitAsync(VideoEvent.RESET);
}
/**
* Start playback
* @example
* player.play();
*/
@playerAPI()
play() {
this._output.play();
}
/**
* Pause playback
* @example
* player.pause();
*/
@playerAPI()
pause() {
this._output.pause();
}
/**
* Toggle (play\pause) playback of video
* @example
* player.togglePlayback();
*/
@playerAPI()
togglePlayback() {
if (this.isPaused) {
this.play();
} else {
this.pause();
}
}
/**
* Reset video playback
* @example
* player.play();
* console.log(player.isPaused); // false
* ...
* player.resetPlayback();
* console.log(player.isPaused); // true;
* console.log(player.getCurrentTime()); //0;
*/
@playerAPI()
resetPlayback() {
this.pause();
this.seekTo(0);
this._eventEmitter.emitAsync(VideoEvent.RESET);
}
/**
* High level state of video playback. Returns true if playback is paused.
* For more advance state use `getPlaybackState`
* @example
* player.play();
* console.log(player.isPaused);
*/
@playerAPI()
get isPaused(): boolean {
return this._output.isPaused;
}
/**
* High level state of video playback. Returns true if playback is ended. Also note, that `isPaused` will return `true` if playback is ended also.
* For more advance state use `getPlaybackState`
* @example
* player.play();
* console.log(player.isEnded);
*/
@playerAPI()
get isEnded(): boolean {
return this._output.isEnded;
}
/**
* Method for synchronize current playback with live point. Available only if you playing live source.
* @example
* player.syncWithLive();
*/
@playerAPI()
syncWithLive() {
this._output.syncWithLive();
}
/**
* Method for going forward in playback by your value
* @param sec - Value in seconds
* @example
* player.seekForward(5);
*/
@playerAPI()
seekForward(sec: number) {
const duration = this.getDuration();
if (duration) {
const current = this.getCurrentTime();
this.seekTo(Math.min(current + sec, duration));
}
}
/**
* Method for going backward in playback by your value
* @param sec - Value in seconds
* @example
* player.seekBackward(5);
*/
@playerAPI()
seekBackward(sec: number) {
const duration = this.getDuration();
if (duration) {
const current = this.getCurrentTime();
this.seekTo(Math.max(current - sec, 0));
}
}
/**
* Set volume
* @param volume - Volume value `0..100`
* @example
* player.setVolume(50);
*/
@playerAPI()
setVolume(volume: number) {
const parsedVolume = Number(volume);
const newVolume = isNaN(parsedVolume)
? 1
: Math.max(0, Math.min(Number(volume) / 100, 1));
this._output.setVolume(newVolume);
}
/**
* Get volume
* @example
* player.getVolume(); // 50
*/
@playerAPI()
getVolume(): number {
return this._output.volume * 100;
}
/**
* Method for increasing current volume by value
* @param value - Value from 0 to 100
* @example
* player.increaseVolume(30);
*/
@playerAPI()
increaseVolume(value: number) {
this.setVolume(this.getVolume() + value);
}
/**
* Method for decreasing current volume by value
* @param value - Value from 0 to 100
* @example
* player.decreaseVolume(30);
*/
@playerAPI()
decreaseVolume(value: number) {
this.setVolume(this.getVolume() - value);
}
setMute(isMuted: boolean) {
this._output.setMute(isMuted);
}
/**
* Mute the video
* @example
* player.mute();
*/
@playerAPI()
mute() {
this.setMute(true);
}
/**
* Unmute the video
* @example
* player.unmute(true);
*/
@playerAPI()
unmute() {
this.setMute(false);
}
/**
* Get mute flag
* @example
* player.mute();
* player.isMuted; // true
* player.unmute();
* player.isMuted: // false
*/
@playerAPI()
get isMuted(): boolean {
return this._output.isMuted;
}
/**
* Set autoplay flag
* @example
* player.setAutoplay();
*/
@playerAPI()
setAutoplay(isAutoplay: boolean) {
this._output.setAutoplay(isAutoplay);
}
/**
* Get autoplay flag
* @example
* player.getAutoplay(); // true
*/
@playerAPI()
getAutoplay(): boolean {
return this._output.isAutoplay;
}
/**
* Set loop flag
* @param isLoop - If `true` video will be played again after it will finish
* @example
* player.setLoop(true);
*/
@playerAPI()
setLoop(isLoop: boolean) {
this._output.setLoop(isLoop);
}
/**
* Get loop flag
* @example
* player.getLoop(); // true
*/
@playerAPI()
getLoop(): boolean {
return this._output.isLoop;
}
/**
* Method for setting playback rate
*/
@playerAPI()
setPlaybackRate(rate: number) {
this._output.setPlaybackRate(rate);
}
/**
* Return current playback rate
*/
@playerAPI()
getPlaybackRate(): number {
return this._output.playbackRate;
}
/**
* Set preload type
* @example
* player.setPreload('none');
*/
@playerAPI()
setPreload(preload: PreloadType) {
this._output.setPreload(preload);
}
/**
* Return preload type
* @example
* player.getPreload(); // none
*/
@playerAPI()
getPreload(): string {
return this._output.preload;
}
/**
* Return current time of video playback
* @example
* player.getCurrentTime(); // 60.139683
*/
@playerAPI()
getCurrentTime(): number {
return this._output.currentTime;
}
/**
* Method for seeking to time in video
* @param time - Time in seconds
* @example
* player.seekTo(34);
*/
@playerAPI()
seekTo(time: number) {
this._output.setCurrentTime(time);
}
/**
* Return duration of video
* @example
* player.getDuration(); // 180.149745
*/
@playerAPI()
getDuration(): number {
return this._output.duration || 0;
}
/**
* Return real width of video from metadata
* @example
* player.getVideoWidth(); // 400
*/
@playerAPI('getVideoRealWidth')
getVideoWidth(): number {
return this._output.videoWidth;
}
/**
* Return real height of video from metadata
* @example
* player.getVideoHeight(); // 225
*/
@playerAPI('getVideoRealHeight')
getVideoHeight(): number {
return this._output.videoHeight;
}
getBuffered() {
return this._output.buffered;
}
/**
* Set playsinline flag
* @param isPlaysinline - If `false` - video will be played in full screen, `true` - inline
* @example
* player.setPlaysinline(true);
*/
@playerAPI()
setPlaysinline(isPlaysinline: boolean) {
this._output.setInline(isPlaysinline);
}
/**
* Get playsinline flag
* @example
* player.getPlaysinline(); // true
*/
@playerAPI()
getPlaysinline(): boolean {
return this._output.isInline;
}
/**
* Set crossorigin attribute for video
* @example
* player.setCrossOrigin('anonymous');
*/
@playerAPI()
setCrossOrigin(crossOrigin?: CrossOriginValue) {
this._output.setCrossOrigin(crossOrigin);
}
/**
* Get crossorigin attribute value for video
* @example
* player.getCrossOrigin(); // 'anonymous'
*/
@playerAPI()
getCrossOrigin(): CrossOriginValue {
return this._output.crossOrigin;
}
/**
* Return current state of playback
*/
@playerAPI('getPlaybackState')
getCurrentState() {
return this._output.currentState;
}
/**
* Return object with internal debug info
*
* @example
* player.getDebugInfo();
*
* @note
* The above command returns JSON structured like this:
*
* @example
* {
* "type": "HLS",
* "viewDimensions": {
* "width": 700,
* "height": 394
* }
* "url": "https://example.com/video.m3u8",
* "currentTime": 22.092514,
* "duration": 60.139683,
* "loadingStateTimestamps": {
* "metadata-loaded": 76,
* "ready-to-play": 67
* },
* "bitrates": [
* // Available bitrates
* "100000",
* "200000",
* ...
* ],
* // One of available bitrates, that used right now
* "currentBitrate": "100000",
* // Raw estimation of bandwidth, that could be used without playback stall
* "bwEstimate": "120000"
* "overallBufferLength": 60.139683,
* "nearestBufferSegInfo": {
* "start": 0,
* "end": 60.139683
* }
* }
*/
@playerAPI()
getDebugInfo(): IEngineDebugInfo {
return this._output.getDebugInfo();
}
destroy() {
// all dependencies are modules and will be destroyed from Player.destroy()
return;
}
changeOutput(output?: IVideoOutput, callback?: Function) {
const src = this.getSrc();
this._output.pause();
this._output = output;
this._applyConfig(this._config);
return this._output.setSrc(src, callback);
}
resetOutput(): void {
const wasPlaying = !this._output.isPaused;
const currentTime = this._output.currentTime;
this._output = this._defaultOutput;
this._output.setCurrentTime(currentTime);
if (wasPlaying) {
this._output.play();
}
}
}
export { IPlaybackEngineAPI };
export default Engine; | the_stack |
'use strict';
import vscode = require('vscode');
import { Uri, SymbolInformation, Position, Range, SymbolKind } from 'vscode';
import { LuaParse } from '../LuaParse'
import { LuaInfo, TokenInfo, TokenTypes, LuaComment, LuaRange, LuaErrorEnum, LuaError, LuaInfoType } from '../TokenInfo';
import { LuaFiledCompletionInfo } from "../provider/LuaFiledCompletionInfo"
import { LuaParseTool } from '../LuaParseTool';
import { CompletionItem, CompletionItemKind } from "vscode"
import { CLog, getFirstComments, getCurrentFunctionName, getComments, getSelfToModuleName, getTokens } from '../Utils'
import { LuaSymbolInformation } from "./LuaSymbolInformation"
import { ExtensionManager } from "../ex/ExtensionManager";
export class FileCompletionItemManager {
//当前解析方法名集合 在解析完毕后 会设置为null
public currentFunctionNames: Array<string> = null;
public currentFunctionParams: Array<Array<string>> = null;
public currentSymbolFunctionNames: Array<string> = null;
public uri: Uri;
public ModuleName:string = null;
//方法集合 用于 方法查找
public symbols: Array<LuaSymbolInformation> = null;
//临时值 解析完毕 会设置为null
public tokens: Array<TokenInfo> = null;
//解析0.2.3 之前会用到 后期 由luaFunFiledCompletions 替代
// public luaFiledCompletionInfo: LuaFiledCompletionInfo = null;
//记录当前文档的所有方法
public luaFunCompletionInfo: LuaFiledCompletionInfo = null;
//全局变量提示 这里在0.2.2 中继续了细化 将文件的全局 和整体全局 区分开来 luaGolbalCompletionInfo 为总体全局
//luaFileGolbalCompletionInfo 当前文件的全局变量 两者配合使用
public luaGolbalCompletionInfo: LuaFiledCompletionInfo = null;
//文件分为的全局变量 存储
public luaFileGolbalCompletionInfo: LuaFiledCompletionInfo = null;
//对每个方法中的的变量通过方法名进行存储 这样可以更加精确地进行提示 而不是整体对在体格completion中
public luaFunFiledCompletions: Map<string, LuaFiledCompletionInfo> = null;
//当前方法的Completion 与luaFunFiledCompletions 配合
private currentFunFiledCompletion: LuaFiledCompletionInfo = null;
//根据 文件中return 进行设置
public rootFunCompletionInfo: LuaFiledCompletionInfo = null;
public rootCompletionInfo: LuaFiledCompletionInfo = null;
public lp: LuaParse;
public constructor(uri: Uri) {
this.lp = LuaParse.lp;
this.currentFunctionNames = new Array<string>();
this.currentSymbolFunctionNames = new Array<string>();
this.currentFunctionParams = new Array<Array<string>>();
this.uri = uri;
this.luaFunCompletionInfo = new LuaFiledCompletionInfo("", CompletionItemKind.Class, uri, null, false);
this.luaGolbalCompletionInfo = new LuaFiledCompletionInfo("", CompletionItemKind.Class, uri, null, false);
this.luaFileGolbalCompletionInfo = new LuaFiledCompletionInfo("", CompletionItemKind.Class, uri, null, false);
this.symbols = new Array<LuaSymbolInformation>();
this.luaFunFiledCompletions = new Map<string, LuaFiledCompletionInfo>();
}
public clear() {
this.luaFunCompletionInfo.clearItems();
this.luaGolbalCompletionInfo.clearItems();
this.luaFileGolbalCompletionInfo.clearItems;
this.currentFunctionParams = null;
this.symbols = null
this.luaFunFiledCompletions.clear()
this.rootCompletionInfo = null
this.rootFunCompletionInfo = null
this.currentFunFiledCompletion = null
this.tokens = null
}
//设置根 用于类型推断
public setRootCompletionInfo(rootName: string) {
this.rootCompletionInfo = this.luaFileGolbalCompletionInfo.getItemByKey(rootName)
if (this.rootCompletionInfo == null) {
this.rootCompletionInfo = this.luaGolbalCompletionInfo.getItemByKey(rootName)
}
this.rootFunCompletionInfo = this.luaFunCompletionInfo.getItemByKey(rootName)
}
/**
* 添加方法开始 标记
* @param funName 方法名称
*/
public setBeginFunName(funName: string, params: Array<string>) {
var luaCompletion: LuaFiledCompletionInfo = new LuaFiledCompletionInfo("", CompletionItemKind.Function, this.lp.tempUri, null, false)
this.currentSymbolFunctionNames.push(funName)
this.currentFunctionParams.push(params)
if (this.currentFunFiledCompletion) {
funName = this.currentFunFiledCompletion.label + "->" + funName
//记录父方法的根
luaCompletion.funParentLuaCompletionInfo = this.currentFunFiledCompletion;
}
this.currentFunctionNames.push(funName)
luaCompletion.label = funName
this.luaFunFiledCompletions.set(funName, luaCompletion)
luaCompletion.completionFunName = funName
this.currentFunFiledCompletion = luaCompletion;
}
public setEndFun() {
this.currentSymbolFunctionNames.pop()
this.currentFunctionNames.pop()
this.currentFunctionParams.pop()
if (this.currentFunctionNames.length > 0) {
var funName = this.currentFunctionNames[this.currentFunctionNames.length - 1]
this.currentFunFiledCompletion = this.luaFunFiledCompletions.get(funName)
} else {
this.currentFunFiledCompletion = null;
}
}
public addFunctionCompletion(
lp: LuaParse,
luaInfo: LuaInfo,
token: TokenInfo,
functionEndToken: TokenInfo) {
var symbol: LuaSymbolInformation = this.addSymbol(lp, luaInfo, token, functionEndToken)
var completion: LuaFiledCompletionInfo = this.addCompletionItem(lp, luaInfo, token, this.tokens, true)
completion.completionFunName = symbol.name
var argsStr =""
var snippetStr = "";
for (var index = 0; index < symbol.argLuaFiledCompleteInfos.length; index++) {
var v = symbol.argLuaFiledCompleteInfos[index];
argsStr += v.label+","
snippetStr += "${"+ (index+1) +":"+ v.label +"},";
}
if(argsStr!=""){
argsStr = argsStr.substring(0,argsStr.length-1);
snippetStr = snippetStr.substring(0,snippetStr.length-1);
snippetStr = completion.label +"("+ snippetStr +")";
var snippetString: vscode.SnippetString = new vscode.SnippetString(snippetStr)
completion.funvSnippetString = snippetString
}
var funLabelStr= completion.label +"("+ argsStr +")";
completion.funLable = funLabelStr
this.checkFunAnnotationReturnValue(completion);
this.checkFunReturnValue(completion, token.index, functionEndToken.index)
}
public checkValueReferenceValue(completion:LuaFiledCompletionInfo)
{
if(completion.comments == null){return}
for (var index = 0; index < completion.comments.length; index++) {
var element = completion.comments[index];
var returnValue = "@valueReference"
var num = element.content.indexOf(returnValue)
if(num == 0){
var className = element.content.substring(returnValue.length).trim()
if(className[0] == "["){
var endIndex = className.indexOf("]")
className = className.substring(1,endIndex)
className = className.trim();
completion.valueReferenceModulePath = className;
break;
}
}
}
}
//检查父类引用
public checkParentClassValue(completion:LuaFiledCompletionInfo){
if(completion.comments == null){return}
for (var index = 0; index < completion.comments.length; index++) {
var element = completion.comments[index];
var returnValue = "@parentClass"
var num = element.content.indexOf(returnValue)
if(num == 0){
var className = element.content.substring(returnValue.length).trim()
if(className[0] == "["){
var endIndex = className.indexOf("]")
className = className.substring(1,endIndex)
className = className.trim();
completion.parentModulePath = className
}
}
}
}
//检查注释的返回值
public checkFunAnnotationReturnValue(completion: LuaFiledCompletionInfo){
if(completion.comments == null)return;
for (var index = 0; index < completion.comments.length; index++) {
var element = completion.comments[index];
var returnValue = "@return"
var num = element.content.indexOf(returnValue)
if(num == 0){
var className = element.content.substring(returnValue.length).trim()
if(className[0] == "["){
var endIndex = className.indexOf("]")
className = className.substring(1,endIndex)
className = className.trim();
// console.log(className)
completion.funAnnotationReturnValue = className
}
}
}
}
//检查返回值
public checkFunReturnValue(completion: LuaFiledCompletionInfo, startIndex: number, endTokenIndex: number) {
var index = startIndex;
while (index < endTokenIndex) {
var token: TokenInfo = this.tokens[index]
index++;
if (token.type == TokenTypes.Keyword && token.value == "return") {
var info = this.getCompletionValueKeys(this.tokens, index)
if (info) {
if (info == null || info.type == null) {
var xx = 1
}
if (info.type == 1) {
completion.addFunctionReturnCompletionKeys(completion.completionFunName, info.keys)
} else {
}
}
}
}
}
public getSymbolEndRange(functionName: string): vscode.Range {
var symbol: LuaSymbolInformation = null;
var range: vscode.Range;
for (var i = 0; i < this.symbols.length; i++) {
symbol = this.symbols[i]
if (!symbol.isLocal) {
if (symbol.name == functionName) {
var loc: vscode.Position = new Position(symbol.location.range.end.line + 1, 0)
range = new vscode.Range(
loc, loc)
break;
}
}
}
if (range == null && symbol != null) {
var loc: vscode.Position = new Position(symbol.location.range.end.line, symbol.location.range.end.character)
range = new vscode.Range(
loc, loc)
}
//没找到直接找最后
return range
}
public getSymbolArgsByNames(funNames: Array<string>): Array<LuaFiledCompletionInfo> {
var argLuaFiledCompleteInfos: Array<LuaFiledCompletionInfo> = new Array<LuaFiledCompletionInfo>()
for (var i = 0; i < this.symbols.length; i++) {
var symbol = this.symbols[i]
for (var j = 0; j < funNames.length; j++) {
var name = funNames[j];
if (symbol.name == name) {
for (var k = 0; k < symbol.argLuaFiledCompleteInfos.length; k++) {
var alc = symbol.argLuaFiledCompleteInfos[k];
argLuaFiledCompleteInfos.push(alc)
}
}
}
}
return argLuaFiledCompleteInfos;
}
public addSymbol(lp: LuaParse, luaInfo: LuaInfo, token: TokenInfo, functionEndToken: TokenInfo, symolName?: string): LuaSymbolInformation {
var parentName: string = "";
var tokens: Array<TokenInfo> = lp.tokens;
var starIndex: number = luaInfo.startToken.index;
var endIndex: number = token.index;
var label: string = "";
var symbolInfo = new LuaSymbolInformation(
token.value,
SymbolKind.Function,
new Range(
new Position(luaInfo.startToken.line, luaInfo.startToken.range.start),
new Position(functionEndToken.line, token.range.end)
),
undefined,
getFirstComments(luaInfo.getComments()));
var nindex: number = token.index;
while (true) {
nindex--;
var upToken: TokenInfo = tokens[nindex]
if (upToken == null) {
break;
}
nindex--;
if (
lp.consume(':', upToken, TokenTypes.Punctuator) ||
lp.consume('.', upToken, TokenTypes.Punctuator)) {
var mtokenInfo: TokenInfo = tokens[nindex];
symbolInfo.name = mtokenInfo.value + upToken.value + symbolInfo.name;
} else {
break;
}
}
if (symolName != null) {
symbolInfo.name = symolName;
}
if (this.currentSymbolFunctionNames.length == 0) {
symbolInfo.isLocal = false;
} else {
symbolInfo.isLocal = true;
var functionName = "";
this.currentSymbolFunctionNames.forEach(fname => {
if (functionName == "") {
functionName = fname;
} else {
functionName = functionName + "->" + fname;
}
});
symbolInfo.name = functionName + "->" + symbolInfo.name;
}
symbolInfo.initArgs(luaInfo.params, luaInfo.getComments())
this.symbols.push(symbolInfo)
return symbolInfo
}
private findLastSymbol(): LuaSymbolInformation {
for (var i = this.symbols.length - 1; i > 0; i--) {
var symbolInfo = this.symbols[i];
if (!symbolInfo.location) {
return symbolInfo;
}
}
return null
}
/**
* 添加itemm
*/
public addCompletionItem(lp: LuaParse, luaInfo: LuaInfo, token: TokenInfo, tokens: Array<TokenInfo>,
isFun: boolean = false,
isCheckValueRequire: boolean = false
): LuaFiledCompletionInfo {
this.lp = lp;
this.tokens = lp.tokens;
// console.log("line:"+luaInfo.startToken.line)
// console.log("line:"+luaInfo.startToken.value)
var starIndex: number = luaInfo.startToken.index;
var endIndex: number = token.index;
var label: string = "";
// console.log(starIndex,endIndex)
if (starIndex == endIndex) {
var singleToken: TokenInfo = this.tokens[starIndex];
if (singleToken.type == TokenTypes.NumericLiteral ||
singleToken.type == TokenTypes.BooleanLiteral ||
singleToken.type == TokenTypes.NilLiteral ||
singleToken.type == TokenTypes.StringLiteral
) {
// if(singleToken.type == TokenTypes.StringLiteral)
// {
// var item:LuaFiledCompletionInfo = new LuaFiledCompletionInfo(singleToken.value,CompletionItemKind.Text,lp.currentUri,new Position(singleToken.line,singleToken.lineStart))
// this.luaFiledCompletionInfo.addItem(item)
// }
return;
}
}
var stoken = this.tokens[starIndex]
if (
stoken.type == TokenTypes.NumericLiteral ||
stoken.type == TokenTypes.BooleanLiteral ||
stoken.type == TokenTypes.NilLiteral ||
stoken.type == TokenTypes.StringLiteral ||
stoken.type == TokenTypes.Punctuator
) {
return
}
if(stoken.value == "module"){
if(this.tokens.length >=starIndex +3){
if(this.tokens[starIndex+1].value == "("){
var moduleToken = this.tokens[starIndex+2]
if(moduleToken.type == TokenTypes.StringLiteral){
this.ModuleName = moduleToken.value;
var moduleCompletion = new LuaFiledCompletionInfo(this.ModuleName,CompletionItemKind.Field, lp.tempUri, new vscode.Position(moduleToken.line, moduleToken.lineStart), false);
this.luaGolbalCompletionInfo.addItem(moduleCompletion)
moduleCompletion.isNewVar = true
var moduleFunCompletion = new LuaFiledCompletionInfo(this.ModuleName,CompletionItemKind.Field, lp.tempUri, new vscode.Position(moduleToken.line, moduleToken.lineStart), false);
this.luaFunCompletionInfo.addItem(moduleFunCompletion)
moduleCompletion.isNewVar = true
moduleFunCompletion.isNewVar = true
this.rootCompletionInfo = moduleCompletion;
this.rootFunCompletionInfo = moduleFunCompletion;
return;
}
}
}
}
var startInfos: LuaFiledCompletionInfo = null
var infos: Array<CompletionItemSimpleInfo> = this.getCompletionKey(starIndex, endIndex);
if (infos == null || infos.length == 0) { return null }
var isCheckParentPath = false
var forindex: number = 0;
if (isFun) {
startInfos = this.luaFunCompletionInfo;
if(this.currentFunFiledCompletion != null){
startInfos = this.currentFunFiledCompletion;
}else if(this.ModuleName != null){
startInfos = startInfos.getItemByKey(this.ModuleName)
}
} else if (this.currentFunctionNames.length == 0) {
if (luaInfo.isLocal) {
startInfos = this.luaFileGolbalCompletionInfo
} else {
if (this.luaFileGolbalCompletionInfo.getItemByKey(infos[0].key) != null) {
startInfos = this.luaFileGolbalCompletionInfo
} else {
startInfos = this.luaGolbalCompletionInfo;
}
}
isCheckParentPath = true
}
else {
var data = null
if (infos[0].key == "self") {
data = getSelfToModuleName(this.tokens.slice(0, endIndex), this.lp)
}
if (data) {
var moduleName = data.moduleName
//找到self 属于谁
var golbalCompletion = this.luaFileGolbalCompletionInfo.getItemByKey(moduleName)
if (golbalCompletion == null) {
golbalCompletion = this.luaGolbalCompletionInfo.getItemByKey(moduleName)
}
if (golbalCompletion == null) {
var keyToken: TokenInfo = data.token
golbalCompletion = new LuaFiledCompletionInfo(moduleName, infos[0].kind, lp.tempUri,
new vscode.Position(keyToken.line, keyToken.lineStart), false)
this.luaGolbalCompletionInfo.addItem(golbalCompletion)
}
forindex = 1;
startInfos = golbalCompletion;
} else {
startInfos = this.currentFunFiledCompletion
if (luaInfo.isLocal == false) {
var key = ""
if (infos.length > 0) {
key = infos[0].key
}
var curName: string = ""
if (key != "") {
//判断是否为参数
for (var pi = 0; pi < this.currentFunctionParams.length; pi++) {
var argNames = this.currentFunctionParams[pi];
for (var ai = 0; ai < argNames.length; ai++) {
var paramsName = argNames[ai];
if (key == paramsName) {
curName = this.currentFunctionNames[pi]
break
}
}
if (curName != "") {
break
}
}
}
if (curName != "") {
startInfos = this.luaFunFiledCompletions.get(curName)
} else {
while (true) {
var completion: LuaFiledCompletionInfo = startInfos.getItemByKey(infos[0].key)
if (completion == null) {
if (startInfos.funParentLuaCompletionInfo) {
startInfos = startInfos.funParentLuaCompletionInfo
} else {
if (this.luaFileGolbalCompletionInfo.getItemByKey(infos[0].key)) {
startInfos = this.luaFileGolbalCompletionInfo
} else {
startInfos = this.luaGolbalCompletionInfo
}
break
}
} else {
break
}
}
}
}
}
}
// var golbalCompletionIsNew:boolean = true
// var isGolbal:boolean = false
// //如果为全局变量那么检查下是不是赋值 如果不是直接返回
// if (startInfos == this.luaGolbalCompletionInfo) {
// isGolbal = true
// var length = tokens.length
// var index = token.index + 1;
// var currentToken: TokenInfo = this.getValueToken(index, tokens)
// if (currentToken) {
// if (!(currentToken.type == TokenTypes.Punctuator && currentToken.value == "=")) {
// golbalCompletionIsNew = false
// }
// } else {
// golbalCompletionIsNew = false
// }
// }
// console.log(infos,"infos")
for (var i = forindex; i < infos.length; i++) {
var newStartInfos: LuaFiledCompletionInfo = null
var completion: LuaFiledCompletionInfo = startInfos.getItemByKey(infos[i].key)
if (completion == null) {
completion = new LuaFiledCompletionInfo(infos[i].key, infos[i].kind, lp.tempUri, infos[i].position, isFun)
startInfos.addItem(completion)
// completion.textEdit.newText = infos[i].insterStr;
if (isFun) {
completion.documentation = getFirstComments(infos[i].comments)
}
else {
completion.documentation = infos[i].desc;
}
completion.comments = infos[i].comments
if(isCheckParentPath && infos.length == 1){
this.checkParentClassValue(completion);
}
} else {
if (infos[i].desc && completion.isFun == false) {
completion.documentation = infos[i].desc
}
}
if(i == infos.length-1){
if(completion.isNewVar == false && endIndex+2 < tokens.length ){
if(lp.consume("=",tokens[endIndex+1],TokenTypes.Punctuator))
{
completion.isNewVar = true;
completion.position = infos[i].position
}
}
}
completion.setType(infos[i].tipTipType)
if (infos[i].nextInfo) {
var nextInfo: CompletionItemSimpleInfo = infos[i].nextInfo
var nextCompletion: LuaFiledCompletionInfo = completion.getItemByKey(nextInfo.key)
if (nextCompletion == null) {
nextCompletion = new LuaFiledCompletionInfo(nextInfo.key, nextInfo.kind, lp.tempUri, nextInfo.position, isFun);
nextCompletion.setType(1)
completion.addItem(nextCompletion);
}else{
var xx= 1;
}
newStartInfos = nextCompletion
} else {
newStartInfos = completion
}
startInfos = newStartInfos
}
if (luaInfo.type == LuaInfoType.Function) {
startInfos.params = luaInfo.params
startInfos.kind = CompletionItemKind.Function;
startInfos.isLocalFunction =luaInfo.isLocal;
var funKey = startInfos.label;
if(this.currentFunFiledCompletion != null){
funKey = this.currentFunFiledCompletion.label + "->" + funKey;
}
if(this.luaFunFiledCompletions.has(funKey)){
this.luaFunFiledCompletions.get(funKey).isLocalFunction = startInfos.isLocalFunction;
}
}
this.addTableFileds(luaInfo, startInfos, lp, isFun);
if (isCheckValueRequire) {
this.checkCompletionItemValueRequire(token, tokens, startInfos)
}
return startInfos
}
private addTableFileds(luaInfo: LuaInfo, startInfos: LuaFiledCompletionInfo, lp: LuaParse, isFun: boolean) {
//判断 luaInfo
if (luaInfo.tableFileds && luaInfo.tableFileds.length) {
var tableFileds: Array<LuaInfo> = luaInfo.tableFileds;
tableFileds.forEach(filed => {
if (!startInfos.getItemByKey(filed.name)) {
if (filed.tableFiledType == 0) {
var completion: LuaFiledCompletionInfo = new LuaFiledCompletionInfo(
filed.name, CompletionItemKind.Field, lp.tempUri,
new vscode.Position(filed.endToken.line, filed.endToken.lineStart), isFun);
completion.isNewVar = true;
startInfos.addItem(completion)
completion.setType(1)
this.addTableFileds(filed, completion, lp, isFun)
} else {
var completion: LuaFiledCompletionInfo = new LuaFiledCompletionInfo(
startInfos.label + filed.name,
CompletionItemKind.Field, lp.tempUri, new vscode.Position(filed.startToken.line, filed.startToken.lineStart), isFun);
startInfos.parent.addItem(completion)
// if (startInfos.parent == this.luaFiledCompletionInfo) {
// completion.setType(0)
// } else {
// completion.setType(1)
// }
this.addTableFileds(filed, completion, lp, isFun)
}
}
})
}
}
public getCompletionKey(starIndex: number, endIndex: number): Array<CompletionItemSimpleInfo> {
// console.log("getCompletionKey")
var infos: Array<CompletionItemSimpleInfo> = new Array<CompletionItemSimpleInfo>();
var key: string = "";
// 1 为 . 2 为 :
var tipType: number = 0;
var comments: Array<LuaComment> = null
//获取注释
while (true) {
CLog();
if (starIndex > endIndex) break;
var keyToken: TokenInfo = this.tokens[starIndex];
if (keyToken.type == TokenTypes.Keyword) {
return infos = [];
}
if (comments == null) {
//判断下 是不是function 和 local
if (starIndex - 1 >= 0) {
var upToken: TokenInfo = this.tokens[starIndex - 1]
if (this.lp.consume('function', upToken, TokenTypes.Keyword)) {
comments = upToken.comments;
if (starIndex - 2 >= 0) {
if (this.lp.consume('local', this.tokens[starIndex - 2], TokenTypes.Keyword)) {
comments = this.tokens[starIndex - 2].comments;
}
}
} else if (this.lp.consume('local', upToken, TokenTypes.Keyword)) {
comments = upToken.comments;
}
} else {
comments = keyToken.comments;
}
}
var key = "";
if (keyToken.type == TokenTypes.StringLiteral) {
key += '"' + this.tokens[starIndex].value + '"';
}
else {
key += this.tokens[starIndex].value;
}
var simpleInfo: CompletionItemSimpleInfo = null;
if (
this.lp.consume('[', keyToken, TokenTypes.Punctuator) ||
this.lp.consume('(', keyToken, TokenTypes.Punctuator) ||
this.lp.consume(')', keyToken, TokenTypes.Punctuator) ||
this.lp.consume(']', keyToken, TokenTypes.Punctuator)
) {
break
} else {
simpleInfo = new CompletionItemSimpleInfo(key, starIndex, CompletionItemKind.Field, tipType, new vscode.Position(keyToken.line,
keyToken.range.start - keyToken.lineStart));
infos.push(simpleInfo);
starIndex++;
if (starIndex > endIndex) break;
tipType = this.getTipType(starIndex);
if (tipType != 0) {
starIndex++;
continue;
}
}
// console.log(127);
if (this.lp.consume('[', this.tokens[starIndex], TokenTypes.Punctuator)) {
var g_number = 1;
var beginIndex = starIndex + 1;
while (true) {
CLog();
starIndex++;
if (this.lp.consume(']', this.tokens[starIndex], TokenTypes.Punctuator)) {
g_number--;
if (g_number == 0) {
var leng: number = starIndex - beginIndex
var lastInfo: CompletionItemSimpleInfo = infos[infos.length - 1]
if (leng == 1) {
var stringToken: TokenInfo = this.tokens[beginIndex];
var tokenValue: string = "";
if (stringToken.type == TokenTypes.StringLiteral) {
tokenValue = '"' + stringToken.value + '"';
var nextSimpleInfo: CompletionItemSimpleInfo = new CompletionItemSimpleInfo(stringToken.value, starIndex, CompletionItemKind.Field, 1, new vscode.Position(stringToken.line,
stringToken.range.start - stringToken.lineStart
))
lastInfo.nextInfo = nextSimpleInfo;
} else if (
stringToken.type == TokenTypes.NumericLiteral ||
stringToken.type == TokenTypes.BooleanLiteral ||
stringToken.type == TokenTypes.Identifier ||
stringToken.type == TokenTypes.VarargLiteral
) {
}
else {
// lastInfo.key = lastInfo.key + "[]"
}
} else {
// lastInfo.key = lastInfo.key + "[]";
}
starIndex++;
break;
}
} else if (this.lp.consume('[', this.tokens[starIndex], TokenTypes.Punctuator)) {
g_number++;
}
}
tipType = this.getTipType(starIndex);
if (tipType != 0) {
starIndex++;
continue;
}
} else {
var ss = 1;
}
if (starIndex > endIndex) break;
if (this.lp.consume('(', this.tokens[starIndex], TokenTypes.Punctuator)) {
// simpleInfo.kind = CompletionItemKind.Function;
var m_number = 1;
while (true) {
CLog();
starIndex++;
if (this.lp.consume(')', this.tokens[starIndex], TokenTypes.Punctuator)) {
m_number--;
if (m_number == 0) {
// simpleInfo.key += "()";
starIndex++;
break;
}
} else if (this.lp.consume('(', this.tokens[starIndex], TokenTypes.Punctuator)) {
m_number++;
}
}
if (starIndex > endIndex) {
break
}
tipType = this.getTipType(starIndex);
if (tipType != 0) {
starIndex++;
continue;
}
}
if (starIndex > endIndex) {
break
}
}
if (infos.length > 0) {
var simpleInfo: CompletionItemSimpleInfo = infos[infos.length - 1]
var commentstr: string = getComments(comments)
var skind: CompletionItemKind = simpleInfo.kind;
if (simpleInfo.nextInfo) {
simpleInfo.kind = CompletionItemKind.Field;
simpleInfo.nextInfo.kind = skind;
simpleInfo.nextInfo.desc = commentstr;
simpleInfo.comments = comments;
// simpleInfo.nextInfo.key += "()"
} else {
simpleInfo.desc = commentstr;
simpleInfo.comments = comments;
// simpleInfo.key += "()"
}
}
return infos;
}
public getTipType(starIndex: number): number {
var tipType: number = 0;
if (starIndex >= this.tokens.length) return tipType;
var symbolToken: TokenInfo = this.tokens[starIndex];
if (this.lp.consume('.', symbolToken, TokenTypes.Punctuator)) {
tipType = 1;
} else if (this.lp.consume(':', this.tokens[starIndex], TokenTypes.Punctuator)) {
tipType = 2;
}
return tipType;
}
public getValueToken(index: number, tokens: Array<TokenInfo>) {
if (index < tokens.length) {
return tokens[index]
} else {
return null
}
}
//检查 item赋值 require 路径
public checkCompletionItemValueRequire(endToken: TokenInfo, tokens: Array<TokenInfo>, completion: LuaFiledCompletionInfo) {
if(completion.valueReferenceModulePath != null){
return;
}
var length = tokens.length
var index = endToken.index + 1;
var currentToken: TokenInfo = this.getValueToken(index, tokens)
if (currentToken) {
if (currentToken.type == TokenTypes.Punctuator && currentToken.value == "=") {
//优先注释
this.checkValueReferenceValue(completion)
if(completion.valueReferenceModulePath != null){
return;
}
index++;
var funNames: Array<string> = getCurrentFunctionName(this.tokens.slice(0, endToken.index))
if (funNames.length == 0) {
//没有方法那么就是文件中的全局信息
funNames.push("__g__")
}
currentToken = this.getValueToken(index, tokens)
if(currentToken == null){
return;
}
if (currentToken.type == TokenTypes.Identifier) {
if ( ExtensionManager.em.luaIdeConfigManager.requireFunNames.indexOf(currentToken.value) > -1 ) {
//require 模式
index++;
currentToken = this.getValueToken(index, tokens)
if (currentToken) {
if (currentToken.type == TokenTypes.Punctuator && currentToken.value == "(") {
index++
currentToken = this.getValueToken(index, tokens)
if (currentToken != null) {
if (currentToken.type == TokenTypes.StringLiteral) {
var pathValue = currentToken.value;
completion.addRequireReferencePath(pathValue)
} else if (currentToken.type == TokenTypes.Identifier) {
var keysInfo = this.getCompletionValueKeys(tokens, index)
if (keysInfo) {
var keys: Array<string> = keysInfo.keys
if (keys.length > 0) {
completion.addRequireReferenceFileds(funNames[0], keys)
}
}
}
}
}
}
} else {
var info = this.getCompletionValueKeys(tokens, index)
if (info) {
if (info.type == 1) {
completion.addReferenceCompletionKeys(funNames[0], info.keys)
} else {
completion.addReferenceCompletionFunKeys(funNames[0], info.keys)
}
}
}
} else if (currentToken.type == TokenTypes.StringLiteral) {
completion.setCompletionStringValue(currentToken.value)
}
}
}
}
/**
* type == 1 字段
* type == 2 方法
*/
public getCompletionValueKeys(tokens: Array<TokenInfo>, index: number): any {
var keys: Array<string> = new Array<string>();
var keyToken: TokenInfo = tokens[index]
if (keyToken.type == TokenTypes.Identifier) {
keys.push(keyToken.value)
if(keyToken.value == "self"){
var info = getSelfToModuleName(tokens,LuaParse.lp)
if(info){
keys[0] = info.moduleName
}
}
} else {
return null
}
index++;
while (index < tokens.length) {
keyToken = tokens[index]
if (keyToken.type == TokenTypes.Punctuator) {
if (keyToken.value == "." || keyToken.value == ":") {
keys.push(keyToken.value)
} else if (keyToken.value == "(") {
//为一个方法
return {
type: 2,
keys: keys
}
}
else if (keyToken.value == ")") {
return {
type: 1,
keys: keys
}
}
else if (keyToken.value == ";") {
return {
type: 1,
keys: keys
}
}
else {
return null
}
} else {
return {
type: 1,
keys: keys
}
}
index++
var keyToken = tokens[index]
if (keyToken.type == TokenTypes.Identifier) {
keys.push(keyToken.value)
}
index++
if (index >= tokens.length) {
return null
}
}
return null
}
/**
* 去除多余的completion
*/
public checkFunCompletion() {
var items = this.luaFunCompletionInfo.getItems()
items.forEach((funCompletion, k) => {
//查找
var gcompletion: LuaFiledCompletionInfo = this.luaFileGolbalCompletionInfo.getItemByKey(k)
if (gcompletion) {
if (funCompletion.getItems().size == 0 && gcompletion.getItems().size == 0) {
this.luaFileGolbalCompletionInfo.delItem(k)
} else {
funCompletion.getItems().forEach((fc, k1) => {
gcompletion.delItem(k1)
})
}
}
gcompletion = this.luaGolbalCompletionInfo.getItemByKey(k)
if (gcompletion) {
if (funCompletion.getItems().size == 0 && gcompletion.getItems().size == 0) {
this.luaFileGolbalCompletionInfo.delItem(k)
} else {
funCompletion.getItems().forEach((fc, k1) => {
gcompletion.delItem(k1)
})
}
}
})
}
}
export class CompletionItemSimpleInfo {
public key: string;
public endIndex11: number;
public tipTipType: number;
public kind: CompletionItemKind;
public desc: string = null;
public nextInfo: CompletionItemSimpleInfo = null;
public isShow: boolean = true;
public comments: Array<LuaComment>
public position: vscode.Position;
public constructor(key: string, endIndex: number, kind: CompletionItemKind, tipTipType: number, position: vscode.Position) {
this.position = position;
this.key = key;
this.tipTipType = tipTipType;
this.endIndex11 = endIndex;
this.kind = kind;
}
} | the_stack |
import { EDITOR, TEST } from 'internal:constants';
import { SafeAreaEdge } from 'pal/screen-adapter';
import { systemInfo } from 'pal/system-info';
import { EventTarget } from '../../../cocos/core/event/event-target';
import { Size } from '../../../cocos/core/math';
import { OS } from '../../system-info/enum-type';
import { Orientation } from '../enum-type';
interface IScreenFunctionName {
requestFullscreen: string,
exitFullscreen: string,
fullscreenchange: string,
fullscreenEnabled: string,
fullscreenElement: string,
fullscreenerror: string,
}
class ScreenAdapter extends EventTarget {
public isFrameRotated = false;
public handleResizeEvent = true;
public get supportFullScreen (): boolean {
return this._supportFullScreen;
}
public get isFullScreen (): boolean {
if (!this._supportFullScreen) {
return false;
}
return !!document[this._fn.fullscreenElement];
}
public get devicePixelRatio () {
return window.devicePixelRatio || 1;
}
public get windowSize (): Size {
const result = this._windowSizeInCssPixels;
const dpr = this.devicePixelRatio;
result.width *= dpr;
result.height *= dpr;
return result;
}
public set windowSize (size: Size) {
if (systemInfo.isMobile || EDITOR) {
// We say that on web mobile, the window size equals to the browser inner size.
// The window size is readonly on web mobile.
return;
}
this._resizeFrame(this._convertToSizeInCssPixels(size));
}
public get resolution () {
return this._resolution;
}
public get resolutionScale () {
return this._resolutionScale;
}
public set resolutionScale (v: number) {
if (v === this._resolutionScale) {
return;
}
this._resolutionScale = v;
this._updateResolution();
}
public get orientation (): Orientation {
return this._orientation;
}
public set orientation (value: Orientation) {
if (this._orientation === value) {
return;
}
this._orientation = value;
if (!this._gameFrame) {
return;
}
const width = window.innerWidth;
const height = window.innerHeight;
const isBrowserLandscape = width > height;
const needToRotateDocument = systemInfo.isMobile && systemInfo.os === OS.ANDROID
&& ((isBrowserLandscape && value & Orientation.PORTRAIT) || (!isBrowserLandscape && value & Orientation.LANDSCAPE));
if (needToRotateDocument) {
this.isFrameRotated = true;
this._gameFrame.style['-webkit-transform'] = 'rotate(90deg)';
this._gameFrame.style.transform = 'rotate(90deg)';
this._gameFrame.style['-webkit-transform-origin'] = '0px 0px 0px';
this._gameFrame.style.transformOrigin = '0px 0px 0px';
this._gameFrame.style.margin = `0 0 0 ${width}px`;
this._gameFrame.style.width = `${height}px`;
this._gameFrame.style.height = `${width}px`;
this._resizeFrame(new Size(height, width));
} else {
this.isFrameRotated = false;
this._gameFrame.style['-webkit-transform'] = 'rotate(0deg)';
this._gameFrame.style.transform = 'rotate(0deg)';
// TODO
// this._gameFrame.style['-webkit-transform-origin'] = '0px 0px 0px';
// this._gameFrame.style.transformOrigin = '0px 0px 0px';
this._gameFrame.style.margin = '0px';
this._gameFrame.style.width = `${width}px`;
this._gameFrame.style.height = `${height}px`;
this._resizeFrame(new Size(width, height));
}
}
public get safeAreaEdge (): SafeAreaEdge {
return {
top: 0,
bottom: 0,
left: 0,
right: 0,
};
}
private _gameFrame?: HTMLDivElement;
private _gameContainer?: HTMLDivElement;
private _gameCanvas?: HTMLCanvasElement;
private _cbToUpdateFrameBuffer?: () => void;
private _supportFullScreen = false;
private _touchEventName: string;
private _onFullscreenChange?: () => void;
private _onFullscreenError?: () => void;
private _fn = {} as IScreenFunctionName;
// Function mapping for cross browser support
private _fnGroup = [
[
'requestFullscreen',
'exitFullscreen',
'fullscreenchange',
'fullscreenEnabled',
'fullscreenElement',
'fullscreenerror',
],
[
'requestFullScreen',
'exitFullScreen',
'fullScreenchange',
'fullScreenEnabled',
'fullScreenElement',
'fullscreenerror',
],
[
'webkitRequestFullScreen',
'webkitCancelFullScreen',
'webkitfullscreenchange',
'webkitIsFullScreen',
'webkitCurrentFullScreenElement',
'webkitfullscreenerror',
],
[
'mozRequestFullScreen',
'mozCancelFullScreen',
'mozfullscreenchange',
'mozFullScreen',
'mozFullScreenElement',
'mozfullscreenerror',
],
[
'msRequestFullscreen',
'msExitFullscreen',
'MSFullscreenChange',
'msFullscreenEnabled',
'msFullscreenElement',
'msfullscreenerror',
],
];
private get _windowSizeInCssPixels () {
if (systemInfo.isMobile || EDITOR || TEST) {
if (this.isFrameRotated) {
return new Size(window.innerHeight, window.innerWidth);
}
return new Size(window.innerWidth, window.innerHeight);
} else {
if (!this._gameFrame) {
console.warn('Cannot access game frame');
return new Size(0, 0);
}
return new Size(this._gameFrame.clientWidth, this._gameFrame.clientHeight);
}
}
private _resolution: Size = new Size(0, 0);
private _resolutionScale = 1;
private _orientation = Orientation.AUTO;
constructor () {
super();
// TODO: need to access frame from 'pal/launcher' module
this._gameFrame = document.getElementById('GameDiv') as HTMLDivElement;
this._gameContainer = document.getElementById('Cocos3dGameContainer') as HTMLDivElement;
this._gameCanvas = document.getElementById('GameCanvas') as HTMLCanvasElement;
let fnList: Array<string>;
const fnGroup = this._fnGroup;
for (let i = 0; i < fnGroup.length; i++) {
fnList = fnGroup[i];
// detect event support
if (typeof document[fnList[1]] !== 'undefined') {
for (let i = 0; i < fnList.length; i++) {
this._fn[fnGroup[0][i]] = fnList[i];
}
break;
}
}
this._supportFullScreen = (this._fn.requestFullscreen !== undefined);
this._touchEventName = ('ontouchstart' in window) ? 'touchend' : 'mousedown';
this._registerEvent();
}
public init (cbToRebuildFrameBuffer: () => void) {
this._cbToUpdateFrameBuffer = cbToRebuildFrameBuffer;
this._resizeFrame(this._windowSizeInCssPixels);
}
public requestFullScreen (): Promise<void> {
return new Promise((resolve, reject) => {
this._doRequestFullScreen().then(() => {
resolve();
}).catch(() => {
const fullscreenTarget = this._getFullscreenTarget();
if (!fullscreenTarget) {
reject(new Error('Cannot access fullscreen target'));
return;
}
fullscreenTarget.addEventListener(this._touchEventName, () => {
this._doRequestFullScreen().then(() => {
resolve();
}).catch(reject);
}, { once: true, capture: true });
});
});
}
public exitFullScreen (): Promise<void> {
return new Promise((resolve, reject) => {
const requestPromise = document[this._fn.exitFullscreen]();
if (window.Promise && requestPromise instanceof Promise) {
requestPromise.then(resolve).catch(reject);
return;
}
resolve();
});
}
private _registerEvent () {
document.addEventListener(this._fn.fullscreenerror, () => {
this._onFullscreenError?.();
});
window.addEventListener('resize', () => {
if (!this.handleResizeEvent) {
return;
}
this._resizeFrame(this._windowSizeInCssPixels);
});
if (typeof window.matchMedia === 'function') {
const updateDPRChangeListener = () => {
const dpr = window.devicePixelRatio;
// NOTE: some browsers especially on iPhone doesn't support MediaQueryList
window.matchMedia(`(resolution: ${dpr}dppx)`)?.addEventListener?.('change', () => {
this.emit('window-resize');
updateDPRChangeListener();
}, { once: true });
};
updateDPRChangeListener();
}
window.addEventListener('orientationchange', () => {
if (!this.handleResizeEvent) {
return;
}
this._resizeFrame(this._windowSizeInCssPixels);
this.emit('orientation-change');
});
document.addEventListener(this._fn.fullscreenchange, () => {
this._resizeFrame(this._windowSizeInCssPixels);
this._onFullscreenChange?.();
this.emit('fullscreen-change');
});
}
private _convertToSizeInCssPixels (size: Size) {
const clonedSize = size.clone();
const dpr = this.devicePixelRatio;
clonedSize.width /= dpr;
clonedSize.height /= dpr;
return clonedSize;
}
private _resizeFrame (sizeInCssPixels: Size) {
if (this._gameFrame) {
this._gameFrame.style.width = `${sizeInCssPixels.width}px`;
this._gameFrame.style.height = `${sizeInCssPixels.height}px`;
this.emit('window-resize');
}
this._updateResolution();
}
private _updateResolution () {
const windowSize = this.windowSize;
// update resolution
this._resolution.width = windowSize.width * this.resolutionScale;
this._resolution.height = windowSize.height * this.resolutionScale;
this._cbToUpdateFrameBuffer?.();
this.emit('resolution-change');
}
private _getFullscreenTarget () {
// On web mobile, the transform of game frame doesn't work when it's on fullscreen.
// So we need to make the body fullscreen.
return systemInfo.isMobile ? document.body : this._gameFrame;
}
private _doRequestFullScreen (): Promise<void> {
return new Promise((resolve, reject) => {
if (!this._supportFullScreen) {
reject(new Error('fullscreen is not supported'));
return;
}
const fullscreenTarget = this._getFullscreenTarget();
if (!fullscreenTarget) {
reject(new Error('Cannot access fullscreen target'));
return;
}
this._onFullscreenChange = undefined;
this._onFullscreenError = undefined;
const requestPromise = fullscreenTarget[this._fn.requestFullscreen]() as Promise<void> | undefined;
if (window.Promise && requestPromise instanceof Promise) {
requestPromise.then(resolve).catch(reject);
} else {
this._onFullscreenChange = resolve;
this._onFullscreenError = reject;
}
});
}
}
export const screenAdapter = new ScreenAdapter(); | the_stack |
import * as url from 'url';
import * as zlib from 'zlib';
import Debug from 'debug';
import { AdapterInterface } from './interface';
import { getVersion } from '../../utils';
import * as Stream from 'stream';
import { FsRequestOptions, FsResponse } from '../types';
import * as utils from '../utils';
import { prepareData, parseResponse, combineURL, set as setHeader, normalizeHeaders } from './../helpers';
import { FsRequestErrorCode, FsRequestError } from '../error';
import { FsHttpMethod } from './../types';
const HTTPS_REGEXP = /https:?/;
const HTTP_CHUNK_SIZE = 16 * 1024;
const MAX_REDIRECTS = 10;
const CANCEL_CLEAR = `FsCleanMemory`;
const debug = Debug('fs:request:http');
/**
* Writable stream thats overwrap http request for progress event
*
* @class HttpWritableStream
* @extends {Stream.Writable}
*/
class HttpWritableStream extends Stream.Writable {
private request;
constructor(req, opts = {}) {
super(opts);
this.request = req;
req.once('drain', () => this.emit('drain'));
}
_write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): void {
this.request.write(chunk, encoding, cb);
}
end(chunk) {
if (chunk) {
this.request.write(chunk);
}
this.request.end();
}
}
/**
* Node http request class
*
* @export
* @class HttpAdapter
* @implements {AdapterInterface}
*/
export class HttpAdapter implements AdapterInterface {
private redirectHoops = 0;
private redirectPaths = [];
/**
* do request based on configuration
*
* @param {FsRequestOptions} config
* @returns
* @memberof HttpAdapter
*/
request(config: FsRequestOptions) {
// if this option is unspecified set it by default
if (typeof config.filestackHeaders === 'undefined') {
config.filestackHeaders = true;
}
config.headers = normalizeHeaders(config.headers);
let { data, headers } = prepareData(config);
headers = setHeader(headers, 'user-agent', `filestack-request/${getVersion()}`);
// for now we are not using streams
if (data) {
debug('Request data %O', data);
if (!Buffer.isBuffer(data)) {
if (!utils.isString(data)) {
return Promise.reject(new FsRequestError('Data must be a string, JSON or a Buffer', config));
}
data = Buffer.from(data, 'utf-8');
}
headers = setHeader(headers, 'content-length', data.length, true);
}
// HTTP basic authentication
let auth;
if (config.auth) {
if (!config.auth.username || config.auth.username.length === 0) {
return Promise.reject(new FsRequestError(`Basic auth: username is required ${config.auth}`, config));
}
auth = `${config.auth.username}:${config.auth.password}`;
}
// Parse url
let parsed = url.parse(config.url);
// try to add default https protocol
if (!parsed.protocol) {
parsed = url.parse(`https://${config.url}`);
}
/* istanbul ignore next: just be sure that the host is parsed correctly, not needed to test */
if (!parsed.host) {
return Promise.reject(new FsRequestError(`Cannot parse provided url ${config.url}`, config));
}
// normalize auth header
if (auth && headers.Authorization) {
delete headers.Authorization;
}
const isHttpsRequest = HTTPS_REGEXP.test(parsed.protocol);
const agent = isHttpsRequest ? require('https') : require('http');
const options = {
path: combineURL(parsed.path, config.params),
host: parsed.host,
port: parsed.port,
protocol: parsed.protocol,
method: config.method.toUpperCase(),
headers: headers,
agent: new agent.Agent(),
auth: auth,
};
debug('Starting %s request with options %O', isHttpsRequest ? 'https' : 'http', options);
return new Promise<FsResponse>((resolve, reject): any => {
let req;
let cancelListener;
if (config.cancelToken) {
cancelListener = config.cancelToken.on('cancel', (reason) => {
// cleanup handler
cancelListener = null;
// do nothing if promise is resolved by system
if (reason && reason.message === CANCEL_CLEAR) {
return;
}
/* istanbul ignore next: if request is done cancel token should not throw any error */
if (req) {
req.abort();
req = null;
}
debug('Request canceled by user %s, config: %O', reason, config);
return reject(new FsRequestError(`Request aborted. Reason: ${reason}`, config, null, FsRequestErrorCode.ABORTED));
});
}
req = agent.request(options, res => {
/* istanbul ignore next: just be sure that response will not be called after request is aborted */
if (!req || req.aborted) {
return reject(new FsRequestError('Request aborted', config));
}
let stream = res;
debug('Response statusCode: %d, Response Headers: %O', res.statusCode, res.headers);
const compressHeaders = res.headers['content-encoding'];
if (compressHeaders && compressHeaders.length && ['gzip', 'compress', 'deflate'].some((v) => compressHeaders.indexOf(v) > -1)) {
// add the unzipper to the body stream processing pipeline
stream = res.statusCode === 204 ? stream : stream.pipe(zlib.createUnzip());
// remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding'];
}
let response: FsResponse = {
status: res.statusCode,
statusText: res.statusMessage,
headers: res.headers,
config,
data: {},
};
// we need to follow redirect so make same request with new location
if ([301, 302].indexOf(res.statusCode) > -1) {
debug('Redirect received %s', res.statusCode);
if (this.redirectHoops >= MAX_REDIRECTS) {
return reject(new FsRequestError(`Max redirects (${this.redirectHoops}) reached. Exiting`, config, response, FsRequestErrorCode.REDIRECT));
}
const url = res.headers['location'];
if (!url || url.length === 0) {
return reject(new FsRequestError(`Redirect header location not found`, config, response, FsRequestErrorCode.REDIRECT));
}
if (this.redirectPaths.indexOf(url) > -1) {
return reject(new FsRequestError(`Redirect loop detected at url ${url}`, config, response, FsRequestErrorCode.REDIRECT));
}
this.redirectPaths.push(url);
this.redirectHoops++;
// free resources
res = undefined;
req = undefined;
debug('Redirecting request to %s (hoop-count: %d)', url, this.redirectHoops);
return resolve(this.request(Object.assign({}, config, { url })));
}
let responseBuffer = [];
stream.on('data', chunk => responseBuffer.push(chunk));
/* istanbul ignore next: its hard to test socket events with jest and nock - tested manually */
stream.on('error', err => {
res = undefined;
req = undefined;
responseBuffer = undefined;
debug('Request error: Aborted %O', err);
if (req.aborted) {
return;
}
// clear cancel token to avoid memory leak
if (cancelListener) {
config.cancelToken.removeListener(cancelListener);
}
return reject(new FsRequestError(err.message, config, null, FsRequestErrorCode.NETWORK));
});
stream.on('end', async () => {
// clear cancel token to avoid memory leak
if (cancelListener) {
config.cancelToken.removeListener(cancelListener);
}
// check if there is any response data inside
if (res.statusCode !== 204) {
// prepare response
response.data = Buffer.concat(responseBuffer);
response = await parseResponse(response);
} else {
response.data = null;
}
// free resources
res = undefined;
req = undefined;
responseBuffer = undefined;
if (500 <= response.status && response.status <= 599) {
// server error throw
debug('Server error(5xx) - %O', response);
return reject(new FsRequestError(`Server error ${url}`, config, response, FsRequestErrorCode.SERVER));
} else if (400 <= response.status && response.status <= 499) {
debug('Request error(4xx) - %O', response);
return reject(new FsRequestError(`Request error ${url}`, config, response, FsRequestErrorCode.REQUEST));
}
debug('Request ends: %O', response);
return resolve(response);
});
});
if (config.timeout) {
req.setTimeout(config.timeout, () => {
req.abort();
if (cancelListener) {
config.cancelToken.removeListener(cancelListener);
}
return reject(new FsRequestError('Request timeout', config, null, FsRequestErrorCode.TIMEOUT));
});
}
req.on('error', err => {
if (cancelListener) {
config.cancelToken.removeListener(cancelListener);
}
if (!req || req.aborted) {
return;
}
debug('Request error: %s - %O', err, err.code);
return reject(new FsRequestError(`Request error: ${err.code}`, config, null, FsRequestErrorCode.NETWORK));
});
if (Buffer.isBuffer(data) && ['POST', 'PUT'].indexOf(config.method) > -1) {
return this.bufferToChunks(data).pipe(this.getProgressMonitor(config, data.length)).pipe(new HttpWritableStream(req));
}
req.end(data);
});
}
/**
* Monitor and emit progress event if needed
*
* @private
* @memberof HttpAdapter
*/
private getProgressMonitor = (config, total) => {
let loaded = 0;
const progress = new Stream.Transform();
progress._transform = (chunk, encoding, cb) => {
if (typeof config.onProgress === 'function' && [FsHttpMethod.POST, FsHttpMethod.PUT].indexOf(config.method) > -1) {
loaded += chunk.length;
config.onProgress({
lengthComputable: true,
loaded,
total,
});
}
cb(null, chunk);
};
return progress;
}
/**
* Convert buffer to stream
*
* @private
* @param {*} buffer
* @returns {Stream.Readable}
* @memberof HttpAdapter
*/
private bufferToChunks(buffer): Stream.Readable {
const chunking = new Stream.Readable();
const totalLength = buffer.length;
const remainder = totalLength % HTTP_CHUNK_SIZE;
const cutoff = totalLength - remainder;
for (let i = 0; i < cutoff; i += HTTP_CHUNK_SIZE) {
const chunk = buffer.slice(i, i + HTTP_CHUNK_SIZE);
chunking.push(chunk);
}
if (remainder > 0) {
const remainderBuffer = buffer.slice(-remainder);
chunking.push(remainderBuffer);
}
chunking.push(null);
return chunking;
}
} | the_stack |
type DeepPartial<T> = {} | T
type Svg = any
function assignProperties<E extends Element, P extends DeepPartial<E>>(elem: E, props: P): void {
for (const p in props) {
if (props.hasOwnProperty(p)) {
if (isObject(props[p])) {
// Go deeper, for properties such as `style`.
assignNestedProperties((elem as any)[p], props[p] as any)
} else {
if (p.indexOf('-') > -1) {
// Deal with custom and special attributes, such as `data-*` and `aria-*` attributes.
elem.setAttribute(p, props[p] as any)
} else {
// Treat the rest as standard properties.
(elem as any)[p] = props[p]
}
}
}
}
}
function assignNestedProperties(target: { [key: string]: any }, props: { [key: string]: any }) {
for (const p in props) {
if (props.hasOwnProperty(p)) {
if (isObject(props[p])) {
// Some SVG properties are even more nested.
assignNestedProperties(target[p], props[p])
} else {
target[p] = props[p]
}
}
}
}
function isObject(o: any): boolean {
return o instanceof Object && (o as Object).constructor === Object
}
//import {assignProperties} from './assignProperties'
//import {DeepPartial} from '../extra/DeepPartial'
//import {Svg} from './s'
/**
* Types added manually as they are not yet present in TypeScript (2.6.2) but they are listed in W3Schools' list of
* [HTML5 New Elements](https://www.w3schools.com/html/html5_new_elements.asp).
*
* TODO Follow up [TypeScript issue #17828](https://github.com/Microsoft/TypeScript/issues/17828).
*/
export type HTMLDetailsElement = HTMLElement & { open: boolean }
export type HTMLDialogElement = HTMLElement & { open: boolean }
/**
* List of all HTML tag names.
*/
export type HTMLTag
= 'a'
| 'abbr'
| 'address'
| 'area'
| 'article'
| 'aside'
| 'audio'
| 'b'
| 'base'
| 'bdi'
| 'bdo'
| 'blockquote'
| 'body'
| 'br'
| 'button'
| 'canvas'
| 'caption'
| 'cite'
| 'code'
| 'col'
| 'colgroup'
| 'data'
| 'datalist'
| 'dd'
| 'del'
| 'details'
| 'dfn'
| 'dialog'
| 'div'
| 'dl'
| 'dt'
| 'em'
| 'embed'
| 'fieldset'
| 'figcaption'
| 'figure'
| 'footer'
| 'form'
| 'h1'
| 'h2'
| 'h3'
| 'h4'
| 'h5'
| 'h6'
| 'head'
| 'header'
| 'hr'
| 'html'
| 'i'
| 'iframe'
| 'img'
| 'input'
| 'ins'
| 'kbd'
| 'label'
| 'legend'
| 'li'
| 'link'
| 'main'
| 'map'
| 'mark'
| 'meta'
| 'meter'
| 'nav'
| 'noscript'
| 'object'
| 'ol'
| 'optgroup'
| 'option'
| 'output'
| 'p'
| 'param'
| 'picture'
| 'pre'
| 'progress'
| 'q'
| 'rp'
| 'rt'
| 'ruby'
| 's'
| 'samp'
| 'script'
| 'section'
| 'select'
| 'small'
| 'source'
| 'span'
| 'strong'
| 'style'
| 'sub'
| 'summary'
| 'sup'
| 'table'
| 'tbody'
| 'td'
| 'template'
| 'textarea'
| 'tfoot'
| 'th'
| 'thead'
| 'time'
| 'title'
| 'tr'
| 'track'
| 'u'
| 'ul'
| 'var'
| 'video'
| 'wbr'
/**
* Aliases for HTML element types, whose native counterparts are not always easy to guess or find.
*
* Notice that some elements do not have a specific interface to define them, and they resort to a more generic one,
* e.g. `Ul` (unordered list) is well-defined by `HTMLUListElement`, but `B` (bold) simply delegates to `HTMLElement`.
*/
export type A = HTMLAnchorElement
export type Abbr = HTMLElement
export type Address = HTMLElement
export type Area = HTMLAreaElement
export type Article = HTMLElement
export type Aside = HTMLElement
export type Audio = HTMLAudioElement
export type B = HTMLElement
export type Base = HTMLBaseElement
export type Bdi = HTMLElement
export type Bdo = HTMLElement
export type Blockquote = HTMLQuoteElement
export type Body = HTMLBodyElement
export type Br = HTMLBRElement
export type Button = HTMLButtonElement
export type Canvas = HTMLCanvasElement
export type Caption = HTMLTableCaptionElement
export type Cite = HTMLElement
export type Code = HTMLElement
export type Col = HTMLTableColElement
export type Colgroup = HTMLTableColElement
export type Data = HTMLDataElement
export type Datalist = HTMLDataListElement
export type Dd = HTMLElement
export type Del = HTMLModElement
export type Details = HTMLDetailsElement
export type Dfn = HTMLElement
export type Dialog = HTMLDialogElement
export type Div = HTMLDivElement
export type Dl = HTMLDListElement
export type Dt = HTMLElement
export type Em = HTMLElement
export type Embed = HTMLEmbedElement
export type Fieldset = HTMLFieldSetElement
export type Figcaption = HTMLElement
export type Figure = HTMLElement
export type Footer = HTMLElement
export type Form = HTMLFormElement
export type H1 = HTMLHeadingElement
export type H2 = HTMLHeadingElement
export type H3 = HTMLHeadingElement
export type H4 = HTMLHeadingElement
export type H5 = HTMLHeadingElement
export type H6 = HTMLHeadingElement
export type Head = HTMLHeadElement
export type Header = HTMLElement
export type Hr = HTMLHRElement
export type Html = HTMLHtmlElement
export type I = HTMLElement
export type Iframe = HTMLIFrameElement
export type Img = HTMLImageElement
export type Input = HTMLInputElement
export type Ins = HTMLModElement
export type Kbd = HTMLElement
export type Label = HTMLLabelElement
export type Legend = HTMLLegendElement
export type Li = HTMLLIElement
export type Link = HTMLLinkElement
export type Main = HTMLElement
export type Map = HTMLMapElement
export type Mark = HTMLElement
export type Meta = HTMLMetaElement
export type Meter = HTMLMeterElement
export type Nav = HTMLElement
export type Noscript = HTMLElement
export type Object = HTMLObjectElement
export type Ol = HTMLOListElement
export type Optgroup = HTMLOptGroupElement
export type Option = HTMLOptionElement
export type Output = HTMLOutputElement
export type P = HTMLParagraphElement
export type Param = HTMLParamElement
export type Picture = HTMLPictureElement
export type Pre = HTMLPreElement
export type Progress = HTMLProgressElement
export type Q = HTMLQuoteElement
export type Rp = HTMLElement
export type Rt = HTMLElement
export type Ruby = HTMLElement
export type S = HTMLElement
export type Samp = HTMLElement
export type Script = HTMLScriptElement
export type Section = HTMLElement
export type Select = HTMLSelectElement
export type Small = HTMLElement
export type Source = HTMLSourceElement
export type Span = HTMLSpanElement
export type Strong = HTMLElement
export type Style = HTMLStyleElement
export type Sub = HTMLElement
export type Summary = HTMLElement
export type Sup = HTMLElement
export type Table = HTMLTableElement
export type Tbody = HTMLTableSectionElement
export type Td = HTMLTableDataCellElement
export type Template = HTMLTemplateElement
export type Textarea = HTMLTextAreaElement
export type Tfoot = HTMLTableSectionElement
export type Th = HTMLTableHeaderCellElement
export type Thead = HTMLTableSectionElement
export type Time = HTMLTimeElement
export type Title = HTMLTitleElement
export type Tr = HTMLTableRowElement
export type Track = HTMLTrackElement
export type U = HTMLElement
export type Ul = HTMLUListElement
export type Var = HTMLElement
export type Video = HTMLVideoElement
export type Wbr = HTMLElement
/**
* Map from HTML tag names to their corresponding types.
*/
export interface HTMLTagMap {
a: A
abbr: Abbr
address: Address
area: Area
article: Article
aside: Aside
audio: Audio
b: B
base: Base
bdi: Bdi
bdo: Bdo
blockquote: Blockquote
body: Body
br: Br
button: Button
canvas: Canvas
caption: Caption
cite: Cite
code: Code
col: Col
colgroup: Colgroup
data: Data
datalist: Datalist
dd: Dd
del: Del
details: Details
dfn: Dfn
dialog: Dialog
div: Div
dl: Dl
dt: Dt
em: Em
embed: Embed
fieldset: Fieldset
figcaption: Figcaption
figure: Figure
footer: Footer
form: Form
h1: H1
h2: H2
h3: H3
h4: H4
h5: H5
h6: H6
head: Head
header: Header
hr: Hr
html: Html
i: I
iframe: Iframe
img: Img
input: Input
ins: Ins
kbd: Kbd
label: Label
legend: Legend
li: Li
link: Link
main: Main
map: Map
mark: Mark
meta: Meta
meter: Meter
nav: Nav
noscript: Noscript
object: Object
ol: Ol
optgroup: Optgroup
option: Option
output: Output
p: P
param: Param
picture: Picture
pre: Pre
progress: Progress
q: Q
rp: Rp
rt: Rt
ruby: Ruby
s: S
samp: Samp
script: Script
section: Section
select: Select
small: Small
source: Source
span: Span
strong: Strong
style: Style
sub: Sub
summary: Summary
sup: Sup
table: Table
tbody: Tbody
td: Td
template: Template
textarea: Textarea
tfoot: Tfoot
th: Th
thead: Thead
time: Time
title: Title
tr: Tr
track: Track
u: U
ul: Ul
var: Var
video: Video
wbr: Wbr
[customTag: string]: HTMLElement
}
/**
* Allowed types for the children of HTML elements, if they accept them and don't have special constraints.
*/
export type HTMLChildren = string | (HTMLElement | Svg | string)[]
/**
* Allowed types for the properties of HTML elements.
*/
export type HTMLProperties<E extends HTMLElement = HTMLElement> = DeepPartial<E> & { [prop: string]: any }
/**
* Helper function to concisely create instances of any HTML element, including custom ones.
*/
export function h<K extends keyof HTMLTagMap>(name: K, props?: HTMLProperties<HTMLTagMap[K]>, children?: HTMLChildren): HTMLTagMap[K] {
const elem: HTMLTagMap[K] = document.createElement(name)
if (props !== undefined) {
assignProperties<HTMLTagMap[K], HTMLProperties<HTMLTagMap[K]>>(elem, props)
}
if (children !== undefined) {
if (typeof children === 'string') {
elem.appendChild(document.createTextNode(children))
} else {
children.forEach(child => elem.appendChild(
typeof child === 'string'
? document.createTextNode(child)
: child
))
}
}
return elem
}
/**
* HTML element content categories, extracted from https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories
* (deprecated, experimental or poorly-supported elements are excluded).
*/
export namespace HTMLContent {
export type Metadata = (Base | Link | Meta | Noscript | Script | Style | Title)[]
export type FlowItems = A | Abbr | Address | Article | Aside | Audio | B | Bdo | Bdi | Blockquote | Br | Button | Canvas | Cite | Code | Data | Datalist | Del | Details | Dfn | Div | Dl | Em | Embed | Fieldset | Figure | Footer | Form | H1 | H2 | H3 | H4 | H5 | H6 | Header | Hr | I | Iframe | Img | Input | Ins | Kbd | Label | Main | Map | Mark | Meter | Nav | Noscript | Object | Ol | Output | P | Pre | Progress | Q | Ruby | S | Samp | Script | Section | Select | Small | Span | Strong | Sub | Sup | Svg | Table | Template | Textarea | Time | Ul | Var | Video | Wbr | Area | Link | Meta | string
export type Flow = HTMLContent.FlowItems[] | string
export type Sectioning = (Article | Aside | Nav | Section)[]
export type HeadingItems = H1 | H2 | H3 | H4 | H5 | H6
export type Heading = HTMLContent.HeadingItems[]
export type PhrasingItems = Abbr | Audio | B | Bdo | Br | Button | Canvas | Cite | Code | Data | Datalist | Dfn | Em | Embed | I | Iframe | Img | Input | Kbd | Label | Mark | Meter | Noscript | Object | Output | Progress | Q | Ruby | Samp | Script | Select | Small | Span | Strong | Sub | Sup | Svg | Textarea | Time | Var | Video | Wbr | A | Area | Del | Ins | Link | Map | Meta | string
export type Phrasing = PhrasingItems[] | string
export type Embedded = (Audio | Canvas | Embed | Iframe | Img | Object | Svg | Video)[]
export type Interactive = (A | Button | Details | Embed | Iframe | Label | Select | Textarea | Audio | Img | Input | Object | Video)[]
export type Palpable = HTMLChildren
export type FormAssociated = (Button | Fieldset | Input | Label | Meter | Object | Output | Progress | Select | Textarea)[]
export type FormAssociatedListed = (Button | Fieldset | Input | Object | Output | Select | Textarea)[]
export type FormAssociatedLabelable = (Button | Input | Meter | Output | Progress | Select | Textarea)[]
export type FormAssociatedSubmittable = (Button | Input | Object | Select | Textarea)[]
export type FormAssociatedResettable = (Input | Output | Select | Textarea)[]
export type ScriptSupportingItems = Script | Template
export type ScriptSupporting = HTMLContent.ScriptSupportingItems[]
export type Transparent = HTMLChildren
}
/**
* Type aliases for the accepted children of all HTML elements.
*/
export namespace Children {
// Type aliases for all HTML elements, as a way to access them within the namespace without naming conflicts.
export type _A = HTMLTagMap['a']
export type _Abbr = HTMLTagMap['abbr']
export type _Address = HTMLTagMap['address']
export type _Area = HTMLTagMap['area']
export type _Article = HTMLTagMap['article']
export type _Aside = HTMLTagMap['aside']
export type _Audio = HTMLTagMap['audio']
export type _B = HTMLTagMap['b']
export type _Base = HTMLTagMap['base']
export type _Bdi = HTMLTagMap['bdi']
export type _Bdo = HTMLTagMap['bdo']
export type _Blockquote = HTMLTagMap['blockquote']
export type _Body = HTMLTagMap['body']
export type _Br = HTMLTagMap['br']
export type _Button = HTMLTagMap['button']
export type _Canvas = HTMLTagMap['canvas']
export type _Caption = HTMLTagMap['caption']
export type _Cite = HTMLTagMap['cite']
export type _Code = HTMLTagMap['code']
export type _Col = HTMLTagMap['col']
export type _Colgroup = HTMLTagMap['colgroup']
export type _Data = HTMLTagMap['data']
export type _Datalist = HTMLTagMap['datalist']
export type _Dd = HTMLTagMap['dd']
export type _Del = HTMLTagMap['del']
export type _Details = HTMLTagMap['details']
export type _Dfn = HTMLTagMap['dfn']
export type _Dialog = HTMLTagMap['dialog']
export type _Div = HTMLTagMap['div']
export type _Dl = HTMLTagMap['dl']
export type _Dt = HTMLTagMap['dt']
export type _Em = HTMLTagMap['em']
export type _Embed = HTMLTagMap['embed']
export type _Fieldset = HTMLTagMap['fieldset']
export type _Figcaption = HTMLTagMap['figcaption']
export type _Figure = HTMLTagMap['figure']
export type _Footer = HTMLTagMap['footer']
export type _Form = HTMLTagMap['form']
export type _H1 = HTMLTagMap['h1']
export type _H2 = HTMLTagMap['h2']
export type _H3 = HTMLTagMap['h3']
export type _H4 = HTMLTagMap['h4']
export type _H5 = HTMLTagMap['h5']
export type _H6 = HTMLTagMap['h6']
export type _Head = HTMLTagMap['head']
export type _Header = HTMLTagMap['header']
export type _Hr = HTMLTagMap['hr']
export type _Html = HTMLTagMap['html']
export type _I = HTMLTagMap['i']
export type _Iframe = HTMLTagMap['iframe']
export type _Img = HTMLTagMap['img']
export type _Input = HTMLTagMap['input']
export type _Ins = HTMLTagMap['ins']
export type _Kbd = HTMLTagMap['kbd']
export type _Label = HTMLTagMap['label']
export type _Legend = HTMLTagMap['legend']
export type _Li = HTMLTagMap['li']
export type _Link = HTMLTagMap['link']
export type _Main = HTMLTagMap['main']
export type _Map = HTMLTagMap['map']
export type _Mark = HTMLTagMap['mark']
export type _Meta = HTMLTagMap['meta']
export type _Meter = HTMLTagMap['meter']
export type _Nav = HTMLTagMap['nav']
export type _Noscript = HTMLTagMap['noscript']
export type _Object = HTMLTagMap['object']
export type _Ol = HTMLTagMap['ol']
export type _Optgroup = HTMLTagMap['optgroup']
export type _Option = HTMLTagMap['option']
export type _Output = HTMLTagMap['output']
export type _P = HTMLTagMap['p']
export type _Param = HTMLTagMap['param']
export type _Picture = HTMLTagMap['picture']
export type _Pre = HTMLTagMap['pre']
export type _Progress = HTMLTagMap['progress']
export type _Q = HTMLTagMap['q']
export type _Rp = HTMLTagMap['rp']
export type _Rt = HTMLTagMap['rt']
export type _Ruby = HTMLTagMap['ruby']
export type _S = HTMLTagMap['s']
export type _Samp = HTMLTagMap['samp']
export type _Script = HTMLTagMap['script']
export type _Section = HTMLTagMap['section']
export type _Select = HTMLTagMap['select']
export type _Small = HTMLTagMap['small']
export type _Source = HTMLTagMap['source']
export type _Span = HTMLTagMap['span']
export type _Strong = HTMLTagMap['strong']
export type _Style = HTMLTagMap['style']
export type _Sub = HTMLTagMap['sub']
export type _Summary = HTMLTagMap['summary']
export type _Sup = HTMLTagMap['sup']
export type _Table = HTMLTagMap['table']
export type _Tbody = HTMLTagMap['tbody']
export type _Td = HTMLTagMap['td']
export type _Template = HTMLTagMap['template']
export type _Textarea = HTMLTagMap['textarea']
export type _Tfoot = HTMLTagMap['tfoot']
export type _Th = HTMLTagMap['th']
export type _Thead = HTMLTagMap['thead']
export type _Time = HTMLTagMap['time']
export type _Title = HTMLTagMap['title']
export type _Tr = HTMLTagMap['tr']
export type _Track = HTMLTagMap['track']
export type _U = HTMLTagMap['u']
export type _Ul = HTMLTagMap['ul']
export type _Var = HTMLTagMap['var']
export type _Video = HTMLTagMap['video']
export type _Wbr = HTMLTagMap['wbr']
// Actual type aliases for the HTML children.
export type A = HTMLContent.Transparent
export type Abbr = HTMLContent.Phrasing
export type Address = HTMLContent.Flow
export type Area = void
export type Article = HTMLContent.Flow
export type Aside = HTMLContent.Flow
export type Audio = HTMLContent.Transparent
export type B = HTMLContent.Phrasing
export type Base = void
export type Bdi = HTMLContent.Phrasing
export type Bdo = HTMLContent.Phrasing
export type Blockquote = HTMLContent.Flow
export type Body = HTMLContent.Flow
export type Br = void
export type Button = HTMLContent.Phrasing
export type Canvas = HTMLContent.Transparent
export type Caption = HTMLContent.Flow
export type Cite = HTMLContent.Phrasing
export type Code = HTMLContent.Phrasing
export type Col = void
export type Colgroup = _Col[]
export type Data = HTMLContent.Phrasing
export type Datalist = HTMLContent.Phrasing | _Option[]
export type Dd = HTMLContent.Flow
export type Del = HTMLContent.Transparent
export type Details = (_Summary | HTMLContent.FlowItems)[] | string
export type Dfn = HTMLContent.Phrasing
export type Dialog = HTMLContent.Flow
export type Div = (HTMLContent.FlowItems | _Dt | _Dd | _Script | _Template)[] | string
export type Dl = (_Dt | _Dd | _Script | _Template | _Div)[]
export type Dt = HTMLContent.Flow
export type Em = HTMLContent.Phrasing
export type Embed = void
export type Fieldset = (_Legend | HTMLContent.FlowItems)[] | string
export type Figcaption = HTMLContent.Flow
export type Figure = (_Figcaption | HTMLContent.FlowItems)[] | string
export type Footer = HTMLContent.Flow
export type Form = HTMLContent.Flow
export type H1 = HTMLContent.Phrasing
export type H2 = HTMLContent.Phrasing
export type H3 = HTMLContent.Phrasing
export type H4 = HTMLContent.Phrasing
export type H5 = HTMLContent.Phrasing
export type H6 = HTMLContent.Phrasing
export type Head = HTMLContent.Metadata
export type Header = HTMLContent.Flow
export type Hr = void
export type Html = [_Head, _Body] | [_Head] | [_Body]
export type I = HTMLContent.Phrasing
export type Iframe = HTMLChildren
export type Img = void
export type Input = void
export type Ins = HTMLContent.Transparent
export type Kbd = HTMLContent.Phrasing
export type Label = HTMLContent.Phrasing
export type Legend = HTMLContent.Phrasing
export type Li = HTMLContent.Flow
export type Link = void
export type Main = HTMLContent.Flow
export type Map = HTMLContent.Transparent
export type Mark = HTMLContent.Phrasing
export type Meta = void
export type Meter = HTMLContent.Phrasing
export type Nav = HTMLContent.Flow
export type Noscript = HTMLChildren
export type Object = HTMLContent.Transparent
export type Ol = _Li[]
export type Optgroup = _Option[]
export type Option = string
export type Output = HTMLContent.Phrasing
export type P = HTMLContent.Phrasing
export type Param = void
export type Picture = (_Source | _Img | HTMLContent.ScriptSupportingItems)[]
export type Pre = HTMLContent.Phrasing
export type Progress = HTMLContent.Phrasing
export type Q = HTMLContent.Phrasing
export type Rp = string
export type Rt = HTMLContent.Phrasing
export type Ruby = HTMLContent.Phrasing
export type S = HTMLContent.Phrasing
export type Samp = HTMLContent.Phrasing
export type Script = string
export type Section = HTMLContent.Flow
export type Select = (_Option | _Optgroup)[]
export type Small = HTMLContent.Phrasing
export type Source = void
export type Span = HTMLContent.Phrasing
export type Strong = HTMLContent.Phrasing
export type Style = string
export type Sub = HTMLContent.Phrasing
export type Summary = HTMLContent.Phrasing | [HTMLContent.HeadingItems]
export type Sup = HTMLContent.Phrasing
export type Table = (_Caption | _Colgroup | _Thead | _Tbody | _Tfoot)[] | (_Caption | _Colgroup | _Thead | _Tr | _Tfoot)[]
export type Tbody = _Tr[]
export type Td = HTMLContent.Flow
export type Template = HTMLChildren
export type Textarea = string
export type Tfoot = _Tr[]
export type Th = HTMLContent.Flow
export type Thead = _Tr[]
export type Time = HTMLContent.Phrasing
export type Title = string
export type Tr = (_Td | _Th | HTMLContent.ScriptSupportingItems)[]
export type Track = void
export type U = HTMLContent.Phrasing
export type Ul = _Li[]
export type Var = HTMLContent.Phrasing
export type Video = HTMLContent.Transparent
export type Wbr = void
}
/**
* Helpers to allow creating any concrete HTML element in a more concise manner.
*
* The types of these are almost always stricter than those of `h()`, e.g. `br()` does not accept children, `ul()`
* accepts only `Li` children.
*
* TODO Once TypeScript's `Exclude` is available, some of the types of `children` can be even stricter.
*/
export const a = (props?: DeepPartial<A>, children?: Children.A): A => h('a', props, children)
export const abbr = (props?: DeepPartial<Abbr>, children?: Children.Abbr): Abbr => h('abbr', props, children)
export const address = (props?: DeepPartial<Address>, children?: Children.Address): Address => h('address', props, children)
export const area = (props?: DeepPartial<Area>): Area => h('area', props)
export const article = (props?: DeepPartial<Article>, children?: Children.Article): Article => h('article', props, children)
export const aside = (props?: DeepPartial<Aside>, children?: Children.Aside): Aside => h('aside', props, children)
export const audio = (props?: DeepPartial<Audio>, children?: Children.Audio): Audio => h('audio', props, children)
export const b = (props?: DeepPartial<B>, children?: Children.B): B => h('b', props, children)
export const base = (props?: DeepPartial<Base>): Base => h('base', props)
export const bdi = (props?: DeepPartial<Bdi>, children?: Children.Bdi): Bdi => h('bdi', props, children)
export const bdo = (props?: DeepPartial<Bdo>, children?: Children.Bdo): Bdo => h('bdo', props, children)
export const blockquote = (props?: DeepPartial<Blockquote>, children?: Children.Blockquote): Blockquote => h('blockquote', props, children)
export const body = (props?: DeepPartial<Body>, children?: Children.Body): Body => h('body', props, children)
export const br = (props?: DeepPartial<Br>): Br => h('br', props)
export const button = (props?: DeepPartial<Button>, children?: Children.Button): Button => h('button', props, children)
export const canvas = (props?: DeepPartial<Canvas>, children?: Children.Canvas): Canvas => h('canvas', props, children)
export const caption = (props?: DeepPartial<Caption>, children?: Children.Caption): Caption => h('caption', props, children)
export const cite = (props?: DeepPartial<Cite>, children?: Children.Cite): Cite => h('cite', props, children)
export const code = (props?: DeepPartial<Code>, children?: Children.Code): Code => h('code', props, children)
export const col = (props?: DeepPartial<Col>): Col => h('col', props)
export const colgroup = (props?: DeepPartial<Colgroup>, children?: Children.Colgroup): Colgroup => h('colgroup', props, children)
export const data = (props?: DeepPartial<Data>, children?: Children.Data): Data => h('data', props, children)
export const datalist = (props?: DeepPartial<Datalist>, children?: Children.Datalist): Datalist => h('datalist', props, children)
export const dd = (props?: DeepPartial<Dd>, children?: Children.Dd): Dd => h('dd', props, children)
export const del = (props?: DeepPartial<Del>, children?: Children.Del): Del => h('del', props, children)
export const details = (props?: DeepPartial<Details>, children?: Children.Details): Details => h('details', props, children)
export const dfn = (props?: DeepPartial<Dfn>, children?: Children.Dfn): Dfn => h('dfn', props, children)
export const dialog = (props?: DeepPartial<Dialog>, children?: Children.Dialog): Dialog => h('dialog', props, children)
export const div = (props?: DeepPartial<Div>, children?: Children.Div): Div => h('div', props, children)
export const dl = (props?: DeepPartial<Dl>, children?: Children.Dl): Dl => h('dl', props, children)
export const dt = (props?: DeepPartial<Dt>, children?: Children.Dt): Dt => h('dt', props, children)
export const em = (props?: DeepPartial<Em>, children?: Children.Em): Em => h('em', props, children)
export const embed = (props?: DeepPartial<Embed>): Embed => h('embed', props)
export const fieldset = (props?: DeepPartial<Fieldset>, children?: Children.Fieldset): Fieldset => h('fieldset', props, children)
export const figcaption = (props?: DeepPartial<Figcaption>, children?: Children.Figcaption): Figcaption => h('figcaption', props, children)
export const figure = (props?: DeepPartial<Figure>, children?: Children.Figure): Figure => h('figure', props, children)
export const footer = (props?: DeepPartial<Footer>, children?: Children.Footer): Footer => h('footer', props, children)
export const form = (props?: DeepPartial<Form>, children?: Children.Form): Form => h('form', props, children)
export const h1 = (props?: DeepPartial<H1>, children?: Children.H1): H1 => h('h1', props, children)
export const h2 = (props?: DeepPartial<H2>, children?: Children.H2): H2 => h('h2', props, children)
export const h3 = (props?: DeepPartial<H3>, children?: Children.H3): H3 => h('h3', props, children)
export const h4 = (props?: DeepPartial<H4>, children?: Children.H4): H4 => h('h4', props, children)
export const h5 = (props?: DeepPartial<H5>, children?: Children.H5): H5 => h('h5', props, children)
export const h6 = (props?: DeepPartial<H6>, children?: Children.H6): H6 => h('h6', props, children)
export const head = (props?: DeepPartial<Head>, children?: Children.Head): Head => h('head', props, children)
export const header = (props?: DeepPartial<Header>, children?: Children.Header): Header => h('header', props, children)
export const hr = (props?: DeepPartial<Hr>): Hr => h('hr', props)
export const html = (props?: DeepPartial<Html>, children?: Children.Html): Html => h('html', props, children)
export const i = (props?: DeepPartial<I>, children?: Children.I): I => h('i', props, children)
export const iframe = (props?: DeepPartial<Iframe>, children?: Children.Iframe): Iframe => h('iframe', props, children)
export const img = (props?: DeepPartial<Img>): Img => h('img', props)
export const input = (props?: DeepPartial<Input>): Input => h('input', props)
export const ins = (props?: DeepPartial<Ins>, children?: Children.Ins): Ins => h('ins', props, children)
export const kbd = (props?: DeepPartial<Kbd>, children?: Children.Kbd): Kbd => h('kbd', props, children)
export const label = (props?: DeepPartial<Label>, children?: Children.Label): Label => h('label', props, children)
export const legend = (props?: DeepPartial<Legend>, children?: Children.Legend): Legend => h('legend', props, children)
export const li = (props?: DeepPartial<Li>, children?: Children.Li): Li => h('li', props, children)
export const link = (props?: DeepPartial<Link>): Link => h('link', props)
export const main = (props?: DeepPartial<Main>, children?: Children.Main): Main => h('main', props, children)
export const map = (props?: DeepPartial<Map>, children?: Children.Map): Map => h('map', props, children)
export const mark = (props?: DeepPartial<Mark>, children?: Children.Mark): Mark => h('mark', props, children)
export const meta = (props?: DeepPartial<Meta>): Meta => h('meta', props)
export const meter = (props?: DeepPartial<Meter>, children?: Children.Meter): Meter => h('meter', props, children)
export const nav = (props?: DeepPartial<Nav>, children?: Children.Nav): Nav => h('nav', props, children)
export const noscript = (props?: DeepPartial<Noscript>, children?: Children.Noscript): Noscript => h('noscript', props, children)
export const object = (props?: DeepPartial<Object>, children?: Children.Object): Object => h('object', props, children)
export const ol = (props?: DeepPartial<Ol>, children?: Children.Ol): Ol => h('ol', props, children)
export const optgroup = (props?: DeepPartial<Optgroup>, children?: Children.Optgroup): Optgroup => h('optgroup', props, children)
export const option = (props?: DeepPartial<Option>, children?: Children.Option): Option => h('option', props, children)
export const output = (props?: DeepPartial<Output>, children?: Children.Output): Output => h('output', props, children)
export const p = (props?: DeepPartial<P>, children?: Children.P): P => h('p', props, children)
export const param = (props?: DeepPartial<Param>): Param => h('param', props)
export const picture = (props?: DeepPartial<Picture>, children?: Children.Picture): Picture => h('picture', props, children)
export const pre = (props?: DeepPartial<Pre>, children?: Children.Pre): Pre => h('pre', props, children)
export const progress = (props?: DeepPartial<Progress>, children?: Children.Progress): Progress => h('progress', props, children)
export const q = (props?: DeepPartial<Q>, children?: Children.Q): Q => h('q', props, children)
export const rp = (props?: DeepPartial<Rp>, children?: Children.Rp): Rp => h('rp', props, children)
export const rt = (props?: DeepPartial<Rt>, children?: Children.Rt): Rt => h('rt', props, children)
export const ruby = (props?: DeepPartial<Ruby>, children?: Children.Ruby): Ruby => h('ruby', props, children)
export const s = (props?: DeepPartial<S>, children?: Children.S): S => h('s', props, children)
export const samp = (props?: DeepPartial<Samp>, children?: Children.Samp): Samp => h('samp', props, children)
export const script = (props?: DeepPartial<Script>, children?: Children.Script): Script => h('script', props, children)
export const section = (props?: DeepPartial<Section>, children?: Children.Section): Section => h('section', props, children)
export const select = (props?: DeepPartial<Select>, children?: Children.Select): Select => h('select', props, children)
export const small = (props?: DeepPartial<Small>, children?: Children.Small): Small => h('small', props, children)
export const source = (props?: DeepPartial<Source>): Source => h('source', props)
export const span = (props?: DeepPartial<Span>, children?: Children.Span): Span => h('span', props, children)
export const strong = (props?: DeepPartial<Strong>, children?: Children.Strong): Strong => h('strong', props, children)
export const style = (props?: DeepPartial<Style>, children?: Children.Style): Style => h('style', props, children)
export const sub = (props?: DeepPartial<Sub>, children?: Children.Sub): Sub => h('sub', props, children)
export const summary = (props?: DeepPartial<Summary>, children?: Children.Summary): Summary => h('summary', props, children)
export const sup = (props?: DeepPartial<Sup>, children?: Children.Sup): Sup => h('sup', props, children)
export const table = (props?: DeepPartial<Table>, children?: Children.Table): Table => h('table', props, children)
export const tbody = (props?: DeepPartial<Tbody>, children?: Children.Tbody): Tbody => h('tbody', props, children)
export const td = (props?: DeepPartial<Td>, children?: Children.Td): Td => h('td', props, children)
export const template = (props?: DeepPartial<Template>, children?: Children.Template): Template => h('template', props, children)
export const textarea = (props?: DeepPartial<Textarea>, children?: Children.Textarea): Textarea => h('textarea', props, children)
export const tfoot = (props?: DeepPartial<Tfoot>, children?: Children.Tfoot): Tfoot => h('tfoot', props, children)
export const th = (props?: DeepPartial<Th>, children?: Children.Th): Th => h('th', props, children)
export const thead = (props?: DeepPartial<Thead>, children?: Children.Thead): Thead => h('thead', props, children)
export const time = (props?: DeepPartial<Time>, children?: Children.Time): Time => h('time', props, children)
export const title = (props?: DeepPartial<Title>, children?: Children.Title): Title => h('title', props, children)
export const tr = (props?: DeepPartial<Tr>, children?: Children.Tr): Tr => h('tr', props, children)
export const track = (props?: DeepPartial<Track>): Track => h('track', props)
export const u = (props?: DeepPartial<U>, children?: Children.U): U => h('u', props, children)
export const ul = (props?: DeepPartial<Ul>, children?: Children.Ul): Ul => h('ul', props, children)
// Reserved word suffixed with "_".
export const var_ = (props?: DeepPartial<Var>, children?: Children.Var): Var => h('var', props, children)
export const video = (props?: DeepPartial<Video>, children?: Children.Video): Video => h('video', props, children)
export const wbr = (props?: DeepPartial<Wbr>): Wbr => h('wbr', props) | the_stack |
import { keccak_256 } from '@noble/hashes/sha3';
import { bytesToHex } from '@noble/hashes/utils';
import * as secp256k1 from '@noble/secp256k1';
import * as rlp from 'micro-rlp';
// `micro-rlp` is forked from the most recent `rlp` and has two changes:
// 1. All dependencies have been removed. 2. Browser support has been added
export const CHAIN_TYPES = { mainnet: 1, ropsten: 3, rinkeby: 4, goerli: 5, kovan: 42 };
export const TRANSACTION_TYPES = { legacy: 0, eip2930: 1, eip1559: 2 };
export function add0x(hex: string) {
return /^0x/i.test(hex) ? hex : `0x${hex}`;
}
export function strip0x(hex: string) {
return hex.replace(/^0x/i, '');
}
function cloneDeep<T>(obj: T): T {
if (Array.isArray(obj)) {
return obj.map((i) => cloneDeep(i)) as unknown as T;
} else if (typeof obj === 'bigint') {
return BigInt(obj) as unknown as T;
} else if (typeof obj === 'object') {
// should be last, so it won't catch other types
let res: any = {};
for (let key in obj) res[key] = cloneDeep(obj[key]);
return res;
} else return obj;
}
const padHex = (hex: string): string => (hex.length & 1 ? `0${hex}` : hex);
function hexToBytes(hex: string): Uint8Array {
hex = padHex(strip0x(hex));
const array = new Uint8Array(hex.length / 2);
for (let i = 0; i < array.length; i++) {
const j = i * 2;
array[i] = Number.parseInt(hex.slice(j, j + 2), 16);
}
return array;
}
function numberToHex(num: number | bigint): string {
return padHex(num.toString(16));
}
function hexToNumber(hex: string): bigint {
if (typeof hex !== 'string') {
throw new TypeError('hexToNumber: expected string, got ' + typeof hex);
}
return hex ? BigInt(add0x(hex)) : 0n;
}
type Chain = keyof typeof CHAIN_TYPES;
type Type = keyof typeof TRANSACTION_TYPES;
// The order is important.
const FIELDS = ['nonce', 'gasPrice', 'gasLimit', 'to', 'value', 'data', 'v', 'r', 's'] as const;
// prettier-ignore
const FIELDS2930 = [
'chainId', 'nonce', 'gasPrice', 'gasLimit',
'to', 'value', 'data', 'accessList', 'yParity', 'r', 's'
] as const;
// prettier-ignore
const FIELDS1559 = [
'chainId', 'nonce', 'maxPriorityFeePerGas', 'maxFeePerGas', 'gasLimit',
'to', 'value', 'data', 'accessList', 'yParity', 'r', 's'
] as const;
const TypeToFields = {
legacy: FIELDS,
eip2930: FIELDS2930,
eip1559: FIELDS1559,
};
export type Field =
| typeof FIELDS[number]
| typeof FIELDS2930[number]
| typeof FIELDS1559[number]
| 'address'
| 'storageKey';
type str = string;
export type AccessList = [str, str[]][];
// These types will should be serializable by rlp as is
export type RawTxLegacy = [str, str, str, str, str, str, str, str, str];
export type RawTx2930 = [str, str, str, str, str, str, AccessList, str, str, str];
export type RawTx1559 = [str, str, str, str, str, str, str, AccessList, str, str, str];
export type RawTx = RawTxLegacy | RawTx2930 | RawTx1559;
export type RawTxMap = {
chainId?: string;
nonce: string;
gasPrice?: string;
maxPriorityFeePerGas?: string;
maxFeePerGas?: string;
gasLimit: string;
to: string;
value: string;
data: string;
accessList?: AccessList;
yParity?: string;
v?: string;
r: string;
s: string;
};
// Normalizes field to format which can easily be serialized by rlp (strings & arrays)
// prettier-ignore
const FIELD_NUMBER = new Set([
'chainId', 'nonce', 'gasPrice', 'maxPriorityFeePerGas', 'maxFeePerGas',
'gasLimit', 'value', 'v', 'yParity', 'r', 's'
]);
const FIELD_DATA = new Set(['data', 'to', 'storageKey', 'address']);
function normalizeField(
field: Field,
value:
| number
| bigint
| string
| Uint8Array
| Record<string, string[]>
| AccessList
| { address: string; storageKeys: string[] }[]
): string | AccessList {
// can be number, bignumber, decimal number in string (123), hex number in string (0x123)
if (FIELD_NUMBER.has(field)) {
// bytes
if (value instanceof Uint8Array) value = add0x(bytesToHex(value));
if (field === 'yParity' && typeof value === 'boolean') value = value ? '0x1' : '0x0';
// '123' -> 0x7b (handles both hex and non-hex numbers)
if (typeof value === 'string') value = BigInt(value === '0x' ? '0x0' : value);
// 123 -> '0x7b' && 1 -> 0x01
if (typeof value === 'number' || typeof value === 'bigint')
value = add0x(padHex(value.toString(16)));
// 21000, default / minimum
if (field === 'gasLimit' && (!value || BigInt(value as string) === 0n)) value = '0x5208';
if (typeof value !== 'string') throw new TypeError(`Invalid type for field ${field}`);
// should be hex string starting with '0x' at this point.
if (field === 'gasPrice' && BigInt(value) === 0n)
throw new TypeError('The gasPrice must have non-zero value');
// '0x00' and '' serializes differently
return BigInt(value) === 0n ? '' : value;
}
// Can be string or Uint8Array
if (FIELD_DATA.has(field)) {
if (!value) value = '';
if (value instanceof Uint8Array) value = bytesToHex(value);
if (typeof value !== 'string') throw new TypeError(`Invalid type for field ${field}`);
value = add0x(value);
return value === '0x' ? '' : value;
}
if (field === 'accessList') {
if (!value) return [];
let res: Record<string, Set<string>> = {};
if (Array.isArray(value)) {
for (let access of value) {
if (Array.isArray(access)) {
// AccessList
if (access.length !== 2 || !Array.isArray(access[1]))
throw new TypeError(`Invalid type for field ${field}`);
const key = normalizeField('address', access[0]) as string;
if (!res[key]) res[key] = new Set();
for (let i of access[1]) res[key].add(normalizeField('storageKey', i) as string);
} else {
// {address: string, storageKeys: string[]}[]
if (
typeof access !== 'object' ||
access == null ||
!access.address ||
!Array.isArray(access.storageKeys)
)
throw new TypeError(`Invalid type for field ${field}`);
const key = normalizeField('address', access.address) as string;
if (!res[key]) res[key] = new Set();
for (let i of access.storageKeys) res[key].add(normalizeField('storageKey', i) as string);
}
}
} else {
// {[address]: string[]}
if (typeof value !== 'object' || value == null || value instanceof Uint8Array)
throw new TypeError(`Invalid type for field ${field}`);
for (let k in value) {
const key = normalizeField('address', k) as string;
// undefined/empty allowed
if (!value[k]) continue;
if (!Array.isArray(value[k])) throw new TypeError(`Invalid type for field ${field}`);
res[key] = new Set(value[k].map((i) => normalizeField('storageKey', i) as string));
}
}
return Object.keys(res).map((i) => [i, Array.from(res[i])]) as AccessList;
}
throw new TypeError(`Invalid type for field ${field}`);
}
function possibleTypes(input: RawTxMap): Set<Type> {
let types: Set<Type> = new Set(Object.keys(TRANSACTION_TYPES) as Type[]);
const keys = new Set(Object.keys(input));
if (keys.has('maxPriorityFeePerGas') || keys.has('maxFeePerGas')) {
types.delete('legacy');
types.delete('eip2930');
}
if (keys.has('accessList') || keys.has('yParity')) types.delete('legacy');
if (keys.has('gasPrice')) types.delete('eip1559');
return types;
}
const RawTxLength: Record<number, Type> = { 9: 'legacy', 11: 'eip2930', 12: 'eip1559' };
const RawTxLengthRev: Record<Type, number> = { legacy: 9, eip2930: 11, eip1559: 12 };
function rawToSerialized(input: RawTx | RawTxMap, chain?: Chain, type?: Type): string {
let chainId;
if (chain) chainId = CHAIN_TYPES[chain];
if (Array.isArray(input)) {
if (!type) type = RawTxLength[input.length];
if (!type || RawTxLengthRev[type] !== input.length)
throw new Error(`Invalid fields length for ${type}`);
} else {
const types = possibleTypes(input);
if (type && !types.has(type)) {
throw new Error(
`Invalid type=${type}. Possible types with current fields: ${Array.from(types)}`
);
}
if (!type) {
if (types.has('legacy')) type = 'legacy';
else if (!types.size) throw new Error('Impossible fields set');
else type = Array.from(types)[0];
}
if (input.chainId) {
if (chain) {
const fromChain = normalizeField('chainId', CHAIN_TYPES[chain]);
const fromInput = normalizeField('chainId', input.chainId);
if (fromChain !== fromInput) {
throw new Error(
`Both chain=${chain}(${fromChain}) and chainId=${input.chainId}(${fromInput}) specified at same time`
);
}
}
chainId = input.chainId;
} else input.chainId = chainId as any;
input = (TypeToFields[type] as unknown as Field[]).map((key) => (input as any)[key]) as RawTx;
}
if (input) {
const sign = input.slice(-3);
// remove signature if any of fields is empty
if (!sign[0] || !sign[1] || !sign[2]) {
input = input.slice(0, -3) as any;
// EIP-155
if (type === 'legacy' && chainId)
(input as any).push(normalizeField('chainId', chainId), '', '');
}
}
let normalized = (input as Field[]).map((value, i) =>
normalizeField(TypeToFields[type as Type][i], value)
);
if (chainId) chainId = normalizeField('chainId', chainId);
if (type !== 'legacy' && chainId && normalized[0] !== chainId)
throw new Error(`ChainId=${normalized[0]} incompatible with Chain=${chainId}`);
const tNum = TRANSACTION_TYPES[type];
return (tNum ? `0x0${tNum}` : '0x') + bytesToHex(rlp.encode(normalized));
}
export const Address = {
fromPrivateKey(key: string | Uint8Array): string {
if (typeof key === 'string') key = hexToBytes(key);
return Address.fromPublicKey(secp256k1.getPublicKey(key));
},
fromPublicKey(key: string | Uint8Array): string {
if (typeof key === 'string') key = hexToBytes(key);
const len = key.length;
if (![33, 65].includes(len)) throw new Error(`Invalid key with length "${len}"`);
const pub = len === 65 ? key : secp256k1.Point.fromHex(key).toRawBytes(false);
const addr = bytesToHex(keccak_256(pub.slice(1, 65))).slice(24);
return Address.checksum(addr);
},
// ETH addr checksum is calculated by hashing the string with keccak.
// NOTE: it hashes *string*, not a bytearray: keccak('beef') not keccak([0xbe, 0xef])
checksum(nonChecksummedAddress: string): string {
const addr = strip0x(nonChecksummedAddress.toLowerCase());
if (addr.length !== 40) throw new Error('Invalid address, must have 40 chars');
const hash = strip0x(bytesToHex(keccak_256(addr)));
let checksummed = '';
for (let i = 0; i < addr.length; i++) {
// If ith character is 9 to f then make it uppercase
const nth = Number.parseInt(hash[i], 16);
let char = addr[i];
if (nth > 7) char = char.toUpperCase();
checksummed += char;
}
return add0x(checksummed);
},
verifyChecksum(address: string): boolean {
const addr = strip0x(address);
if (addr.length !== 40) throw new Error('Invalid address, must have 40 chars');
if (addr === addr.toLowerCase() || addr === addr.toUpperCase()) return true;
const hash = bytesToHex(keccak_256(addr.toLowerCase()));
for (let i = 0; i < 40; i++) {
// the nth letter should be uppercase if the nth digit of casemap is 1
const nth = Number.parseInt(hash[i], 16);
const char = addr[i];
if (nth > 7 && char.toUpperCase() !== char) return false;
if (nth <= 7 && char.toLowerCase() !== char) return false;
}
return true;
},
};
export class Transaction {
static DEFAULT_HARDFORK = 'london';
static DEFAULT_CHAIN: Chain = 'mainnet';
static DEFAULT_TYPE: Type = 'eip1559';
readonly hex: string;
readonly raw: RawTxMap;
readonly isSigned: boolean;
readonly type: Type;
constructor(
data: string | Uint8Array | RawTx | RawTxMap,
chain?: Chain,
readonly hardfork = Transaction.DEFAULT_HARDFORK,
type?: Type
) {
let norm;
if (typeof data === 'string') {
norm = data;
} else if (data instanceof Uint8Array) {
norm = bytesToHex(data);
} else if (Array.isArray(data) || (typeof data === 'object' && data != null)) {
norm = rawToSerialized(data, chain, type);
} else {
throw new TypeError('Expected valid serialized tx');
}
if (norm.length <= 6) throw new Error('Invalid tx length');
this.hex = add0x(norm);
let txData;
const prevType = type;
if (this.hex.startsWith('0x01')) [txData, type] = [add0x(this.hex.slice(4)), 'eip2930'];
else if (this.hex.startsWith('0x02')) [txData, type] = [add0x(this.hex.slice(4)), 'eip1559'];
else [txData, type] = [this.hex, 'legacy'];
if (prevType && prevType !== type) throw new Error('Invalid transaction type');
this.type = type;
const ui8a = rlp.decode(txData) as Uint8Array[];
this.raw = ui8a.reduce((res: any, value: any, i: number) => {
const name = TypeToFields[type!][i];
if (!name) return res;
res[name] = normalizeField(name, value);
return res;
}, {} as RawTxMap);
if (!this.raw.chainId) {
// Unsigned transaction with EIP-155
if (type === 'legacy' && !this.raw.r && !this.raw.s) {
this.raw.chainId = this.raw.v;
this.raw.v = '';
}
}
if (!this.raw.chainId) {
this.raw.chainId = normalizeField(
'chainId',
CHAIN_TYPES[chain || Transaction.DEFAULT_CHAIN]
) as string;
}
this.isSigned = !!(this.raw.r && this.raw.r !== '0x');
}
get bytes(): Uint8Array {
return hexToBytes(this.hex);
}
equals(other: Transaction) {
return this.getMessageToSign() === other.getMessageToSign();
}
get chain(): Chain | undefined {
for (let k in CHAIN_TYPES)
if (CHAIN_TYPES[k as Chain] === Number(this.raw.chainId!)) return k as Chain;
}
get sender(): string {
const sender = this.recoverSenderPublicKey();
if (!sender) throw new Error('Invalid signed transaction');
return Address.fromPublicKey(sender);
}
get gasPrice(): bigint {
if (this.type === 'eip1559') throw new Error('Field only available for "legacy" transactions');
return BigInt(this.raw.gasPrice!);
}
// maxFeePerGas: Represents the maximum amount that a user is willing to pay for their tx (inclusive of baseFeePerGas and maxPriorityFeePerGas)
get maxFeePerGas() {
if (this.type !== 'eip1559') throw new Error('Field only available for "eip1559" transactions');
return BigInt(this.raw.maxFeePerGas!);
}
get maxPriorityFeePerGas() {
if (this.type !== 'eip1559') throw new Error('Field only available for "eip1559" transactions');
return BigInt(this.raw.maxPriorityFeePerGas!);
}
get gasLimit(): bigint {
return BigInt(this.raw.gasLimit!);
}
// Amount in wei
get amount(): bigint {
return BigInt(this.raw.value);
}
// Total fee in wei
get fee(): bigint {
const price = this.type === 'eip1559' ? this.maxFeePerGas : this.gasPrice;
return price * this.gasLimit;
}
// Amount + fee in wei
get upfrontCost(): bigint {
return this.amount + this.fee;
}
// Checksummed address
get to(): string {
return Address.checksum(this.raw.to);
}
// Nonce is a counter that represents a number of outgoing transactions on the acct
get nonce(): number {
return Number.parseInt(this.raw.nonce, 16) || 0;
}
private supportsReplayProtection() {
const properBlock = !['chainstart', 'homestead', 'dao', 'tangerineWhistle'].includes(
this.hardfork
);
if (!this.isSigned) return true; // Unsigned, supports EIP155
const v = Number(hexToNumber(this.raw.v!));
const chainId = Number(this.raw.chainId!);
const meetsConditions = v === chainId * 2 + 35 || v === chainId * 2 + 36;
return properBlock && meetsConditions;
}
getMessageToSign(signed: boolean = false): string {
let values = (TypeToFields[this.type] as any).map((i: any) => (this.raw as any)[i]);
if (!signed) {
// TODO: merge with line #252 somehow? (same strip & EIP-155)
// Strip signature (last 3 values)
values = values.slice(0, -3);
// EIP-155
if (this.type === 'legacy' && this.supportsReplayProtection())
values.push(this.raw.chainId! as any, '', '');
}
let encoded = rlp.encode(values);
if (this.type !== 'legacy')
encoded = new Uint8Array([TRANSACTION_TYPES[this.type], ...Array.from(encoded)]);
return bytesToHex(keccak_256(encoded));
}
// Used in block explorers etc
get hash(): string {
if (!this.isSigned) throw new Error('Expected signed transaction');
return this.getMessageToSign(true);
}
async sign(privateKey: string | Uint8Array): Promise<Transaction> {
if (this.isSigned) throw new Error('Expected unsigned transaction');
if (typeof privateKey === 'string') privateKey = strip0x(privateKey);
const [hex, recovery] = await secp256k1.sign(this.getMessageToSign(), privateKey, {
recovered: true,
canonical: true,
});
const signature = secp256k1.Signature.fromHex(hex);
const chainId = Number(this.raw.chainId!);
const vv =
this.type === 'legacy' ? (chainId ? recovery + (chainId * 2 + 35) : recovery + 27) : recovery;
const [v, r, s] = [vv, signature.r, signature.s].map((n) => add0x(numberToHex(n)));
const signedRaw: RawTxMap =
this.type === 'legacy'
? { ...this.raw, v, r, s }
: { ...cloneDeep(this.raw), yParity: v, r, s };
return new Transaction(signedRaw, this.chain, this.hardfork, this.type);
}
recoverSenderPublicKey(): string | undefined {
if (!this.isSigned)
throw new Error('Expected signed transaction: cannot recover sender of unsigned tx');
const [r, s] = [this.raw.r, this.raw.s].map((n) => hexToNumber(n));
if (this.hardfork !== 'chainstart' && s && s > secp256k1.CURVE.n / 2n) {
throw new Error('Invalid signature: s is invalid');
}
const signature = new secp256k1.Signature(r, s).toHex();
const v = Number(hexToNumber(this.type === 'legacy' ? this.raw.v! : this.raw.yParity!));
const chainId = Number(this.raw.chainId!);
const recovery = this.type === 'legacy' ? (chainId ? v - (chainId * 2 + 35) : v - 27) : v;
return secp256k1.recoverPublicKey(this.getMessageToSign(), signature, recovery);
}
} | the_stack |
import * as dartStyle from 'dart-style';
import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
import * as base from './base';
import {ImportSummary, TranspilerBase} from './base';
import DeclarationTranspiler from './declaration';
import {FacadeConverter} from './facade_converter';
import {convertAST} from './json/conversions';
import {ConvertedSyntaxKind} from './json/converted_syntax_kinds';
import * as merge from './merge';
import mkdirP from './mkdirp';
import ModuleTranspiler from './module';
import TypeTranspiler from './type';
export interface TranspilerOptions {
/**
* Fail on the first error, do not collect multiple. Allows easier debugging as stack traces lead
* directly to the offending line.
*/
failFast?: boolean;
/**
* Output TypeScript semantic diagnostics when facade generation fails and TS errors could be the
* reason for the failure. When falsey, semantic diagnostics will never be output.
*/
semanticDiagnostics?: boolean;
/**
* Skip running dart-format on the output. This is useful for large files (like dom.d.ts) since
* the node package version of dart-format is significantly slower than the version in the SDK.
*/
skipFormatting?: boolean;
/**
* Specify the module name (e.g.) d3 instead of determining the module name from the d.ts files.
* This is useful for libraries that assume they will be loaded with a JS module loader but that
* Dart needs to load without a module loader until Dart supports JS module loaders.
*/
moduleName?: string;
/**
* A base path to relativize absolute file paths against. This is useful for library name
* generation (see above) and nicer file names in error messages.
*/
basePath?: string;
/**
* Enforce conventions of public/private keyword and underscore prefix
*/
enforceUnderscoreConventions?: boolean;
/**
* Sets a root path to look for typings used by the facade converter.
*/
typingsRoot?: string;
/**
* Generate browser API facades instead of importing them from dart:html.
*/
generateHTML?: boolean;
/**
* Rename types to avoid conflicts in cases where a variable and a type have the exact same name,
* but it is not clear if they are related or not.
*/
renameConflictingTypes?: boolean;
/**
* Do not assume that all properties declared on the anonymous types of top level variable
* declarations are static.
*/
explicitStatic?: boolean;
/**
* Emit anonymous tags on all classes that have neither constructors nor static members.
*/
trustJSTypes?: boolean;
/**
* Experimental option to emit the source file ASTs as JSON after performing preliminary
* processing that makes the format compatible with Dart.
*/
toJSON?: boolean;
/**
* Experimental JS Interop specific option to promote properties with function
* types to methods instead of properties with a function type. This the makes
* the Dart code more readable at the cost of disallowing setting the value of
* the property.
* Example JS library that benifits from this option:
* https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/chartjs/chart.d.ts
*/
promoteFunctionLikeMembers?: boolean;
}
export const COMPILER_OPTIONS: ts.CompilerOptions = {
experimentalDecorators: true,
module: ts.ModuleKind.ES2015,
// ES2015 is targeted rather than a later version of ES because we don't require any features
// introduced after ES2015
target: ts.ScriptTarget.ES2015,
};
/**
* Context to ouput code into.
*/
export const enum OutputContext {
Import = 0,
Header = 1,
Default = 2,
}
const NUM_OUTPUT_CONTEXTS = 3;
export class Transpiler {
private outputs: Output[];
private outputStack: Output[];
private currentFile: ts.SourceFile;
/**
* Map of import library path to a Set of identifier names being imported.
*/
imports: Map<String, ImportSummary>;
/**
* Map containing AST nodes that we have removed or replaced. This is safer than modifying the AST
* directly.
*/
nodeSubstitutions: Map<ts.Node, ts.Node> = new Map();
// Comments attach to all following AST nodes before the next 'physical' token. Track the earliest
// offset to avoid printing comments multiple times.
private lastCommentIdx = -1;
private errors: string[] = [];
private transpilers: TranspilerBase[];
private declarationTranspiler: DeclarationTranspiler;
private fc: FacadeConverter;
/* Number of nested levels of type arguments the current expression is within. */
private typeArgumentDepth = 0;
constructor(private options: TranspilerOptions = {}) {
this.fc = new FacadeConverter(this, options.typingsRoot, options.generateHTML);
this.declarationTranspiler = new DeclarationTranspiler(
this, this.fc, options.enforceUnderscoreConventions, options.promoteFunctionLikeMembers,
options.trustJSTypes);
this.transpilers = [
new ModuleTranspiler(this, this.fc, options.moduleName),
this.declarationTranspiler,
new TypeTranspiler(this, this.fc),
];
}
/**
* Transpiles the given files to Dart.
* @param fileNames The input files.
* @param destination Location to write files to. Outputs file contents to stdout if absent.
*/
transpile(fileNames: string[], destination?: string): void {
this.errors = [];
if (this.options.basePath) {
this.options.basePath = this.normalizeSlashes(path.resolve(this.options.basePath));
}
fileNames = fileNames.map((name: string) => {
const normalizedName = this.normalizeSlashes(name);
if (normalizedName.startsWith('./')) {
// The fileName property of SourceFiles omits ./ for files in the current directory
return normalizedName.substring(2);
}
return normalizedName;
});
// Only write files that were explicitly passed in.
const fileSet = new Set(fileNames);
const sourceFileMap: Map<string, ts.SourceFile> = new Map();
const host = this.createCompilerHost(sourceFileMap);
this.normalizeSourceFiles(fileSet, sourceFileMap, host);
// Create a new program after performing source file transformations.
const normalizedProgram = ts.createProgram(fileNames, this.getCompilerOptions(), host);
const translatedResults = this.translateProgram(normalizedProgram, fileNames);
for (const fileName of translatedResults.keys()) {
if (destination) {
const outputFile = this.getOutputPath(path.resolve(fileName), destination);
console.log('Output file:', outputFile);
mkdirP(path.dirname(outputFile));
fs.writeFileSync(outputFile, translatedResults.get(fileName));
} else {
// Write source code directly to the console when no destination is specified.
console.log(translatedResults.get(fileName));
}
}
this.checkForErrors(normalizedProgram);
}
translateProgram(program: ts.Program, entryPoints: string[]): Map<string, string> {
this.fc.setTypeChecker(program.getTypeChecker());
this.declarationTranspiler.setTypeChecker(program.getTypeChecker());
const paths: Map<string, string> = new Map();
this.errors = [];
program.getSourceFiles()
.filter((f: ts.SourceFile) => entryPoints.includes(f.fileName))
.forEach((f) => {
if (this.options.toJSON) {
paths.set(f.fileName, this.convertToJSON(f));
} else {
paths.set(f.fileName, this.translate(f));
}
});
this.checkForErrors(program);
if (this.options.toJSON) {
paths.set('converted_syntax_kinds.ts', JSON.stringify(ConvertedSyntaxKind, undefined, 2));
}
return paths;
}
/**
* Preliminary processing of source files to make them compatible with Dart.
*
* Propagates namespace export declarations and merges related classes and variables.
*
* @param fileNames The input files.
* @param sourceFileMap A map that is used to access SourceFiles by their file names. The
* normalized files will be stored in this map.
* @param compilerHost The TS compiler host.
*/
normalizeSourceFiles(
fileNames: Set<string>, sourceFileMap: Map<string, ts.SourceFile>,
compilerHost: ts.CompilerHost) {
const program =
ts.createProgram(Array.from(fileNames), this.getCompilerOptions(), compilerHost);
if (program.getSyntacticDiagnostics().length > 0) {
// Throw first error.
const first = program.getSyntacticDiagnostics()[0];
const error = new Error(`${first.start}: ${first.messageText} in ${first.file.fileName}`);
error.name = 'DartFacadeError';
throw error;
}
this.fc.setTypeChecker(program.getTypeChecker());
const sourceFiles =
program.getSourceFiles().filter((f: ts.SourceFile) => fileNames.has(f.fileName));
sourceFiles.forEach((f: ts.SourceFile) => {
sourceFileMap.set(f.fileName, f);
});
sourceFiles.forEach((f: ts.SourceFile) => {
this.propagateNamespaceExportDeclarations(f, sourceFileMap, compilerHost);
});
sourceFiles.forEach((f: ts.SourceFile) => {
const normalizedFile = merge.normalizeSourceFile(
f, this.fc, fileNames, this.options.renameConflictingTypes, this.options.explicitStatic);
sourceFileMap.set(f.fileName, normalizedFile);
});
}
/**
* Check for namespace export declarations and propagate them to all modules they export.
*
* Namespace export declarations are used to declare UMD modules. The syntax for
* them is 'export as namespace MyNamespace;'. This means that exported members of module
* MyNamespace can be accessed through the global variable 'MyNamespace' within script files. Or
* within source files, by importing them like you would import other modular libraries.
*/
private propagateNamespaceExportDeclarations(
sourceFile: ts.SourceFile,
sourceFileMap: Map<string, ts.SourceFile>,
compilerHost: ts.CompilerHost,
) {
let globalModuleName: string;
sourceFile.forEachChild((n: ts.Node) => {
if (!ts.isNamespaceExportDeclaration(n)) return;
// This is the name we are interested in for Dart purposes until Dart supports AMD module
// loaders. This module name should all be reflected by all modules exported by this
// library as we need to specify a global module location for every Dart library.
globalModuleName = base.ident(n.name);
sourceFile.moduleName = globalModuleName;
});
const missingFiles: string[] = [];
sourceFile.statements.forEach((e: ts.Node) => {
if (!ts.isExportDeclaration(e)) return;
let exportDecl = e;
if (!exportDecl.moduleSpecifier) return;
let moduleLocation = <ts.StringLiteral>exportDecl.moduleSpecifier;
let location = moduleLocation.text;
let resolvedPath = compilerHost.resolveModuleNames(
[location], sourceFile.fileName, undefined, undefined, this.getCompilerOptions());
resolvedPath.forEach((p) => {
if (!p || p.isExternalLibraryImport) return;
const exportedFile = sourceFileMap.get(p.resolvedFileName);
if (exportedFile) {
exportedFile.moduleName = globalModuleName;
} else {
missingFiles.push(p.resolvedFileName);
}
});
});
if (missingFiles.length) {
const error = new Error();
error.message =
'The following files were referenced but were not supplied as a command line arguments. Reference the README for usage instructions.';
for (const file of missingFiles) {
error.message += '\n';
error.message += file;
}
error.name = 'DartFacadeError';
throw error;
}
}
getCompilerOptions() {
const opts: ts.CompilerOptions = Object.assign({}, COMPILER_OPTIONS);
opts.rootDir = this.options.basePath;
if (this.options.generateHTML) {
// Prevent the TypeScript DOM library files from being compiled.
opts.lib = ['lib.es2015.d.ts', 'lib.scripthost.d.ts'];
}
return opts;
}
private createCompilerHost(sourceFileMap: Map<string, ts.SourceFile>): ts.CompilerHost {
const compilerOptions = this.getCompilerOptions();
const compilerHost = ts.createCompilerHost(compilerOptions);
const defaultLibFileName = this.normalizeSlashes(ts.getDefaultLibFileName(compilerOptions));
compilerHost.getSourceFile = (sourceName) => {
let sourcePath = sourceName;
if (sourceName === defaultLibFileName) {
sourcePath = ts.getDefaultLibFilePath(compilerOptions);
} else if (sourceFileMap.has(sourceName)) {
return sourceFileMap.get(sourceName);
}
if (!fs.existsSync(sourcePath)) {
return undefined;
}
const contents = fs.readFileSync(sourcePath, 'utf-8');
return ts.createSourceFile(sourceName, contents, COMPILER_OPTIONS.target, true);
};
compilerHost.writeFile = (name, text, writeByteOrderMark) => {
fs.writeFile(name, text, undefined);
};
compilerHost.useCaseSensitiveFileNames = () => true;
compilerHost.getCurrentDirectory = () => '';
compilerHost.getNewLine = () => '\n';
compilerHost.resolveModuleNames = getModuleResolver(compilerHost);
return compilerHost;
}
// Visible for testing.
getOutputPath(filePath: string, destinationRoot: string): string {
let relative: string;
if (this.options.toJSON) {
relative = this.getJSONFileName(filePath);
} else {
relative = this.getDartFileName(filePath);
}
return this.normalizeSlashes(path.join(destinationRoot, relative));
}
public pushContext(context: OutputContext) {
this.outputStack.push(this.outputs[context]);
}
public popContext() {
if (this.outputStack.length === 0) {
this.reportError(null, 'Attempting to pop output stack when already empty');
}
this.outputStack.pop();
}
private translate(sourceFile: ts.SourceFile): string {
this.currentFile = sourceFile;
this.outputs = [];
this.outputStack = [];
this.imports = new Map();
for (let i = 0; i < NUM_OUTPUT_CONTEXTS; ++i) {
this.outputs.push(new Output());
}
this.lastCommentIdx = -1;
this.pushContext(OutputContext.Default);
this.visit(sourceFile);
this.popContext();
if (this.outputStack.length > 0) {
this.reportError(
sourceFile,
'Internal error managing output contexts. ' +
'Inconsistent push and pop context calls.');
}
this.pushContext(OutputContext.Import);
this.imports.forEach((summary, name) => {
this.emit(`import ${JSON.stringify(name)}`);
if (!summary.showAll) {
let shownNames = Array.from(summary.shown);
if (shownNames.length > 0) {
this.emit(`show ${shownNames.join(', ')}`);
}
}
if (summary.asPrefix) {
this.emit(`as ${summary.asPrefix}`);
}
this.emit(';\n');
});
this.popContext();
let result = '';
for (let output of this.outputs) {
result += output.getResult();
}
if (this.options.skipFormatting) {
return result;
}
return this.formatCode(result, sourceFile);
}
private convertToJSON(sourceFile: ts.SourceFile): string {
const converted = convertAST(sourceFile);
return JSON.stringify(converted, undefined, 2);
}
private formatCode(code: string, context: ts.Node) {
let result = dartStyle.formatCode(code);
if (result.error) {
this.reportError(context, result.error);
return code;
}
return result.code;
}
private checkForErrors(program: ts.Program) {
let errors = this.errors;
let diagnostics = program.getGlobalDiagnostics().concat(program.getSyntacticDiagnostics());
if ((errors.length || diagnostics.length)) {
// Only report semantic diagnostics if facade generation failed; this
// code is not a generic compiler, so only yields TS errors if they could
// be the cause of facade generation issues.
// This greatly speeds up tests and execution.
if (this.options.semanticDiagnostics) {
diagnostics = diagnostics.concat(program.getSemanticDiagnostics());
}
}
let diagnosticErrs = diagnostics.map((d) => {
let msg = '';
if (d.file) {
let pos = d.file.getLineAndCharacterOfPosition(d.start);
let fn = this.getRelativeFileName(d.file.fileName);
msg += ` ${fn}:${pos.line + 1}:${pos.character + 1}`;
}
msg += ': ';
msg += ts.flattenDiagnosticMessageText(d.messageText, '\n');
return msg;
});
if (diagnosticErrs.length) errors = errors.concat(diagnosticErrs);
if (errors.length) {
const e = new Error(errors.join('\n'));
e.name = 'DartFacadeError';
throw e;
}
}
/**
* Returns `filePath`, relativized to the program's `basePath`.
* @param filePath Optional path to relativize, defaults to the current file's path.
*/
getRelativeFileName(filePath?: string): string {
if (filePath === undefined) {
filePath = path.resolve(this.currentFile.fileName);
}
if (!path.isAbsolute(filePath)) {
return filePath; // already relative.
}
const basePath = this.options.basePath || '';
if (filePath.indexOf(basePath) !== 0 && !filePath.match(/\.d\.ts$/)) {
throw new Error(`Files must be located under base, got ${filePath} vs ${basePath}`);
}
return this.normalizeSlashes(path.relative(basePath, filePath));
}
getDartFileName(filePath?: string): string {
if (filePath === undefined) {
filePath = path.resolve(this.currentFile.fileName);
}
filePath = this.normalizeSlashes(filePath);
filePath = filePath.replace(/\.(js|es6|d\.ts|ts)$/, '.dart');
// Normalize from node module file path pattern to
filePath = filePath.replace(/([^/]+)\/index.dart$/, '$1.dart');
return this.getRelativeFileName(filePath);
}
getJSONFileName(filePath?: string): string {
if (filePath === undefined) {
filePath = path.resolve(this.currentFile.fileName);
}
filePath = this.normalizeSlashes(filePath);
filePath = filePath.replace(/\.(js|es6|d\.ts|ts)$/, '.json');
// Normalize from node module file path pattern to
filePath = filePath.replace(/([^/]+)\/index.dart$/, '$1.json');
return this.getRelativeFileName(filePath);
}
isJsModuleFile(): boolean {
// Treat files as being part of js modules if they match the node module file naming convention
// of module_name/index.js.
return !('/' + this.currentFile.fileName).match(/\/index\.(js|es6|d\.ts|ts)$/);
}
private get currentOutput(): Output {
return this.outputStack[this.outputStack.length - 1];
}
emit(s: string) {
this.currentOutput.emit(s);
}
emitNoSpace(s: string) {
this.currentOutput.emitNoSpace(s);
}
maybeLineBreak() {
return this.currentOutput.maybeLineBreak();
}
enterCodeComment() {
return this.currentOutput.enterCodeComment();
}
exitCodeComment() {
return this.currentOutput.exitCodeComment();
}
enterTypeArgument() {
this.typeArgumentDepth++;
}
exitTypeArgument() {
this.typeArgumentDepth--;
}
get insideTypeArgument(): boolean {
return this.typeArgumentDepth > 0;
}
emitType(s: string, comment: string) {
return this.currentOutput.emitType(s, comment);
}
get insideCodeComment() {
return this.currentOutput.insideCodeComment;
}
reportError(n: ts.Node, message: string) {
let file = n.getSourceFile() || this.currentFile;
let fileName = this.getRelativeFileName(file.fileName);
let start = n.getStart(file);
let pos = file.getLineAndCharacterOfPosition(start);
// Line and character are 0-based.
let fullMessage = `${fileName}:${pos.line + 1}:${pos.character + 1}: ${message}`;
if (this.options.failFast) throw new Error(fullMessage);
this.errors.push(fullMessage);
}
visit(node: ts.Node) {
if (this.nodeSubstitutions.has(node)) {
node = this.nodeSubstitutions.get(node);
}
if (!node) return;
let comments = ts.getLeadingCommentRanges(this.currentFile.text, node.getFullStart());
if (comments) {
comments.forEach((c) => {
// Warning: the following check means that comments will only be
// emitted correctly if Dart code is emitted in the same order it
// appeared in the JavaScript AST.
if (c.pos <= this.lastCommentIdx) return;
this.lastCommentIdx = c.pos;
let text = this.currentFile.text.substring(c.pos, c.end);
if (c.pos > 1) {
let prev = this.currentFile.text.substring(c.pos - 2, c.pos);
if (prev === '\n\n') {
// If the two previous characters are both \n then add a \n
// so that we ensure the output has sufficient line breaks to
// separate comment blocks.
this.currentOutput.emit('\n');
}
}
this.currentOutput.emitComment(this.translateComment(text));
});
}
for (let i = 0; i < this.transpilers.length; i++) {
if (this.transpilers[i].visitNode(node)) return;
}
this.reportError(
node,
'Unsupported node type ' + (<any>ts).SyntaxKind[node.kind] + ': ' + node.getFullText());
}
private normalizeSlashes(filePath: string) {
return filePath.replace(/\\/g, '/');
}
private translateComment(comment: string): string {
let rawComment = comment;
comment = comment.replace(/\{@link ([^\}]+)\}/g, '[$1]');
// Remove the following tags and following comments till end of line.
comment = comment.replace(/@param.*$/gm, '');
comment = comment.replace(/@throws.*$/gm, '');
comment = comment.replace(/@return.*$/gm, '');
// Remove the following tags.
comment = comment.replace(/@module/g, '');
comment = comment.replace(/@description/g, '');
comment = comment.replace(/@deprecated/g, '');
// Switch to /* */ comments and // comments to ///
let sb = '';
for (let line of comment.split('\n')) {
line = line.trim();
line = line.replace(/^[\/]\*\*?/g, '');
line = line.replace(/\*[\/]$/g, '');
line = line.replace(/^\*/g, '');
line = line.replace(/^\/\/\/?/g, '');
line = line.trim();
if (line.length > 0) {
sb += ' /// ' + line + '\n';
}
}
if (rawComment[0] === '\n') sb = '\n' + sb;
return sb;
}
}
export function getModuleResolver(compilerHost: ts.CompilerHost) {
return (moduleNames: string[], containingFile: string): ts.ResolvedModule[] => {
let res: ts.ResolvedModule[] = [];
for (let mod of moduleNames) {
let lookupRes = ts.resolveModuleName(mod, containingFile, COMPILER_OPTIONS, compilerHost);
if (lookupRes.resolvedModule) {
res.push(lookupRes.resolvedModule);
continue;
}
lookupRes = ts.classicNameResolver(mod, containingFile, COMPILER_OPTIONS, compilerHost);
if (lookupRes.resolvedModule) {
res.push(lookupRes.resolvedModule);
continue;
}
res.push(undefined);
}
return res;
};
}
class Output {
private result = '';
private firstColumn = true;
insideCodeComment = false;
private codeCommentResult = '';
/**
* Line break if the current line is not empty.
*/
maybeLineBreak() {
if (this.insideCodeComment) {
// Avoid line breaks inside code comments.
return;
}
if (!this.firstColumn) {
this.emitNoSpace('\n');
}
}
emit(str: string) {
let buffer = this.insideCodeComment ? this.codeCommentResult : this.result;
if (buffer.length > 0) {
let lastChar = buffer.slice(-1);
if (lastChar !== ' ' && lastChar !== '(' && lastChar !== '<' && lastChar !== '[' &&
lastChar !== '_') {
// Avoid emitting a space in obvious cases where a space is not required
// to make the output slightly prettier in cases where the DartFormatter
// cannot run such as within a comment where code we emit is not quite
// valid Dart code.
this.emitNoSpace(' ');
}
}
this.emitNoSpace(str);
}
emitNoSpace(str: string) {
if (str.length === 0) return;
if (this.insideCodeComment) {
this.codeCommentResult += str;
return;
}
this.result += str;
this.firstColumn = str.slice(-1) === '\n';
}
enterCodeComment() {
if (this.insideCodeComment) {
throw 'Cannot nest code comments' + this.codeCommentResult;
}
this.insideCodeComment = true;
this.codeCommentResult = '';
}
emitType(s: string, comment: string) {
this.emit(base.formatType(s, comment, {insideComment: this.insideCodeComment}));
}
/**
* Always emit comments in the main program body outside of the existing code
* comment block.
*/
emitComment(s: string) {
if (!this.firstColumn) {
this.result += '\n';
}
this.result += s;
this.firstColumn = true;
}
exitCodeComment() {
if (!this.insideCodeComment) {
throw 'Exit code comment called while not within a code comment.';
}
this.insideCodeComment = false;
this.emitNoSpace(' /*');
let result = dartStyle.formatCode(this.codeCommentResult);
let code = this.codeCommentResult;
if (!result.error) {
code = result.code;
}
const trimmed = code.trim();
const isMultilineComment = trimmed.indexOf('\n') !== -1;
if (isMultilineComment) {
this.emitNoSpace(code);
} else {
this.emitNoSpace(trimmed);
}
this.emitNoSpace('*/');
// Don't really need an exact column, just need to track
// that we aren't on the first column.
this.firstColumn = false;
this.codeCommentResult = '';
}
getResult(): string {
if (this.insideCodeComment) {
throw 'Code comment not property terminated.';
}
return this.result;
}
} | the_stack |
import assert from "assert";
import { matchMaker, MatchMakerDriver, Room } from "@colyseus/core";
import { DummyRoom, Room2Clients, createDummyClient, timeout, ReconnectRoom, Room3Clients, DRIVERS, ReconnectTokenRoom } from "./utils";
const DEFAULT_SEAT_RESERVATION_TIME = Number(process.env.COLYSEUS_SEAT_RESERVATION_TIME);
describe("MatchMaker", () => {
for (let i = 0; i < DRIVERS.length; i++) {
describe(`Driver: ${DRIVERS[i].name}`, () => {
let driver: MatchMakerDriver;
/**
* register room types
*/
before(async () => {
driver = new DRIVERS[i]();
matchMaker.setup(undefined, driver, 'dummyMatchMakerProcessId');
matchMaker.defineRoomType("empty", DummyRoom);
matchMaker.defineRoomType("dummy", DummyRoom);
matchMaker.defineRoomType("room2", Room2Clients);
matchMaker.defineRoomType("room3", Room3Clients);
matchMaker.defineRoomType("reconnect", ReconnectRoom);
matchMaker.defineRoomType("reconnect_token", ReconnectTokenRoom);
matchMaker
.defineRoomType("room2_filtered", Room2Clients)
.filterBy(['mode']);
matchMaker
.defineRoomType("room3_sorted_desc", Room3Clients)
.filterBy(['clients'])
.sortBy({ clients: -1 });
matchMaker
.defineRoomType("room3_sorted_asc", Room3Clients)
.filterBy(['clients'])
.sortBy({ clients: 1 });
/**
* give some time for `cleanupStaleRooms()` to run
*/
await timeout(50);
});
// make sure driver is cleared out.
after(async() => await driver.clear());
/**
* `setup` matchmaker to re-set graceful shutdown status
*/
beforeEach(() => matchMaker.setup(undefined, driver, 'dummyMatchMakerProcessId'));
/**
* ensure no rooms are avaialble in-between tests
*/
afterEach(async () => await matchMaker.gracefullyShutdown());
describe("exposed methods", () => {
it("joinOrCreate() should create a new room", async () => {
const reservedSeat = await matchMaker.joinOrCreate("dummy");
const room = matchMaker.getRoomById(reservedSeat.room.roomId)
assert.ok(room.hasReservedSeat(reservedSeat.sessionId));
assert.ok(room instanceof Room);
assert.ok(room instanceof DummyRoom);
});
it("joinOrCreate() should not find private rooms", async () => {
const reservedSeat = await matchMaker.joinOrCreate("dummy");
const room = matchMaker.getRoomById(reservedSeat.room.roomId)
await room.setPrivate();
const reservedSeat2 = await matchMaker.joinOrCreate("dummy");
assert.notStrictEqual(reservedSeat2.room.roomId, reservedSeat.room.roomId, "should not join a private room");
});
it("joinOrCreate() should not find locked rooms", async () => {
const reservedSeat = await matchMaker.joinOrCreate("dummy");
const room = matchMaker.getRoomById(reservedSeat.room.roomId)
await room.lock();
const reservedSeat2 = await matchMaker.joinOrCreate("dummy");
assert.notStrictEqual(reservedSeat2.room.roomId, reservedSeat.room.roomId, "should not join a locked room");
});
it("join() should fail if room doesn't exist", async () => {
await assert.rejects(async () => await matchMaker.join("empty"), /no rooms found/i);
});
it("join() should succeed if room exists", async () => {
const reservedSeat1 = await matchMaker.joinOrCreate("dummy");
const reservedSeat2 = await matchMaker.join("dummy");
const room = matchMaker.getRoomById(reservedSeat2.room.roomId);
assert.strictEqual(reservedSeat1.room.roomId, reservedSeat2.room.roomId);
assert.ok(room.hasReservedSeat(reservedSeat2.sessionId));
});
it("create() should create a new room", async () => {
const reservedSeat1 = await matchMaker.joinOrCreate("dummy");
const reservedSeat2 = await matchMaker.create("dummy");
const room = matchMaker.getRoomById(reservedSeat2.room.roomId);
assert.notStrictEqual(reservedSeat1.room.roomId, reservedSeat2.room.roomId);
assert.ok(reservedSeat2.room.roomId);
assert.ok(room.hasReservedSeat(reservedSeat2.sessionId));
});
it("joinById() should allow to join a room by id", async () => {
const reservedSeat1 = await matchMaker.create("room2");
const reservedSeat2 = await matchMaker.joinById(reservedSeat1.room.roomId);
const room = matchMaker.getRoomById(reservedSeat2.room.roomId);
assert.strictEqual(reservedSeat1.room.roomId, reservedSeat2.room.roomId);
assert.ok(room.hasReservedSeat(reservedSeat2.sessionId));
});
it("joinById() should not allow to join a locked room", async () => {
const reservedSeat1 = await matchMaker.create("room2");
await matchMaker.joinById(reservedSeat1.room.roomId);
await assert.rejects(async () => await matchMaker.joinById(reservedSeat1.room.roomId), /locked/i);
});
it("joinById() should allow to join a private room", async () => {
const reservedSeat1 = await matchMaker.create("room2");
const room = matchMaker.getRoomById(reservedSeat1.room.roomId);
await room.setPrivate();
const reservedSeat2 = await matchMaker.joinById(reservedSeat1.room.roomId)
assert.strictEqual(reservedSeat1.room.roomId, reservedSeat2.room.roomId);
});
it("should throw error trying to create a room not defined", async () => {
await assert.rejects(async () => await matchMaker.joinOrCreate("non_existing_room"), /not defined/i);
await assert.rejects(async () => await matchMaker.create("non_existing_room"), /not defined/i);
});
it("filterBy(): filter by 'mode' field", async () => {
const reservedSeat1 = await matchMaker.joinOrCreate("room2_filtered", { mode: "squad" });
const reservedSeat2 = await matchMaker.joinOrCreate("room2_filtered", { mode: "duo" });
assert.notStrictEqual(reservedSeat1.room.roomId, reservedSeat2.room.roomId);
const reservedSeat3 = await matchMaker.joinOrCreate("room2_filtered", { mode: "squad" });
const reservedSeat4 = await matchMaker.joinOrCreate("room2_filtered", { mode: "duo" });
assert.strictEqual(reservedSeat1.room.roomId, reservedSeat3.room.roomId);
assert.strictEqual(reservedSeat2.room.roomId, reservedSeat4.room.roomId);
});
it("sortBy(): sort desc by 'clients' field", async () => {
await matchMaker.createRoom("room3_sorted_desc", { roomId: "aaa" });
await matchMaker.createRoom("room3_sorted_desc", { roomId: "bbb" });
await matchMaker.createRoom("room3_sorted_desc", { roomId: "ccc" });
// The RedisDriver do not rely on insertion order when querying for rooms.
const roomsCachedOrder = await matchMaker.query({});
const reservedSeat1 = await matchMaker.join("room3_sorted_desc");
assert.strictEqual(roomsCachedOrder[0].roomId, reservedSeat1.room.roomId);
const reservedSeat2 = await matchMaker.join("room3_sorted_desc");
assert.strictEqual(roomsCachedOrder[0].roomId, reservedSeat2.room.roomId);
const reservedSeat3 = await matchMaker.join("room3_sorted_desc");
assert.strictEqual(roomsCachedOrder[0].roomId, reservedSeat3.room.roomId);
const reservedSeat4 = await matchMaker.join("room3_sorted_desc");
assert.strictEqual(roomsCachedOrder[1].roomId, reservedSeat4.room.roomId);
const reservedSeat5 = await matchMaker.join("room3_sorted_desc");
assert.strictEqual(roomsCachedOrder[1].roomId, reservedSeat5.room.roomId);
const reservedSeat6 = await matchMaker.join("room3_sorted_desc");
assert.strictEqual(roomsCachedOrder[1].roomId, reservedSeat6.room.roomId);
const reservedSeat7 = await matchMaker.join("room3_sorted_desc");
assert.strictEqual(roomsCachedOrder[2].roomId, reservedSeat7.room.roomId);
const reservedSeat8 = await matchMaker.join("room3_sorted_desc");
assert.strictEqual(roomsCachedOrder[2].roomId, reservedSeat8.room.roomId);
const reservedSeat9 = await matchMaker.join("room3_sorted_desc");
assert.strictEqual(roomsCachedOrder[2].roomId, reservedSeat9.room.roomId);
});
it("sortBy(): sort asc by 'clients' field", async () => {
await matchMaker.createRoom("room3_sorted_asc", { roomId: "aaa" });
await matchMaker.createRoom("room3_sorted_asc", { roomId: "bbb" });
await matchMaker.createRoom("room3_sorted_asc", { roomId: "ccc" });
// The RedisDriver do not rely on insertion order when querying for rooms.
const roomsCachedOrder = await matchMaker.query({});
const reservedSeat1 = await matchMaker.join("room3_sorted_asc");
assert.strictEqual(roomsCachedOrder[0].roomId, reservedSeat1.room.roomId);
const reservedSeat2 = await matchMaker.join("room3_sorted_asc");
assert.strictEqual(roomsCachedOrder[1].roomId, reservedSeat2.room.roomId);
const reservedSeat3 = await matchMaker.join("room3_sorted_asc");
assert.strictEqual(roomsCachedOrder[2].roomId, reservedSeat3.room.roomId);
const reservedSeat4 = await matchMaker.join("room3_sorted_asc");
assert.strictEqual(roomsCachedOrder[0].roomId, reservedSeat4.room.roomId);
const reservedSeat5 = await matchMaker.join("room3_sorted_asc");
assert.strictEqual(roomsCachedOrder[1].roomId, reservedSeat5.room.roomId);
const reservedSeat6 = await matchMaker.join("room3_sorted_asc");
assert.strictEqual(roomsCachedOrder[2].roomId, reservedSeat6.room.roomId);
const reservedSeat7 = await matchMaker.join("room3_sorted_asc");
assert.strictEqual(roomsCachedOrder[0].roomId, reservedSeat7.room.roomId);
const reservedSeat8 = await matchMaker.join("room3_sorted_asc");
assert.strictEqual(roomsCachedOrder[1].roomId, reservedSeat8.room.roomId);
const reservedSeat9 = await matchMaker.join("room3_sorted_asc");
assert.strictEqual(roomsCachedOrder[2].roomId, reservedSeat9.room.roomId);
});
});
describe("query() for cached rooms", () => {
it("should list all", async () => {
// create 4 rooms
for (let i = 0; i < 4; i++) {
await matchMaker.create("dummy");
}
const rooms = await matchMaker.query({});
assert.strictEqual(4, rooms.length);
});
it("should list only public and unlocked rooms", async () => {
// create 4 public rooms
for (let i = 0; i < 4; i++) {
await matchMaker.create("dummy");
}
// create 2 private rooms
for (let i = 0; i < 2; i++) {
const reservedSeat = await matchMaker.create("dummy");
await matchMaker.remoteRoomCall(reservedSeat.room.roomId, "setPrivate");
}
//
for (let i = 0; i < 2; i++) {
const reservedSeat = await matchMaker.create("dummy");
await matchMaker.remoteRoomCall(reservedSeat.room.roomId, "lock");
}
assert.strictEqual(8, (await matchMaker.query({})).length);
assert.strictEqual(6, (await matchMaker.query({ private: false })).length);
assert.strictEqual(4, (await matchMaker.query({ private: false, locked: false })).length);
});
});
describe("reconnect", async () => {
it("should allow to reconnect", async () => {
const reservedSeat1 = await matchMaker.joinOrCreate("reconnect");
const client1 = createDummyClient(reservedSeat1);
const room = matchMaker.getRoomById(reservedSeat1.room.roomId);
await room._onJoin(client1 as any);
assert.strictEqual(1, room.clients.length);
client1.close();
await timeout(100);
let rooms = await matchMaker.query({});
assert.strictEqual(1, rooms.length);
assert.strictEqual(1, rooms[0].clients, "should keep seat reservation after disconnection");
await matchMaker.joinById(room.roomId, { sessionId: client1.sessionId });
await room._onJoin(client1 as any);
rooms = await matchMaker.query({});
assert.strictEqual(1, rooms.length);
assert.strictEqual(1, rooms[0].clients);
assert.strictEqual(1, room.clients.length);
client1.close();
await timeout(100);
});
it("should not allow to reconnect", async () => {
const reservedSeat1 = await matchMaker.joinOrCreate("reconnect");
const reservedSeat2 = await matchMaker.joinOrCreate("reconnect");
const client1 = createDummyClient(reservedSeat1);
const room = matchMaker.getRoomById(reservedSeat1.room.roomId);
await room._onJoin(client1 as any);
/**
* Create a second client so the room won't dispose
*/
const client2 = createDummyClient(reservedSeat2);
await room._onJoin(client2 as any);
assert.strictEqual(2, room.clients.length);
client1.close();
await timeout(250);
assert.strictEqual(1, room.clients.length);
await assert.rejects(async() => await matchMaker.joinById(room.roomId, { sessionId: client1.sessionId }), /expired/);
});
it("using token: should allow to reconnect", async () => {
const reservedSeat1 = await matchMaker.joinOrCreate("reconnect_token");
const client1 = createDummyClient(reservedSeat1);
const room = matchMaker.getRoomById(reservedSeat1.room.roomId) as ReconnectTokenRoom;
await room._onJoin(client1 as any);
assert.strictEqual(1, room.clients.length);
client1.close();
await timeout(100);
let rooms = await matchMaker.query({});
assert.strictEqual(1, rooms.length);
assert.strictEqual(1, rooms[0].clients, "should keep seat reservation after disconnection");
await matchMaker.joinById(room.roomId, { sessionId: client1.sessionId });
await room._onJoin(client1 as any);
rooms = await matchMaker.query({});
assert.strictEqual(1, rooms.length);
assert.strictEqual(1, rooms[0].clients);
assert.strictEqual(1, room.clients.length);
client1.close();
await timeout(100);
});
it("using token: should not allow to reconnect", async () => {
const reservedSeat1 = await matchMaker.joinOrCreate("reconnect_token");
const reservedSeat2 = await matchMaker.joinOrCreate("reconnect_token");
const client1 = createDummyClient(reservedSeat1);
const room = matchMaker.getRoomById(reservedSeat1.room.roomId) as ReconnectTokenRoom;
await room._onJoin(client1 as any);
/**
* Create a second client so the room won't dispose
*/
const client2 = createDummyClient(reservedSeat2);
await room._onJoin(client2 as any);
assert.strictEqual(2, room.clients.length);
client1.close();
await timeout(100);
room.token.reject();
await timeout(100);
assert.strictEqual(1, room.clients.length);
await assert.rejects(async() => await matchMaker.joinById(room.roomId, { sessionId: client1.sessionId }), /expired/);
});
});
// define the same tests using multiple drivers
it("when `maxClients` is reached, the room should be locked", async () => {
// first client joins
const reservedSeat1 = await matchMaker.joinOrCreate("room3");
const room = matchMaker.getRoomById(reservedSeat1.room.roomId);
assert.strictEqual(false, room.locked);
// more 2 clients join
await matchMaker.joinOrCreate("room3");
await matchMaker.joinOrCreate("room3");
const roomsBeforeExpiration = await matchMaker.query({});
assert.strictEqual(1, roomsBeforeExpiration.length);
assert.strictEqual(3, roomsBeforeExpiration[0].clients);
assert.strictEqual(true, room.locked);
assert.strictEqual(true, roomsBeforeExpiration[0].locked);
});
it("seat reservation should expire", async () => {
const reservedSeat1 = await matchMaker.joinOrCreate("room3");
const room = matchMaker.getRoomById(reservedSeat1.room.roomId);
assert.strictEqual(false, room.locked);
// more 2 clients join
await matchMaker.joinOrCreate("room3");
await matchMaker.joinOrCreate("room3");
const roomsBeforeExpiration = await matchMaker.query({});
assert.strictEqual(1, roomsBeforeExpiration.length);
assert.strictEqual(3, roomsBeforeExpiration[0].clients);
assert.strictEqual(true, roomsBeforeExpiration[0].locked);
// only 1 client actually joins the room, 2 of them are going to expire
await room._onJoin(createDummyClient(reservedSeat1) as any);
await timeout(DEFAULT_SEAT_RESERVATION_TIME * 1100);
// connect 2 clients to the same room again
await matchMaker.joinOrCreate("room3");
await matchMaker.joinOrCreate("room3");
const roomsAfterExpiration2 = await matchMaker.query({});
assert.strictEqual(1, roomsAfterExpiration2.length);
assert.strictEqual(3, roomsAfterExpiration2[0].clients);
assert.strictEqual(true, roomsAfterExpiration2[0].locked);
});
it("should automatically lock rooms", async () => {
const _firstRoom = await matchMaker.joinOrCreate("room3");
await matchMaker.joinOrCreate("room3");
await matchMaker.joinOrCreate("room3");
let rooms = await matchMaker.query({});
assert.strictEqual(1, rooms.length);
assert.strictEqual(3, rooms[0].clients);
assert.strictEqual(true, rooms[0].locked);
const _secondRoom = await matchMaker.joinOrCreate("room3");
rooms = await matchMaker.query({});
const firstRoom = rooms.find((r) => r.roomId === _firstRoom.room.roomId);
const secondRoom = rooms.find((r) => r.roomId === _secondRoom.room.roomId);
assert.strictEqual(2, rooms.length);
assert.strictEqual(3, firstRoom.clients);
assert.strictEqual(1, secondRoom.clients);
assert.strictEqual(true, firstRoom.locked);
assert.strictEqual(false, secondRoom.locked);
});
it("should allow to manually lock rooms", async () => {
const reservedSeat1 = await matchMaker.joinOrCreate("room3");
await matchMaker.remoteRoomCall(reservedSeat1.room.roomId, "lock");
const reservedSeat2 = await matchMaker.joinOrCreate("room3");
await matchMaker.remoteRoomCall(reservedSeat2.room.roomId, "lock");
const reservedSeat3 = await matchMaker.joinOrCreate("room3");
await matchMaker.remoteRoomCall(reservedSeat3.room.roomId, "lock");
let rooms = await matchMaker.query({});
assert.strictEqual(3, rooms.length);
assert.strictEqual(true, rooms[0].locked);
assert.strictEqual(true, rooms[1].locked);
assert.strictEqual(true, rooms[2].locked);
});
describe("concurrency", async () => {
it("should create 50 rooms", async () => {
const numConnections = 100;
const promises = [];
for (let i = 0; i < numConnections; i++) {
promises.push(new Promise<void>(async (resolve, reject) => {
try {
const reservedSeat = await matchMaker.joinOrCreate("room2");
const room = matchMaker.getRoomById(reservedSeat.room.roomId);
await room._onJoin(createDummyClient(reservedSeat) as any);
resolve();
} catch (e) {
reject();
}
}));
}
// await for all calls to be complete
const results = await Promise.all(promises);
assert.strictEqual(100, results.length);
const rooms = await matchMaker.query({});
assert.strictEqual(50, rooms.length);
for (let i = 0; i < Math.floor(numConnections / 2); i++) {
assert.strictEqual(2, rooms[i].clients);
assert.strictEqual(true,rooms[i].locked);
}
});
});
});
}
}); | the_stack |
import * as Express from 'express'
import * as Path from 'path'
import * as HTTP from 'http'
import * as SocketIo from 'socket.io'
import * as Tool from './tools/initSystem'
import * as Async from 'async'
import * as Fs from 'fs'
import * as Util from 'util'
import * as Uuid from 'node-uuid'
import * as Imap from './tools/imap'
import CoNETConnectCalss from './tools/coNETConnect'
import * as Crypto from 'crypto'
import * as mime from 'mime-types'
Express.static.mime.define({ 'multipart/related': ['mht'] })
//Express.static.mime.define({ 'message/rfc822' : ['mhtml','mht'] })
Express.static.mime.define({ 'application/x-mimearchive' : ['mhtml','mht'] })
Express.static.mime.define({ 'multipart/related' : ['mhtml','mht'] })
interface localConnect {
socket: SocketIO.Socket
login: boolean
listenAfterPasswd: boolean
}
let logFileFlag = 'w'
const conetImapAccount = /^qtgate_test\d\d?@icloud.com$/i
const saveLog = ( err: {} | string ) => {
if ( !err ) {
return
}
const data = `${ new Date().toUTCString () }: ${ typeof err === 'object' ? ( err['message'] ? err['message'] : '' ) : err }\r\n`
console.log ( data )
return Fs.appendFile ( Tool.ErrorLogFile, data, { flag: logFileFlag }, () => {
return logFileFlag = 'a'
})
}
const saveServerStartup = ( localIpaddress: string ) => {
const info = `\n*************************** CoNET Platform [ ${ Tool.CoNET_version } ] server start up *****************************\n` +
`Access url: http://${localIpaddress}:${ Tool.LocalServerPortNumber }\n`
saveLog ( info )
}
const saveServerStartupError = ( err: {} ) => {
const info = `\n*************************** CoNET Platform [ ${ Tool.CoNET_version } ] server startup falied *****************************\n` +
`platform ${ process.platform }\n` +
`${ err['message'] }\n`
saveLog ( info )
}
const imapErrorCallBack = ( message: string ) => {
if ( message && message.length ) {
if ( /auth|login|log in|Too many simultaneous|UNAVAILABLE/i.test( message )) {
return 1
}
if ( /ECONNREFUSED/i.test ( message )) {
return 5
}
if (/OVERQUOTA/i.test ( message )) {
return 6
}
if ( /certificate/i.test ( message )) {
return 2
}
if ( /timeout|ENOTFOUND/i.test ( message )) {
return 0
}
return 5
}
return -1
}
export default class localServer {
private expressServer = Express()
private httpServer = HTTP.createServer ( this.expressServer )
private socketServer = SocketIo ( this.httpServer )
private socketServer_CoSearch = this.socketServer.of ('/CoSearch')
public config: install_config = null
public keyPair: keypair = null
public savedPasswrod: string = ''
public imapConnectData: IinputData = null
public localConnected: Map < string, localConnect > = new Map ()
private CoNETConnectCalss: CoNETConnectCalss = null
private openPgpKeyOption = null
private sessionHashPool = []
private Pbkdf2Password = null
private nodeList = [{
email: 'node@Kloak.app',
keyID:'',
key: ''
}]
private requestPool: Map < string, SocketIO.Socket > = new Map()
private catchCmd ( mail: string, uuid: string ) {
if ( !this.imapConnectData.sendToQTGate ) {
this.imapConnectData.sendToQTGate = true
Tool.saveEncryptoData ( Tool.imapDataFileName1, this.imapConnectData, this.config, this.savedPasswrod, err => {
})
}
console.log ( `Get response from CoNET uuid [${ uuid }] length [${ mail.length }]`)
const socket = this.requestPool.get ( uuid )
if ( !socket ) {
return console.log (`Get cmd that have no matched socket \n\n`, mail )
}
socket.emit ( 'doingRequest', mail, uuid )
}
private tryConnectCoNET ( socket: SocketIO.Socket, sessionHash: string ) {
console.log (`doing tryConnectCoNET`)
// have CoGate connect
if ( this.CoNETConnectCalss ) {
return this.CoNETConnectCalss.Ping()
}
let sendMail = false
const _exitFunction = err => {
console.trace ( `makeConnect on _exitFunction err this.CoNETConnectCalss destroy!`, err )
this.CoNETConnectCalss = null
}
const makeConnect = () => {
return this.CoNETConnectCalss = new CoNETConnectCalss ( this.imapConnectData, this.socketServer, !this.imapConnectData.sendToQTGate, this.nodeList[0].email,
this.openPgpKeyOption, this.keyPair.publicKey, ( mail, uuid ) => {
return this.catchCmd ( mail, uuid )
}, _exitFunction )
}
return makeConnect ()
}
private listenAfterPassword ( socket: SocketIO.Socket, sessionHash: string ) {
socket.on ( 'checkImap', ( emailAddress: string, password: string, timeZone, tLang, CallBack1 ) => {
CallBack1()
console.log (`localServer on checkImap!`)
const imapServer = Tool.getImapSmtpHost( emailAddress )
this.imapConnectData = {
email: this.config.account,
account: this.config.account,
smtpServer: imapServer.smtp,
smtpUserName: emailAddress,
smtpPortNumber: imapServer.SmtpPort,
smtpSsl: imapServer.smtpSsl,
smtpIgnoreCertificate: false,
smtpUserPassword: password,
imapServer: imapServer.imap,
imapPortNumber: imapServer.ImapPort,
imapSsl: imapServer.imapSsl,
imapUserName: emailAddress,
imapIgnoreCertificate: false,
imapUserPassword: password,
timeZoneOffset: timeZone,
language: tLang,
imapTestResult: null,
clientFolder: Uuid.v4(),
serverFolder: Uuid.v4(),
randomPassword: Uuid.v4(),
uuid: Uuid.v4(),
confirmRisk: false,
clientIpAddress: null,
ciphers: null,
sendToQTGate: false
}
return this.doingCheckImap ( socket )
})
socket.on ( 'tryConnectCoNET', CallBack1 => {
const uuid = Uuid.v4()
CallBack1( uuid )
const _callBack = ( ...data ) => {
socket.emit ( uuid, ...data )
}
console.log (`socket on tryConnectCoNET!\n\n`)
if ( !this.imapConnectData ) {
console.log (`socket.on ( 'tryConnectCoNET') !this.imapConnectData \n\n `)
return _callBack ( 'systemError' )
}
if ( !this.imapConnectData.confirmRisk ) {
this.imapConnectData.confirmRisk = true
return Tool.saveEncryptoData ( Tool.imapDataFileName1, this.imapConnectData, this.config, this.savedPasswrod, err => {
return this.tryConnectCoNET ( socket, sessionHash )
})
}
return this.tryConnectCoNET ( socket, sessionHash )
})
socket.on ( 'sendRequestMail', CallBack1 => {
CallBack1 ()
if ( !this.CoNETConnectCalss ) {
return console.log (`localServer on sendRequestMail Error! have no this.CoNETConnectCalss!`)
}
socket.emit ( 'tryConnectCoNETStage', null, 2, false )
if ( this.CoNETConnectCalss ) {
console.log (`localWebServer on sendRequestMail !`)
return this.CoNETConnectCalss.sendRequestMail ()
}
console.log (`localWebServer on sendRequestMail have no CoNETConnectCalss create CoNETConnectCalss`)
return this.tryConnectCoNET ( socket, sessionHash )
})
socket.on ( 'checkActiveEmailSubmit', ( text, CallBack1 ) => {
const uuid = Uuid.v4()
CallBack1( uuid )
const _callBack = ( ...data ) => {
socket.emit ( uuid, ...data )
}
const key = Buffer.from ( text, 'base64' ).toString ()
console.log (`checkActiveEmailSubmit`, key )
if ( key && key.length ) {
console.log ( `active key success! \n[${ key }]`)
this.keyPair.publicKey = this.config.keypair.publicKey = key
this.keyPair.verified = this.config.keypair.verified = true
this.imapConnectData.sendToQTGate = true
_callBack ()
Tool.saveEncryptoData ( Tool.imapDataFileName1, this.imapConnectData, this.config, this.savedPasswrod, err => {
if ( err ) {
saveLog (`Tool.saveConfig return Error: [${ err.message }]`)
}
})
return Tool.saveConfig ( this.config, err => {
if ( err ) {
saveLog (`Tool.saveConfig return Error: [${ err.message }]`)
}
})
}
})
socket.on ( 'doingRequest', ( uuid, request, CallBack1 ) => {
const _uuid = Uuid.v4()
CallBack1 ( _uuid )
const _callBack = ( ...data ) => {
socket.emit ( _uuid, ...data )
}
this.requestPool.set ( uuid, socket )
console.log (`on doingRequest uuid = [${ uuid }]\n${ request }\n`)
if ( this.CoNETConnectCalss ) {
saveLog (`doingRequest on ${ uuid }`)
return this.CoNETConnectCalss.requestCoNET_v1 ( uuid, request, _callBack )
}
saveLog ( `doingRequest on ${ uuid } but have not CoNETConnectCalss need restart! socket.emit ( 'systemErr' )`)
socket.emit ( 'systemErr' )
})
socket.on ( 'getFilesFromImap', ( files: string, CallBack1 ) => {
const uuid = Uuid.v4()
CallBack1( uuid )
const _callBack = ( ...data ) => {
socket.emit ( uuid, ...data )
}
if ( typeof files !== 'string' || !files.length ) {
return _callBack ( new Error ('invalidRequest'))
}
const _files = files.split (',')
console.log (`socket.on ('getFilesFromImap') _files = [${ _files }] _files.length = [${ _files.length }]` )
let ret = ''
return Async.eachSeries ( _files, ( n, next ) => {
console.log (`Async.eachSeries _files[${ n }]`)
return this.CoNETConnectCalss.getFile ( n, ( err, data ) => {
if ( err ) {
return next ( err )
}
ret += data.toString ()
return next ()
})
}, err => {
if ( err ) {
return _callBack ( err )
}
//console.log (`******************** getFilesFromImap success all [${ ret.length }] fies!\n\n${ ret }\n\n`)
return _callBack ( null, ret )
})
})
socket.on ( 'sendMedia', ( uuid, rawData, CallBack1 ) => {
const _uuid = Uuid.v4()
CallBack1( _uuid )
const _callBack = ( ...data ) => {
socket.emit ( _uuid, ...data )
}
return this.CoNETConnectCalss.sendDataToANewUuidFolder ( Buffer.from ( rawData ).toString ( 'base64' ), uuid, uuid, _callBack )
})
socket.on ( 'mime', ( _mime, CallBack1 ) => {
const _uuid = Uuid.v4()
CallBack1( _uuid )
const _callBack = ( ...data ) => {
socket.emit ( _uuid, ...data )
}
let y = mime.lookup( _mime )
if ( !y ) {
return _callBack ( new Error ('no mime'))
}
return _callBack ( null, y )
})
/*
socket.on ('getUrl', ( url: string, CallBack ) => {
const uu = new URLSearchParams ( url )
if ( !uu || typeof uu.get !== 'function' ) {
console.log (`getUrl [${ url }] have not any URLSearchParams`)
return CallBack ()
}
return CallBack ( null, uu.get('imgrefurl'), uu.get('/imgres?imgurl'))
})
*/
}
private doingCheckImap ( socket: SocketIO.Socket ) {
this.imapConnectData.imapTestResult = false
return Async.series ([
next => Imap.imapAccountTest ( this.imapConnectData, err => {
if ( err ) {
return next ( err )
}
console.log (`imapAccountTest success!`, typeof next )
socket.emit ( 'imapTest' )
return next ()
}),
next => Tool.smtpVerify ( this.imapConnectData, next )
], ( err: Error ) => {
if ( err ) {
console.log (`doingCheckImap Async.series Error!`, err )
return socket.emit ( 'smtpTest', imapErrorCallBack ( err.message ))
}
this.imapConnectData.imapTestResult = true
return Tool.saveEncryptoData ( Tool.imapDataFileName1, this.imapConnectData, this.config, this.savedPasswrod, err => {
console.log (`socket.emit ( 'imapTestFinish' )`)
socket.emit ( 'imapTestFinish' , this.imapConnectData )
})
})
}
private socketServerConnected ( socket: SocketIO.Socket ) {
const clientName = `[${ socket.id }][ ${ socket.conn.remoteAddress }]`
let sessionHash = ''
const clientObj: localConnect = {
listenAfterPasswd: false,
socket: socket,
login: false
}
saveLog ( `socketServerConnected ${ clientName } connect ${ this.localConnected.size }`)
socket.once ( 'init', Callback1 => {
const uuid = Uuid.v4()
Callback1 ( uuid )
const ret = Tool.emitConfig ( this.config, false )
//console.log ( Util.inspect( ret, false, 3, true ))
//console.log ( `typeof Callback1 [${ typeof Callback1 }]`)
return socket.emit ( uuid, null, ret )
})
socket.once ( 'agreeClick', () => {
this.config.firstRun = false
return Tool.saveConfig ( this.config, saveLog )
})
socket.on ( 'checkPemPassword', ( password: string, CallBack1 ) => {
const uuid = Uuid.v4()
CallBack1 ( uuid )
this.sessionHashPool.push ( sessionHash = Crypto.randomBytes ( 10 ).toString ('hex'))
const passwordFail = ( imap ) => {
//onsole.log (`passwordFail this.Pbkdf2Password = [${ this.Pbkdf2Password }]`)
return socket.emit ( uuid, null, imap, this.Pbkdf2Password, sessionHash )
}
if ( !this.config.keypair || !this.config.keypair.publicKey ) {
console.log ( `checkPemPassword !this.config.keypair` )
return passwordFail ( true )
}
if ( !password || password.length < 5 ) {
console.log (`! password `)
return passwordFail ( true )
}
if ( this.savedPasswrod && this.savedPasswrod.length ) {
if ( this.savedPasswrod !== password ) {
console.log ( `savedPasswrod !== password `)
return passwordFail ( true )
}
this.listenAfterPassword ( socket, sessionHash )
return passwordFail ( this.imapConnectData )
}
return Async.waterfall ([
next => Tool.getPbkdf2 ( this.config, password, next ),
( Pbkdf2Password: Buffer, next ) => {
this.Pbkdf2Password = Pbkdf2Password.toString ( 'hex' )
Tool.getKeyPairInfo ( this.config.keypair.publicKey, this.config.keypair.privateKey, this.Pbkdf2Password, next )
},
( key, next ) => {
//console.log ( `checkPemPassword Tool.getKeyPairInfo success!`)
if ( ! key.passwordOK ) {
this.Pbkdf2Password = null
saveLog ( `[${ clientName }] on checkPemPassword had try password! [${ password }]` )
return passwordFail ( true )
}
//console.log (`checkPemPassword this.Pbkdf2Password = [${ this.Pbkdf2Password}]`)
this.savedPasswrod = password
this.keyPair = key
clientObj.listenAfterPasswd = clientObj.login = true
this.localConnected.set ( clientName, clientObj )
return Tool.makeGpgKeyOption ( this.config, this.savedPasswrod, next )
},
( option_KeyOption, next ) => {
console.log (`checkPemPassword Tool.makeGpgKeyOption success!`)
this.openPgpKeyOption = option_KeyOption
return Tool.readEncryptoFile ( Tool.imapDataFileName1, password, this.config, next )
}], ( err: Error, data: string ) => {
console.log (`checkPemPassword Async.waterfall success!`)
if ( err ) {
if ( !( err.message && /no such file/i.test( err.message ))) {
passwordFail ( err )
return saveLog ( `Tool.makeGpgKeyOption return err [${ err && err.message ? err.message : null }]` )
}
}
// console.log (`this.sessionHashPool.push!\n${ this.sessionHashPool }\n${ this.sessionHashPool.length }`)
this.listenAfterPassword ( socket, sessionHash )
try {
this.imapConnectData = JSON.parse ( data )
} catch ( ex ) {
return passwordFail ( ex )
}
this.localConnected.set ( clientName, clientObj )
return passwordFail ( this.imapConnectData )
})
})
socket.on ( 'deleteKeyPairNext', CallBack1 => {
CallBack1()
console.log ( `on deleteKeyPairNext` )
const thisConnect = this.localConnected.get ( clientName )
if ( this.localConnected.size > 1 && thisConnect && ! thisConnect.login ) {
console.log (`this.localConnected = [${ Util.inspect( this.localConnected, false, 2, true )}], thisConnect.login = [${ thisConnect.login }]`)
return this.socketServer.emit ( 'deleteKeyPairNoite' )
}
const info = `socket on deleteKeyPairNext, delete key pair now.`
saveLog ( info )
this.config = Tool.InitConfig ()
this.config.firstRun = false
this.keyPair = null
Tool.saveConfig ( this.config, saveLog )
if ( this.CoNETConnectCalss ) {
this.CoNETConnectCalss.destroy ( 2 )
this.CoNETConnectCalss = null
}
sessionHash = ''
Tool.deleteImapFile ()
return this.socketServer.emit ( 'init', null, this.config )
})
socket.on ( 'NewKeyPair', ( preData: INewKeyPair, CallBack1 ) => {
const uuid = Uuid.v4()
CallBack1( uuid )
const _callBack = ( ...data ) => {
socket.emit ( uuid, ...data )
}
// already have key pair
if ( this.config.keypair && this.config.keypair.createDate ) {
return saveLog (`[${ clientName }] on NewKeyPair but system already have keypair: ${ this.config.keypair.publicKeyID } stop and return keypair.`)
}
this.savedPasswrod = preData.password
return Tool.getPbkdf2 ( this.config, this.savedPasswrod, ( err, Pbkdf2Password: Buffer ) => {
if ( err ) {
saveLog ( `NewKeyPair getPbkdf2 Error: [${ err.message }]`)
return _callBack ('systemError')
}
preData.password = Pbkdf2Password.toString ( 'hex' )
//console.log (`preData.password = [${ preData.password }]`)
return Tool.newKeyPair( preData.email, preData.nikeName, preData.password, ( err, retData )=> {
if ( err ) {
console.log ( err )
_callBack ()
return saveLog (`CreateKeyPairProcess return err: [${ err.message }]`)
}
if ( ! retData ) {
const info = `newKeyPair return null key!`
saveLog ( info )
console.log ( info )
return _callBack ( )
}
if ( !clientObj.listenAfterPasswd ) {
clientObj.listenAfterPasswd = clientObj.login = true
this.localConnected.set ( clientName, clientObj )
this.sessionHashPool.push ( sessionHash = Crypto.randomBytes (10).toString ('hex'))
//console.log ( `this.sessionHashPool.push!\n${ this.sessionHashPool }\n${ this.sessionHashPool.length }`)
this.listenAfterPassword ( socket, sessionHash )
}
return Tool.getKeyPairInfo ( retData.publicKey, retData.privateKey, preData.password, ( err, key ) => {
if ( err ) {
const info = `Tool.getKeyPairInfo Error [${ err.message ? err.message : 'null err message '}]`
return _callBack ( 'systemError' )
}
this.keyPair = this.config.keypair = key
this.config.account = this.config.keypair.email
return Tool.makeGpgKeyOption ( this.config, this.savedPasswrod, ( err, data ) => {
if ( err ) {
return saveLog ( err.message )
}
this.openPgpKeyOption = data
Tool.saveConfig ( this.config, saveLog )
return _callBack ( null, this.config.keypair, sessionHash )
})
})
})
})
})
}
constructor( private cmdResponse: ( cmd: QTGateAPIRequestCommand ) => void, test: boolean ) {
//Express.static.mime.define({ 'message/rfc822' : ['mhtml','mht'] })
//Express.static.mime.define ({ 'multipart/related' : ['mhtml','mht'] })
Express.static.mime.define ({ 'application/x-mimearchive' : ['mhtml','mht'] })
this.expressServer.set ( 'views', Path.join ( __dirname, 'views' ))
this.expressServer.set ( 'view engine', 'pug' )
this.expressServer.use ( Express.static ( Tool.QTGateFolder ))
this.expressServer.use ( Express.static ( Path.join ( __dirname, 'public' )))
this.expressServer.use ( Express.static ( Path.join ( __dirname, 'html' )))
this.expressServer.get ( '/', ( req, res ) => {
res.render( 'home', { title: 'home', proxyErr: false })
})
this.socketServer.on ( 'connection', socker => {
return this.socketServerConnected ( socker )
})
this.httpServer.once ( 'error', err => {
console.log (`httpServer error`, err )
saveServerStartupError ( err )
return process.exit (1)
})
Async.series ([
next => Tool.checkSystemFolder ( next ),
next => Tool.checkConfig ( next )
], ( err, data ) => {
if ( err ) {
return saveServerStartupError ( err )
}
this.config = data['1']
if ( !test ) {
this.httpServer.listen ( Tool.LocalServerPortNumber, () => {
return saveServerStartup ( `localhost`)
})
}
})
}
} | the_stack |
import { createElement } from '@syncfusion/ej2-base';
import { Diagram } from '../../../src/diagram/diagram';
import { NodeModel } from '../../../src/diagram/objects/node-model';
import { Node } from '../../../src/diagram/objects/node';
import { MouseEvents } from '../interaction/mouseevents.spec';
import { ConnectorModel, PathModel, BasicShapeModel } from '../../../src';
import {profile , inMB, getMemoryProfile} from '../../../spec/common.spec';
/**
* Annotations - Alignments
*/
describe('Diagram Control', () => {
describe('Annotation alignment- horizontal center', () => {
let diagram: Diagram;
let ele: HTMLElement;
let pathData: string = 'M540.3643,137.9336L546.7973,159.7016L570.3633,159.7296L550.7723,171.9366L558.9053,194.9966L540.3643,'
+ '179.4996L521.8223,194.9966L529.9553,171.9366L510.3633,159.7296L533.9313,159.7016L540.3643,137.9336z';
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram53' });
document.body.appendChild(ele);
let node: NodeModel = {
id: 'node',
width: 100, height: 100,
offsetX: 100, offsetY: 100,
shape: { type: 'Path', data: pathData },
annotations: [{
style: { strokeColor: 'black', opacity: 0.5 },
content: 'center center',
height: 50,
offset: { x: 0.5, y: 0.5 },
horizontalAlignment: 'Center',
verticalAlignment: 'Center',
}]
};
let node2: NodeModel = {
id: 'node2',
width: 100, height: 100,
offsetX: 300, offsetY: 100,
shape: { type: 'Path', data: pathData },
annotations: [{
style: { strokeColor: 'black', opacity: 0.5 },
content: 'top center',
height: 50,
offset: { x: 0.5, y: 0.5 },
horizontalAlignment: 'Center',
verticalAlignment: 'Top',
}]
};
let node3: NodeModel = {
id: 'node3',
width: 100, height: 100,
offsetX: 500, offsetY: 100,
shape: { type: 'Path', data: pathData },
annotations: [{
style: { strokeColor: 'black', opacity: 0.5 },
content: 'bottom center',
height: 50,
offset: { x: 0.5, y: 0.5 },
horizontalAlignment: 'Center',
verticalAlignment: 'Bottom',
}]
};
let node4: NodeModel = {
id: 'node4',
width: 100, height: 100,
offsetX: 700, offsetY: 100,
shape: { type: 'Path', data: pathData },
annotations: [{
style: { strokeColor: 'black', opacity: 0.5 },
content: 'stretch center',
height: 50,
offset: { x: 0.5, y: 0.5 },
horizontalAlignment: 'Center',
verticalAlignment: 'Stretch',
}]
};
diagram = new Diagram({ mode: 'Canvas', width: 800, height: 800, nodes: [node, node2, node3, node4] });
diagram.appendTo('#diagram53');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking horizontal center annotation alignment', (done: Function) => {
expect((diagram.nodes[0] as Node).wrapper.children[1].offsetX === 100
&& (diagram.nodes[0] as Node).wrapper.children[1].offsetY === 100 &&
(diagram.nodes[1] as Node).wrapper.children[1].offsetX === 300 &&
(diagram.nodes[1] as Node).wrapper.children[1].offsetY === 125 &&
(diagram.nodes[2] as Node).wrapper.children[1].offsetX === 500 &&
(diagram.nodes[2] as Node).wrapper.children[1].offsetY === 75 &&
(diagram.nodes[3] as Node).wrapper.children[1].offsetX === 700 &&
(diagram.nodes[3] as Node).wrapper.children[1].offsetY === 100).toBe(true);
done();
});
it('Checking horizontal left annotation alignment', (done: Function) => {
(diagram.nodes[0] as NodeModel).annotations[0].horizontalAlignment = 'Left';
(diagram.nodes[1] as NodeModel).annotations[0].horizontalAlignment = 'Left';
(diagram.nodes[2] as NodeModel).annotations[0].horizontalAlignment = 'Left';
(diagram.nodes[3] as NodeModel).annotations[0].horizontalAlignment = 'Left';
diagram.dataBind();
expect((diagram.nodes[0] as Node).wrapper.children[1].offsetX === 150
&& (diagram.nodes[0] as Node).wrapper.children[1].offsetY === 100 &&
(diagram.nodes[1] as Node).wrapper.children[1].offsetX === 350 &&
(diagram.nodes[1] as Node).wrapper.children[1].offsetY === 125 &&
(diagram.nodes[2] as Node).wrapper.children[1].offsetX === 550 &&
(diagram.nodes[2] as Node).wrapper.children[1].offsetY === 75 &&
(diagram.nodes[3] as Node).wrapper.children[1].offsetX === 750 &&
(diagram.nodes[3] as Node).wrapper.children[1].offsetY === 100).toBe(true);
done();
});
it('Checking horizontal right annotation alignment', (done: Function) => {
(diagram.nodes[0] as NodeModel).annotations[0].horizontalAlignment = 'Right';
(diagram.nodes[1] as NodeModel).annotations[0].horizontalAlignment = 'Right';
(diagram.nodes[2] as NodeModel).annotations[0].horizontalAlignment = 'Right';
(diagram.nodes[3] as NodeModel).annotations[0].horizontalAlignment = 'Right';
diagram.dataBind();
expect((diagram.nodes[0] as Node).wrapper.children[1].offsetX === 50
&& (diagram.nodes[0] as Node).wrapper.children[1].offsetY === 100 &&
(diagram.nodes[1] as Node).wrapper.children[1].offsetX === 250 &&
(diagram.nodes[1] as Node).wrapper.children[1].offsetY === 125 &&
(diagram.nodes[2] as Node).wrapper.children[1].offsetX === 450 &&
(diagram.nodes[2] as Node).wrapper.children[1].offsetY === 75 &&
(diagram.nodes[3] as Node).wrapper.children[1].offsetX === 650 &&
(diagram.nodes[3] as Node).wrapper.children[1].offsetY === 100).toBe(true);
done();
});
it('Checking horizontal stretch annotation alignment', (done: Function) => {
(diagram.nodes[0] as NodeModel).annotations[0].horizontalAlignment = 'Stretch';
(diagram.nodes[1] as NodeModel).annotations[0].horizontalAlignment = 'Stretch';
(diagram.nodes[2] as NodeModel).annotations[0].horizontalAlignment = 'Stretch';
(diagram.nodes[3] as NodeModel).annotations[0].horizontalAlignment = 'Stretch';
diagram.dataBind();
expect((diagram.nodes[0] as Node).wrapper.children[1].offsetX === 100
&& (diagram.nodes[0] as Node).wrapper.children[1].offsetY === 100 &&
(diagram.nodes[1] as Node).wrapper.children[1].offsetX === 300 &&
(diagram.nodes[1] as Node).wrapper.children[1].offsetY === 125 &&
(diagram.nodes[2] as Node).wrapper.children[1].offsetX === 500 &&
(diagram.nodes[2] as Node).wrapper.children[1].offsetY === 75 &&
(diagram.nodes[3] as Node).wrapper.children[1].offsetX === 700 &&
(diagram.nodes[3] as Node).wrapper.children[1].offsetY === 100).toBe(true);
done();
});
});
describe('Annotation editing', () => {
let diagram: Diagram;
let ele: HTMLElement;
let mouseEvents: MouseEvents = new MouseEvents();
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagramannotationEditing' });
document.body.appendChild(ele);
let node: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 100, offsetY: 100 };
diagram = new Diagram({
mode: 'Canvas',
width: '600px', height: '600px',
nodes: [node]
});
diagram.appendTo('#diagramannotationEditing');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking without label', (done: Function) => {
let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content');
mouseEvents.clickEvent(diagramCanvas, 100, 100);
mouseEvents.dblclickEvent(diagramCanvas, 100, 100);
mouseEvents.clickEvent(diagramCanvas, 200, 200);
expect((diagram.nodes[0] as NodeModel).annotations.length > 0).toBe(true);
done();
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
});
}); | the_stack |
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CdkTreeModule } from '@angular/cdk/tree';
import { DragDropModule } from '@angular/cdk/drag-drop';
import { NouisliderModule } from 'ng2-nouislider';
import { NgbDatepickerModule, NgbModule, NgbTimepickerModule, NgbTypeaheadModule } from '@ng-bootstrap/ng-bootstrap';
import { MissingTranslationHandler, TranslateModule } from '@ngx-translate/core';
import { NgxPaginationModule } from 'ngx-pagination';
import { FileUploadModule } from 'ng2-file-upload';
import { InfiniteScrollModule } from 'ngx-infinite-scroll';
import { DYNAMIC_FORM_CONTROL_MAP_FN, DynamicFormsCoreModule } from '@ng-dynamic-forms/core';
import { DynamicFormsNGBootstrapUIModule } from '@ng-dynamic-forms/ui-ng-bootstrap';
import { TextMaskModule } from 'angular2-text-mask';
import { MomentModule } from 'ngx-moment';
import { ComcolRoleComponent } from './comcol-forms/edit-comcol-page/comcol-role/comcol-role.component';
import { ConfirmationModalComponent } from './confirmation-modal/confirmation-modal.component';
import { ExportMetadataSelectorComponent } from './dso-selector/modal-wrappers/export-metadata-selector/export-metadata-selector.component';
import { FileDropzoneNoUploaderComponent } from './file-dropzone-no-uploader/file-dropzone-no-uploader.component';
import { ItemListElementComponent } from './object-list/item-list-element/item-types/item/item-list-element.component';
import { EnumKeysPipe } from './utils/enum-keys-pipe';
import { FileSizePipe } from './utils/file-size-pipe';
import { MetadataFieldValidator } from './utils/metadatafield-validator.directive';
import { SafeUrlPipe } from './utils/safe-url-pipe';
import { ConsolePipe } from './utils/console.pipe';
import { CollectionListElementComponent } from './object-list/collection-list-element/collection-list-element.component';
import { CommunityListElementComponent } from './object-list/community-list-element/community-list-element.component';
import { SearchResultListElementComponent } from './object-list/search-result-list-element/search-result-list-element.component';
import { ObjectListComponent } from './object-list/object-list.component';
import { CollectionGridElementComponent } from './object-grid/collection-grid-element/collection-grid-element.component';
import { CommunityGridElementComponent } from './object-grid/community-grid-element/community-grid-element.component';
import { AbstractListableElementComponent } from './object-collection/shared/object-collection-element/abstract-listable-element.component';
import { ObjectGridComponent } from './object-grid/object-grid.component';
import { ObjectCollectionComponent } from './object-collection/object-collection.component';
import { ComcolPageContentComponent } from './comcol-page-content/comcol-page-content.component';
import { ComcolPageHandleComponent } from './comcol-page-handle/comcol-page-handle.component';
import { ComcolPageHeaderComponent } from './comcol-page-header/comcol-page-header.component';
import { ComcolPageLogoComponent } from './comcol-page-logo/comcol-page-logo.component';
import { ErrorComponent } from './error/error.component';
import { LoadingComponent } from './loading/loading.component';
import { PaginationComponent } from './pagination/pagination.component';
import { ThumbnailComponent } from '../thumbnail/thumbnail.component';
import { SearchFormComponent } from './search-form/search-form.component';
import { SearchResultGridElementComponent } from './object-grid/search-result-grid-element/search-result-grid-element.component';
import { ViewModeSwitchComponent } from './view-mode-switch/view-mode-switch.component';
import { VarDirective } from './utils/var.directive';
import { AuthNavMenuComponent } from './auth-nav-menu/auth-nav-menu.component';
import { LogOutComponent } from './log-out/log-out.component';
import { FormComponent } from './form/form.component';
import { DsDynamicOneboxComponent } from './form/builder/ds-dynamic-form-ui/models/onebox/dynamic-onebox.component';
import { DsDynamicScrollableDropdownComponent } from './form/builder/ds-dynamic-form-ui/models/scrollable-dropdown/dynamic-scrollable-dropdown.component';
import {
DsDynamicFormControlContainerComponent,
dsDynamicFormControlMapFn,
} from './form/builder/ds-dynamic-form-ui/ds-dynamic-form-control-container.component';
import { DsDynamicFormComponent } from './form/builder/ds-dynamic-form-ui/ds-dynamic-form.component';
import { DragClickDirective } from './utils/drag-click.directive';
import { TruncatePipe } from './utils/truncate.pipe';
import { TruncatableComponent } from './truncatable/truncatable.component';
import { TruncatableService } from './truncatable/truncatable.service';
import { TruncatablePartComponent } from './truncatable/truncatable-part/truncatable-part.component';
import { UploaderComponent } from './uploader/uploader.component';
import { ChipsComponent } from './chips/chips.component';
import { DsDynamicTagComponent } from './form/builder/ds-dynamic-form-ui/models/tag/dynamic-tag.component';
import { DsDynamicListComponent } from './form/builder/ds-dynamic-form-ui/models/list/dynamic-list.component';
import { DsDynamicFormGroupComponent } from './form/builder/ds-dynamic-form-ui/models/form-group/dynamic-form-group.component';
import { DsDynamicFormArrayComponent } from './form/builder/ds-dynamic-form-ui/models/array-group/dynamic-form-array.component';
import { DsDynamicRelationGroupComponent } from './form/builder/ds-dynamic-form-ui/models/relation-group/dynamic-relation-group.components';
import { DsDatePickerInlineComponent } from './form/builder/ds-dynamic-form-ui/models/date-picker-inline/dynamic-date-picker-inline.component';
import { NumberPickerComponent } from './number-picker/number-picker.component';
import { DsDatePickerComponent } from './form/builder/ds-dynamic-form-ui/models/date-picker/date-picker.component';
import { DsDynamicLookupComponent } from './form/builder/ds-dynamic-form-ui/models/lookup/dynamic-lookup.component';
import { MockAdminGuard } from './mocks/admin-guard.service.mock';
import { AlertComponent } from './alert/alert.component';
import { SearchResultDetailElementComponent } from './object-detail/my-dspace-result-detail-element/search-result-detail-element.component';
import { ClaimedTaskActionsComponent } from './mydspace-actions/claimed-task/claimed-task-actions.component';
import { PoolTaskActionsComponent } from './mydspace-actions/pool-task/pool-task-actions.component';
import { ObjectDetailComponent } from './object-detail/object-detail.component';
import { ItemDetailPreviewComponent } from './object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component';
import { MyDSpaceItemStatusComponent } from './object-collection/shared/mydspace-item-status/my-dspace-item-status.component';
import { WorkspaceitemActionsComponent } from './mydspace-actions/workspaceitem/workspaceitem-actions.component';
import { WorkflowitemActionsComponent } from './mydspace-actions/workflowitem/workflowitem-actions.component';
import { ItemSubmitterComponent } from './object-collection/shared/mydspace-item-submitter/item-submitter.component';
import { ItemActionsComponent } from './mydspace-actions/item/item-actions.component';
import { ClaimedTaskActionsApproveComponent } from './mydspace-actions/claimed-task/approve/claimed-task-actions-approve.component';
import { ClaimedTaskActionsRejectComponent } from './mydspace-actions/claimed-task/reject/claimed-task-actions-reject.component';
import { ObjNgFor } from './utils/object-ngfor.pipe';
import { BrowseByComponent } from './browse-by/browse-by.component';
import { BrowseEntryListElementComponent } from './object-list/browse-entry-list-element/browse-entry-list-element.component';
import { DebounceDirective } from './utils/debounce.directive';
import { ClickOutsideDirective } from './utils/click-outside.directive';
import { EmphasizePipe } from './utils/emphasize.pipe';
import { InputSuggestionsComponent } from './input-suggestions/input-suggestions.component';
import { CapitalizePipe } from './utils/capitalize.pipe';
import { ObjectKeysPipe } from './utils/object-keys-pipe';
import { AuthorityConfidenceStateDirective } from './authority-confidence/authority-confidence-state.directive';
import { LangSwitchComponent } from './lang-switch/lang-switch.component';
import { PlainTextMetadataListElementComponent } from './object-list/metadata-representation-list-element/plain-text/plain-text-metadata-list-element.component';
import { ItemMetadataListElementComponent } from './object-list/metadata-representation-list-element/item/item-metadata-list-element.component';
import { MetadataRepresentationListElementComponent } from './object-list/metadata-representation-list-element/metadata-representation-list-element.component';
import { ComColFormComponent } from './comcol-forms/comcol-form/comcol-form.component';
import { CreateComColPageComponent } from './comcol-forms/create-comcol-page/create-comcol-page.component';
import { EditComColPageComponent } from './comcol-forms/edit-comcol-page/edit-comcol-page.component';
import { DeleteComColPageComponent } from './comcol-forms/delete-comcol-page/delete-comcol-page.component';
import { ObjectValuesPipe } from './utils/object-values-pipe';
import { InListValidator } from './utils/in-list-validator.directive';
import { AutoFocusDirective } from './utils/auto-focus.directive';
import { ComcolPageBrowseByComponent } from './comcol-page-browse-by/comcol-page-browse-by.component';
import { StartsWithDateComponent } from './starts-with/date/starts-with-date.component';
import { StartsWithTextComponent } from './starts-with/text/starts-with-text.component';
import { DSOSelectorComponent } from './dso-selector/dso-selector/dso-selector.component';
import { CreateCommunityParentSelectorComponent } from './dso-selector/modal-wrappers/create-community-parent-selector/create-community-parent-selector.component';
import { CreateItemParentSelectorComponent } from './dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component';
import { CreateCollectionParentSelectorComponent } from './dso-selector/modal-wrappers/create-collection-parent-selector/create-collection-parent-selector.component';
import { CommunitySearchResultListElementComponent } from './object-list/search-result-list-element/community-search-result/community-search-result-list-element.component';
import { CollectionSearchResultListElementComponent } from './object-list/search-result-list-element/collection-search-result/collection-search-result-list-element.component';
import { EditItemSelectorComponent } from './dso-selector/modal-wrappers/edit-item-selector/edit-item-selector.component';
import { EditCommunitySelectorComponent } from './dso-selector/modal-wrappers/edit-community-selector/edit-community-selector.component';
import { EditCollectionSelectorComponent } from './dso-selector/modal-wrappers/edit-collection-selector/edit-collection-selector.component';
import { ItemListPreviewComponent } from './object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component';
import { MetadataFieldWrapperComponent } from '../item-page/field-components/metadata-field-wrapper/metadata-field-wrapper.component';
import { MetadataValuesComponent } from '../item-page/field-components/metadata-values/metadata-values.component';
import { RoleDirective } from './roles/role.directive';
import { UserMenuComponent } from './auth-nav-menu/user-menu/user-menu.component';
import { ClaimedTaskActionsReturnToPoolComponent } from './mydspace-actions/claimed-task/return-to-pool/claimed-task-actions-return-to-pool.component';
import { ItemDetailPreviewFieldComponent } from './object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component';
import { DsDynamicLookupRelationModalComponent } from './form/builder/ds-dynamic-form-ui/relation-lookup-modal/dynamic-lookup-relation-modal.component';
import { SearchResultsComponent } from './search/search-results/search-results.component';
import { SearchSidebarComponent } from './search/search-sidebar/search-sidebar.component';
import { SearchSettingsComponent } from './search/search-settings/search-settings.component';
import { CollectionSearchResultGridElementComponent } from './object-grid/search-result-grid-element/collection-search-result/collection-search-result-grid-element.component';
import { CommunitySearchResultGridElementComponent } from './object-grid/search-result-grid-element/community-search-result/community-search-result-grid-element.component';
import { SearchFiltersComponent } from './search/search-filters/search-filters.component';
import { SearchFilterComponent } from './search/search-filters/search-filter/search-filter.component';
import { SearchFacetFilterComponent } from './search/search-filters/search-filter/search-facet-filter/search-facet-filter.component';
import { SearchLabelsComponent } from './search/search-labels/search-labels.component';
import { SearchFacetFilterWrapperComponent } from './search/search-filters/search-filter/search-facet-filter-wrapper/search-facet-filter-wrapper.component';
import { SearchRangeFilterComponent } from './search/search-filters/search-filter/search-range-filter/search-range-filter.component';
import { SearchTextFilterComponent } from './search/search-filters/search-filter/search-text-filter/search-text-filter.component';
import { SearchHierarchyFilterComponent } from './search/search-filters/search-filter/search-hierarchy-filter/search-hierarchy-filter.component';
import { SearchBooleanFilterComponent } from './search/search-filters/search-filter/search-boolean-filter/search-boolean-filter.component';
import { SearchFacetOptionComponent } from './search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component';
import { SearchFacetSelectedOptionComponent } from './search/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component';
import { SearchFacetRangeOptionComponent } from './search/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component';
import { SearchSwitchConfigurationComponent } from './search/search-switch-configuration/search-switch-configuration.component';
import { SearchAuthorityFilterComponent } from './search/search-filters/search-filter/search-authority-filter/search-authority-filter.component';
import { DsDynamicDisabledComponent } from './form/builder/ds-dynamic-form-ui/models/disabled/dynamic-disabled.component';
import { DsDynamicLookupRelationSearchTabComponent } from './form/builder/ds-dynamic-form-ui/relation-lookup-modal/search-tab/dynamic-lookup-relation-search-tab.component';
import { DsDynamicLookupRelationSelectionTabComponent } from './form/builder/ds-dynamic-form-ui/relation-lookup-modal/selection-tab/dynamic-lookup-relation-selection-tab.component';
import { PageSizeSelectorComponent } from './page-size-selector/page-size-selector.component';
import { AbstractTrackableComponent } from './trackable/abstract-trackable.component';
import { ComcolMetadataComponent } from './comcol-forms/edit-comcol-page/comcol-metadata/comcol-metadata.component';
import { ItemSelectComponent } from './object-select/item-select/item-select.component';
import { CollectionSelectComponent } from './object-select/collection-select/collection-select.component';
import { FilterInputSuggestionsComponent } from './input-suggestions/filter-suggestions/filter-input-suggestions.component';
import { DsoInputSuggestionsComponent } from './input-suggestions/dso-input-suggestions/dso-input-suggestions.component';
import { ItemGridElementComponent } from './object-grid/item-grid-element/item-types/item/item-grid-element.component';
import { TypeBadgeComponent } from './object-list/type-badge/type-badge.component';
import { MetadataRepresentationLoaderComponent } from './metadata-representation/metadata-representation-loader.component';
import { MetadataRepresentationDirective } from './metadata-representation/metadata-representation.directive';
import { ListableObjectComponentLoaderComponent } from './object-collection/shared/listable-object/listable-object-component-loader.component';
import { ItemSearchResultListElementComponent } from './object-list/search-result-list-element/item-search-result/item-types/item/item-search-result-list-element.component';
import { ListableObjectDirective } from './object-collection/shared/listable-object/listable-object.directive';
import { SearchLabelComponent } from './search/search-labels/search-label/search-label.component';
import { ItemMetadataRepresentationListElementComponent } from './object-list/metadata-representation-list-element/item/item-metadata-representation-list-element.component';
import { PageWithSidebarComponent } from './sidebar/page-with-sidebar.component';
import { SidebarDropdownComponent } from './sidebar/sidebar-dropdown.component';
import { SidebarFilterComponent } from './sidebar/filter/sidebar-filter.component';
import { SidebarFilterSelectedOptionComponent } from './sidebar/filter/sidebar-filter-selected-option.component';
import { SelectableListItemControlComponent } from './object-collection/shared/selectable-list-item-control/selectable-list-item-control.component';
import { DsDynamicLookupRelationExternalSourceTabComponent } from './form/builder/ds-dynamic-form-ui/relation-lookup-modal/external-source-tab/dynamic-lookup-relation-external-source-tab.component';
import { ExternalSourceEntryImportModalComponent } from './form/builder/ds-dynamic-form-ui/relation-lookup-modal/external-source-tab/external-source-entry-import-modal/external-source-entry-import-modal.component';
import { ImportableListItemControlComponent } from './object-collection/shared/importable-list-item-control/importable-list-item-control.component';
import { ExistingMetadataListElementComponent } from './form/builder/ds-dynamic-form-ui/existing-metadata-list-element/existing-metadata-list-element.component';
import { ItemVersionsComponent } from './item/item-versions/item-versions.component';
import { SortablejsModule } from 'ngx-sortablejs';
import { LogInContainerComponent } from './log-in/container/log-in-container.component';
import { LogInShibbolethComponent } from './log-in/methods/shibboleth/log-in-shibboleth.component';
import { LogInPasswordComponent } from './log-in/methods/password/log-in-password.component';
import { LogInComponent } from './log-in/log-in.component';
import { CustomSwitchComponent } from './form/builder/ds-dynamic-form-ui/models/custom-switch/custom-switch.component';
import { BundleListElementComponent } from './object-list/bundle-list-element/bundle-list-element.component';
import { MissingTranslationHelper } from './translate/missing-translation.helper';
import { ItemVersionsNoticeComponent } from './item/item-versions/notice/item-versions-notice.component';
import { FileValidator } from './utils/require-file.validator';
import { FileValueAccessorDirective } from './utils/file-value-accessor.directive';
import { FileSectionComponent } from '../item-page/simple/field-components/file-section/file-section.component';
import { ExistingRelationListElementComponent } from './form/builder/ds-dynamic-form-ui/existing-relation-list-element/existing-relation-list-element.component';
import { ModifyItemOverviewComponent } from '../item-page/edit-item-page/modify-item-overview/modify-item-overview.component';
import { ClaimedTaskActionsLoaderComponent } from './mydspace-actions/claimed-task/switcher/claimed-task-actions-loader.component';
import { ClaimedTaskActionsDirective } from './mydspace-actions/claimed-task/switcher/claimed-task-actions.directive';
import { ClaimedTaskActionsEditMetadataComponent } from './mydspace-actions/claimed-task/edit-metadata/claimed-task-actions-edit-metadata.component';
import { ImpersonateNavbarComponent } from './impersonate-navbar/impersonate-navbar.component';
import { ResourcePoliciesComponent } from './resource-policies/resource-policies.component';
import { NgForTrackByIdDirective } from './ng-for-track-by-id.directive';
import { ResourcePolicyFormComponent } from './resource-policies/form/resource-policy-form.component';
import { EpersonGroupListComponent } from './resource-policies/form/eperson-group-list/eperson-group-list.component';
import { ResourcePolicyTargetResolver } from './resource-policies/resolvers/resource-policy-target.resolver';
import { ResourcePolicyResolver } from './resource-policies/resolvers/resource-policy.resolver';
import { EpersonSearchBoxComponent } from './resource-policies/form/eperson-group-list/eperson-search-box/eperson-search-box.component';
import { GroupSearchBoxComponent } from './resource-policies/form/eperson-group-list/group-search-box/group-search-box.component';
import { FileDownloadLinkComponent } from './file-download-link/file-download-link.component';
import { CollectionDropdownComponent } from './collection-dropdown/collection-dropdown.component';
import { EntityDropdownComponent } from './entity-dropdown/entity-dropdown.component';
import { DsSelectComponent } from './ds-select/ds-select.component';
import { VocabularyTreeviewComponent } from './vocabulary-treeview/vocabulary-treeview.component';
import { CurationFormComponent } from '../curation-form/curation-form.component';
import { PublicationSidebarSearchListElementComponent } from './object-list/sidebar-search-list-element/item-types/publication/publication-sidebar-search-list-element.component';
import { SidebarSearchListElementComponent } from './object-list/sidebar-search-list-element/sidebar-search-list-element.component';
import { CollectionSidebarSearchListElementComponent } from './object-list/sidebar-search-list-element/collection/collection-sidebar-search-list-element.component';
import { CommunitySidebarSearchListElementComponent } from './object-list/sidebar-search-list-element/community/community-sidebar-search-list-element.component';
import { AuthorizedCollectionSelectorComponent } from './dso-selector/dso-selector/authorized-collection-selector/authorized-collection-selector.component';
import { DsoPageEditButtonComponent } from './dso-page/dso-page-edit-button/dso-page-edit-button.component';
import { DsoPageVersionButtonComponent } from './dso-page/dso-page-version-button/dso-page-version-button.component';
import { HoverClassDirective } from './hover-class.directive';
import { ValidationSuggestionsComponent } from './input-suggestions/validation-suggestions/validation-suggestions.component';
import { ItemAlertsComponent } from './item/item-alerts/item-alerts.component';
import { ItemSearchResultGridElementComponent } from './object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component';
import { ResourcePolicyEditComponent } from './resource-policies/edit/resource-policy-edit.component';
import { ResourcePolicyCreateComponent } from './resource-policies/create/resource-policy-create.component';
import { SearchObjects } from './search/search-objects.model';
import { SearchResult } from './search/search-result.model';
import { FacetConfigResponse } from './search/facet-config-response.model';
import { FacetValues } from './search/facet-values.model';
import { BitstreamDownloadPageComponent } from './bitstream-download-page/bitstream-download-page.component';
import { GenericItemPageFieldComponent } from '../item-page/simple/field-components/specific-field/generic/generic-item-page-field.component';
import { MetadataRepresentationListComponent } from '../item-page/simple/metadata-representation-list/metadata-representation-list.component';
import { RelatedItemsComponent } from '../item-page/simple/related-items/related-items-component';
import { TabbedRelatedEntitiesSearchComponent } from '../item-page/simple/related-entities/tabbed-related-entities-search/tabbed-related-entities-search.component';
import { RelatedEntitiesSearchComponent } from '../item-page/simple/related-entities/related-entities-search/related-entities-search.component';
import { ConfigurationSearchPageComponent } from '../search-page/configuration-search-page.component';
import { LinkMenuItemComponent } from './menu/menu-item/link-menu-item.component';
import { OnClickMenuItemComponent } from './menu/menu-item/onclick-menu-item.component';
import { TextMenuItemComponent } from './menu/menu-item/text-menu-item.component';
import { ThemedConfigurationSearchPageComponent } from '../search-page/themed-configuration-search-page.component';
import { SearchNavbarComponent } from '../search-navbar/search-navbar.component';
import { ItemVersionsSummaryModalComponent } from './item/item-versions/item-versions-summary-modal/item-versions-summary-modal.component';
import { ItemVersionsDeleteModalComponent } from './item/item-versions/item-versions-delete-modal/item-versions-delete-modal.component';
import { ScopeSelectorModalComponent } from './search-form/scope-selector-modal/scope-selector-modal.component';
import { BitstreamRequestACopyPageComponent } from './bitstream-request-a-copy-page/bitstream-request-a-copy-page.component';
/**
* Declaration needed to make sure all decorator functions are called in time
*/
export const MODELS = [
SearchObjects,
FacetConfigResponse,
FacetValues,
SearchResult
];
const MODULES = [
// Do NOT include UniversalModule, HttpModule, or JsonpModule here
CommonModule,
SortablejsModule,
DynamicFormsCoreModule,
DynamicFormsNGBootstrapUIModule,
FileUploadModule,
FormsModule,
InfiniteScrollModule,
NgbModule,
NgbDatepickerModule,
NgbTimepickerModule,
NgbTypeaheadModule,
NgxPaginationModule,
ReactiveFormsModule,
RouterModule,
NouisliderModule,
MomentModule,
TextMaskModule,
DragDropModule,
CdkTreeModule
];
const ROOT_MODULES = [
TranslateModule.forChild({
missingTranslationHandler: { provide: MissingTranslationHandler, useClass: MissingTranslationHelper },
useDefaultLang: true
})
];
const PIPES = [
// put shared pipes here
EnumKeysPipe,
FileSizePipe,
SafeUrlPipe,
TruncatePipe,
EmphasizePipe,
CapitalizePipe,
ObjectKeysPipe,
ObjectValuesPipe,
ConsolePipe,
ObjNgFor
];
const COMPONENTS = [
// put shared components here
AlertComponent,
AuthNavMenuComponent,
UserMenuComponent,
ChipsComponent,
ComcolPageContentComponent,
ComcolPageHandleComponent,
ComcolPageHeaderComponent,
ComcolPageLogoComponent,
ComColFormComponent,
CreateComColPageComponent,
EditComColPageComponent,
DeleteComColPageComponent,
ComcolPageBrowseByComponent,
ComcolRoleComponent,
DsDynamicFormComponent,
DsDynamicFormControlContainerComponent,
DsDynamicListComponent,
DsDynamicLookupComponent,
DsDynamicDisabledComponent,
DsDynamicLookupRelationModalComponent,
DsDynamicScrollableDropdownComponent,
DsDynamicTagComponent,
DsDynamicOneboxComponent,
DsDynamicRelationGroupComponent,
DsDatePickerComponent,
DsDynamicFormGroupComponent,
DsDynamicFormArrayComponent,
DsDatePickerInlineComponent,
DsSelectComponent,
ErrorComponent,
FileSectionComponent,
FormComponent,
LangSwitchComponent,
LoadingComponent,
LogInComponent,
LogOutComponent,
NumberPickerComponent,
ObjectListComponent,
ObjectDetailComponent,
ObjectGridComponent,
AbstractListableElementComponent,
ObjectCollectionComponent,
PaginationComponent,
SearchFormComponent,
PageWithSidebarComponent,
SidebarDropdownComponent,
SidebarFilterComponent,
SidebarFilterSelectedOptionComponent,
ThumbnailComponent,
UploaderComponent,
FileDropzoneNoUploaderComponent,
ItemListPreviewComponent,
MyDSpaceItemStatusComponent,
ItemSubmitterComponent,
ItemDetailPreviewComponent,
ItemDetailPreviewFieldComponent,
ClaimedTaskActionsComponent,
ClaimedTaskActionsApproveComponent,
ClaimedTaskActionsRejectComponent,
ClaimedTaskActionsReturnToPoolComponent,
ClaimedTaskActionsEditMetadataComponent,
ClaimedTaskActionsLoaderComponent,
ItemActionsComponent,
PoolTaskActionsComponent,
WorkflowitemActionsComponent,
WorkspaceitemActionsComponent,
ViewModeSwitchComponent,
TruncatableComponent,
TruncatablePartComponent,
BrowseByComponent,
InputSuggestionsComponent,
FilterInputSuggestionsComponent,
ValidationSuggestionsComponent,
DsoInputSuggestionsComponent,
DSOSelectorComponent,
CreateCommunityParentSelectorComponent,
CreateCollectionParentSelectorComponent,
CreateItemParentSelectorComponent,
EditCommunitySelectorComponent,
EditCollectionSelectorComponent,
EditItemSelectorComponent,
CommunitySearchResultListElementComponent,
CollectionSearchResultListElementComponent,
BrowseByComponent,
SearchResultsComponent,
SearchSidebarComponent,
SearchSettingsComponent,
CollectionSearchResultGridElementComponent,
CommunitySearchResultGridElementComponent,
SearchFiltersComponent,
SearchFilterComponent,
SearchFacetFilterComponent,
SearchLabelsComponent,
SearchLabelComponent,
SearchFacetFilterWrapperComponent,
SearchRangeFilterComponent,
SearchTextFilterComponent,
SearchHierarchyFilterComponent,
SearchBooleanFilterComponent,
SearchFacetOptionComponent,
SearchFacetSelectedOptionComponent,
SearchFacetRangeOptionComponent,
SearchSwitchConfigurationComponent,
SearchAuthorityFilterComponent,
PageSizeSelectorComponent,
ListableObjectComponentLoaderComponent,
CollectionListElementComponent,
CommunityListElementComponent,
CollectionGridElementComponent,
CommunityGridElementComponent,
BrowseByComponent,
AbstractTrackableComponent,
ComcolMetadataComponent,
TypeBadgeComponent,
BrowseByComponent,
AbstractTrackableComponent,
CustomSwitchComponent,
ItemSelectComponent,
CollectionSelectComponent,
MetadataRepresentationLoaderComponent,
SelectableListItemControlComponent,
ExternalSourceEntryImportModalComponent,
ImportableListItemControlComponent,
ExistingMetadataListElementComponent,
ExistingRelationListElementComponent,
LogInShibbolethComponent,
LogInPasswordComponent,
LogInContainerComponent,
ItemVersionsComponent,
ItemSearchResultListElementComponent,
ItemVersionsNoticeComponent,
ModifyItemOverviewComponent,
ImpersonateNavbarComponent,
ResourcePoliciesComponent,
ResourcePolicyFormComponent,
ResourcePolicyEditComponent,
ResourcePolicyCreateComponent,
EpersonGroupListComponent,
EpersonSearchBoxComponent,
GroupSearchBoxComponent,
FileDownloadLinkComponent,
BitstreamDownloadPageComponent,
BitstreamRequestACopyPageComponent,
CollectionDropdownComponent,
EntityDropdownComponent,
ExportMetadataSelectorComponent,
ConfirmationModalComponent,
VocabularyTreeviewComponent,
AuthorizedCollectionSelectorComponent,
CurationFormComponent,
SearchResultListElementComponent,
SearchResultGridElementComponent,
ItemListElementComponent,
ItemGridElementComponent,
ItemSearchResultGridElementComponent,
BrowseEntryListElementComponent,
SearchResultDetailElementComponent,
PlainTextMetadataListElementComponent,
ItemMetadataListElementComponent,
MetadataRepresentationListElementComponent,
DsDynamicLookupRelationSearchTabComponent,
DsDynamicLookupRelationSelectionTabComponent,
ItemMetadataRepresentationListElementComponent,
DsDynamicLookupRelationExternalSourceTabComponent,
BundleListElementComponent,
StartsWithDateComponent,
StartsWithTextComponent,
SidebarSearchListElementComponent,
PublicationSidebarSearchListElementComponent,
CollectionSidebarSearchListElementComponent,
CommunitySidebarSearchListElementComponent,
SearchNavbarComponent,
ScopeSelectorModalComponent,
];
const ENTRY_COMPONENTS = [
// put only entry components that use custom decorator
CollectionListElementComponent,
CommunityListElementComponent,
SearchResultListElementComponent,
CommunitySearchResultListElementComponent,
CollectionSearchResultListElementComponent,
CollectionGridElementComponent,
CommunityGridElementComponent,
CommunitySearchResultGridElementComponent,
CollectionSearchResultGridElementComponent,
SearchResultGridElementComponent,
ItemListElementComponent,
ItemGridElementComponent,
ItemSearchResultListElementComponent,
ItemSearchResultGridElementComponent,
BrowseEntryListElementComponent,
SearchResultDetailElementComponent,
StartsWithDateComponent,
StartsWithTextComponent,
CreateCommunityParentSelectorComponent,
CreateCollectionParentSelectorComponent,
CreateItemParentSelectorComponent,
EditCommunitySelectorComponent,
EditCollectionSelectorComponent,
EditItemSelectorComponent,
PlainTextMetadataListElementComponent,
ItemMetadataListElementComponent,
MetadataRepresentationListElementComponent,
CustomSwitchComponent,
ItemMetadataRepresentationListElementComponent,
SearchResultsComponent,
SearchFacetFilterComponent,
SearchRangeFilterComponent,
SearchTextFilterComponent,
SearchHierarchyFilterComponent,
SearchBooleanFilterComponent,
SearchFacetOptionComponent,
SearchFacetSelectedOptionComponent,
SearchFacetRangeOptionComponent,
SearchAuthorityFilterComponent,
LogInPasswordComponent,
LogInShibbolethComponent,
BundleListElementComponent,
ClaimedTaskActionsApproveComponent,
ClaimedTaskActionsRejectComponent,
ClaimedTaskActionsReturnToPoolComponent,
ClaimedTaskActionsEditMetadataComponent,
CollectionDropdownComponent,
FileDownloadLinkComponent,
BitstreamDownloadPageComponent,
BitstreamRequestACopyPageComponent,
CurationFormComponent,
ExportMetadataSelectorComponent,
ConfirmationModalComponent,
VocabularyTreeviewComponent,
SidebarSearchListElementComponent,
PublicationSidebarSearchListElementComponent,
CollectionSidebarSearchListElementComponent,
CommunitySidebarSearchListElementComponent,
LinkMenuItemComponent,
OnClickMenuItemComponent,
TextMenuItemComponent,
ScopeSelectorModalComponent,
];
const SHARED_SEARCH_PAGE_COMPONENTS = [
ConfigurationSearchPageComponent,
ThemedConfigurationSearchPageComponent
];
const SHARED_ITEM_PAGE_COMPONENTS = [
MetadataFieldWrapperComponent,
MetadataValuesComponent,
DsoPageEditButtonComponent,
DsoPageVersionButtonComponent,
ItemAlertsComponent,
GenericItemPageFieldComponent,
MetadataRepresentationListComponent,
RelatedItemsComponent,
RelatedEntitiesSearchComponent,
TabbedRelatedEntitiesSearchComponent
];
const PROVIDERS = [
TruncatableService,
MockAdminGuard,
AbstractTrackableComponent,
{
provide: DYNAMIC_FORM_CONTROL_MAP_FN,
useValue: dsDynamicFormControlMapFn
},
ResourcePolicyResolver,
ResourcePolicyTargetResolver
];
const DIRECTIVES = [
VarDirective,
DragClickDirective,
DebounceDirective,
ClickOutsideDirective,
AuthorityConfidenceStateDirective,
InListValidator,
AutoFocusDirective,
RoleDirective,
MetadataRepresentationDirective,
ListableObjectDirective,
ClaimedTaskActionsDirective,
FileValueAccessorDirective,
FileValidator,
ClaimedTaskActionsDirective,
NgForTrackByIdDirective,
MetadataFieldValidator,
HoverClassDirective
];
@NgModule({
imports: [
...MODULES,
...ROOT_MODULES
],
declarations: [
...PIPES,
...COMPONENTS,
...DIRECTIVES,
...SHARED_ITEM_PAGE_COMPONENTS,
...SHARED_SEARCH_PAGE_COMPONENTS,
ItemVersionsSummaryModalComponent,
ItemVersionsDeleteModalComponent,
],
providers: [
...PROVIDERS
],
exports: [
...MODULES,
...PIPES,
...COMPONENTS,
...SHARED_ITEM_PAGE_COMPONENTS,
...SHARED_SEARCH_PAGE_COMPONENTS,
...DIRECTIVES,
TranslateModule
]
})
/**
* This module handles all components and pipes that need to be shared among multiple other modules
*/
export class SharedModule {
/**
* NOTE: this method allows to resolve issue with components that using a custom decorator
* which are not loaded during SSR otherwise
*/
static withEntryComponents() {
return {
ngModule: SharedModule,
providers: ENTRY_COMPONENTS.map((component) => ({provide: component}))
};
}
} | the_stack |
import {
ParsedVisitor,
TreeVisitor,
ParseReferenceType,
ParseDefinition,
ParseResult,
ParseClassDeclaration,
ParseInterfaceDeclaration,
ParseMethod,
ParseEmpty,
ParseTypeAliasDeclaration,
ParseTypeParameter,
ParseGeneric,
ParseLocation,
ParseExpression,
} from '../parsed-nodes';
import { flatten, cloneDeep, clone } from 'lodash';
import { Logger } from '@sketchmine/node-helpers';
import { getReferencedDeclarations } from '../utils';
const log = new Logger();
/**
* @description
* Lookup Table for the Generics that are found in the tree
* The outer map is a map where the key represents the filename
* the value of this map is another map where the key represents the position
* in the file where the generic ocurred and holds as value the generic symbol
*/
export const LOOKUP_TABLE = new Map<string, Map<number, ParseGeneric>>();
/**
* @description
* All parsed class types that can have typeParameters
*/
type typeParametersNode =
| ParseClassDeclaration
| ParseInterfaceDeclaration
| ParseMethod
| ParseTypeAliasDeclaration;
class RestoreGenericsReferenceResolver extends TreeVisitor implements ParsedVisitor {
private internalLookupTable = new Map<string, Map<number, ParseGeneric>>();
visitGeneric(node: ParseGeneric) {
const fileMap = this.internalLookupTable.get(node.location.path);
if (!fileMap) {
const position = new Map<number, ParseGeneric>();
position.set(node.location.position, node);
this.internalLookupTable.set(node.location.path, position);
} else if (!fileMap.has(node.location.position)) {
fileMap.set(node.location.position, node);
} else {
return fileMap.get(node.location.position);
}
return node;
}
resetTable(): void {
this.internalLookupTable.clear();
}
}
/**
* @class
* @classdesc
* The reference resolver is used to get the values of interfaces, type alias declarations
* generics or methods and replace them with their place holding parse reference class.
* The first lookup is always in a lookup table that stores all generics. These generics are
* collected during the visiting process. If a reference type matches with a generic from the table
* the reference (pointer to the object) is placed instead.
*/
export class ReferenceResolver extends TreeVisitor implements ParsedVisitor {
/**
* @description
* The path of the file that is currently visited, gathered by the ParseResults
* location path. Is used to determine the matching rootNode in the module resolution.
*/
private currentFilePath: string;
private genericsRestoreResolver = new RestoreGenericsReferenceResolver();
constructor(public parsedResults: Map<string, ParseResult>) { super(); }
/**
* @description
* Overrides the visitResult from the tree visitor to gather the current file name.
*/
visitResult(node: ParseResult): any {
// clear lookup table on each file
LOOKUP_TABLE.clear();
this.currentFilePath = node.location.path;
return super.visitResult(node);
}
visit(node: any): any {
// Node that was visited from the ReferenceResolver has the visited
// property – so that we know if we have to visit it or not when we collectGenerics
// a node from the root nodes
if (node) { node._visited = true; }
return super.visit(node);
}
visitTypeAliasDeclaration(node: ParseTypeAliasDeclaration): any {
this.collectGenerics(node);
return super.visitTypeAliasDeclaration(node);
}
visitMethod(node: ParseMethod): any {
this.collectGenerics(node);
return super.visitMethod(node);
}
visitClassDeclaration(node: ParseClassDeclaration): any {
this.collectGenerics(node);
return super.visitClassDeclaration(node);
}
visitInterfaceDeclaration(node: ParseInterfaceDeclaration): any {
this.collectGenerics(node);
return super.visitInterfaceDeclaration(node);
}
/**
* @description
* Overwrites the visitExpression method from the tree visitor. Try to find the matching
* function declaration and pass the arguments in so that we get the returning value that can
* be assigned to a variable declaration.
*/
visitExpression(node: ParseExpression): any {
const method = this.getRootNodeByName(node) as ParseMethod;
if (!method) {
return new ParseEmpty();
}
// We need to check if we have typeArguments, and when we have some, we have
// to pass it through the typeParameters of the matching `typeParametersNode`
const cloned = this.passTypeArguments(node, method);
if (!cloned) {
return new ParseEmpty();
}
// we have to visit the arguments so that we can pass the values to the
// matching function declaration instead only passing some reference.
node.args = this.visitAll(node.args);
for (let i = 0, max = node.args.length; i < max; i += 1) {
const arg = node.args[i];
if (!cloned.parameters[i]) {
// tslint:disable-next-line: max-line-length
log.error(`When resolving the expression ${node.name} – a problem occurred, the found parameters did not match the provided ones!`);
}
const param = cloned.parameters[i].type;
if (param && param.constructor.name === 'ParseGeneric') {
(param as ParseGeneric).value = arg;
} else {
cloned.parameters[i] = arg as any;
}
}
return cloned;
}
/**
* @description
* Overwrites the visitReferenceType method from the tree visitor to resolve the ParseReferenceType.
* It should result into a value from a generic, interface, class, type etc...
* If it is not resolvable, in case that it comes from any node dependency that we don't want to parse
* we result in returning the ParseEmpty class.
*/
visitReferenceType(node: ParseReferenceType) {
// Check if the reference is a generic and is stored in the lookup Table
const generic = this.getGenericFromLookupTable(node);
// if we have a generic replace it with the reference type
if (generic) {
return generic;
}
// If the reference is not in the lookup Table search it in the root nodes
// So now we know it is not a generic and we can search in the types and interfaces
// if there is a matching Symbol name
const resolvedNode = this.getRootNodeByName(node) as typeParametersNode;
// if there is no resolved node we have to return ParseEmpty so we know it cannot be resolved
if (!resolvedNode) {
return new ParseEmpty();
}
// We need to check if we have typeArguments, and when we have some, we have
// to pass it through the typeParameters of the matching `typeParametersNode`
return this.passTypeArguments(node, resolvedNode);
}
/**
* @description
* Passes the typeArguments to the found resolvedNode and returns
* the resulting node with the typeArguments from the reference node or expression
*/
private passTypeArguments<T extends typeParametersNode>(
node: ParseReferenceType | ParseExpression,
resolvedNode: T,
): T {
// if we have typeArguments it is a generic and we have to clone the resolvedNode
// because maybe it is used by other declarations as well.
// So we won't modify the original reference.
let cloned = cloneDeep(resolvedNode) as T;
// we have to clear the lookup table in case that we need a fresh value when we want to resolve the
// generic and not a pre filled table with values in there.
this.genericsRestoreResolver.resetTable();
cloned = cloned.visit(this.genericsRestoreResolver);
// If we have typeArguments they have to be replaced with the arguments from the generic
// after we replaced the generic type we can resolve the reference and replace the values
if (node.typeArguments && node.typeArguments.length) {
for (let i = 0, max = node.typeArguments.length; i < max; i += 1) {
let typeArgument = node.typeArguments[i];
// if the typeArgument is a reference type we have to resolve it
// before we pass it into the generic.
// to limit ourselves not only to reference types we can call the generic
// visit function of the typeArgument so it does not matter which class it is!
typeArgument = this.visit(typeArgument);
if (cloned.typeParameters && cloned.typeParameters[i]) {
(cloned.typeParameters[i] as ParseGeneric).type = typeArgument as ParseDefinition;
}
}
}
return cloned;
}
/**
* @description
* This function is used to find the matching function overload for a call expressions
* @param node the node that is calling the method
* @param overloads the available overloads
*/
private findMatchingFunctionOverload(node: ParseExpression, overloads: ParseMethod[]) {
if (!overloads || !overloads.length) {
return;
}
let foundOverload: ParseMethod = overloads[0];
for (let i = 0, max = overloads.length; i < max; i += 1) {
const method = overloads[i];
// filter the required parameters out of the function parameters
const requiredParameters = method.parameters.filter(param => !param.isOptional);
// to find the matching overload the amount of typeParameters has to match the typeArguments
// length that is provided from the node, then the amount of the provided arguments has to be
// greater or equal than the amount of the required parameters but less or equal the maximum amount of parameters
if (
node.typeArguments.length === method.typeParameters.length &&
node.args.length >= requiredParameters.length &&
node.args.length <= method.parameters.length
) {
foundOverload = method;
}
}
return foundOverload;
}
/**
* @description
* Find the matching expression or declaration for a reference type or
* expression call. In case there would be a function overload we have to check the
* type parameter length and the argument length to match the correct overload.
* @param referencedNode The reference that should be resolved either a reference type or an expression
*/
private getRootNodeByName(referencedNode: ParseExpression | ParseReferenceType): ParseDefinition | undefined {
// TODO: major: lukas.holzer build check if rootNode is not parent node,
// otherwise we would get a circular structure that is causing a memory leak!
const rootNodes = getReferencedDeclarations(referencedNode, this.parsedResults, this.currentFilePath);
// if we could not find any root node for the referenceNode we cannot resolve
// this type or expression
if (rootNodes.length < 1) {
return;
}
let rootNode = rootNodes[0];
// if we have more than one matching rootNode we have to check if it is an expression
// and then we have to choose the matching overload
if (rootNodes.length > 1 && referencedNode.constructor === ParseExpression) {
// filter out the methods to be sure we have an overload
const methods = rootNodes.filter(n => n.constructor === ParseMethod) as ParseMethod[];
rootNode = this.findMatchingFunctionOverload(referencedNode as ParseExpression, methods);
}
if (rootNode && (!rootNode.hasOwnProperty('_visited') || (<any>rootNode)._visited !== true)) {
// if the node was not visited yet we have to visit the root node first
// before we are returning it!
return this.visit(rootNode);
}
// rootNode was visited and we can pass it!
return rootNode;
}
/**
* @description
* Checks the typeParameters of a parsed node and
* adds the generics to the lookup table.
*/
private collectGenerics(node: typeParametersNode): void {
for (let i = 0, max = node.typeParameters.length; i < max; i += 1) {
const generic: ParseTypeParameter = node.typeParameters[i];
let constraint;
if (generic.constraint) {
constraint = this.visit(generic.constraint);
}
const location = generic.location;
const gen = new ParseGeneric(location, generic.name, constraint);
this.addGenericToLookupTable(generic.location, gen);
node.typeParameters[i] = gen;
}
}
/**
* @description
* Adds a generic to the lookup table according to its file and the position.
* The position is always unique in a file – *(the character position)*
*/
private addGenericToLookupTable(location: ParseLocation, value: ParseGeneric): void {
const file = LOOKUP_TABLE.get(location.path);
// file key already exists so we need to append it.
// to the existing position Map.
if (file) {
file.set(location.position, value);
return;
}
// if there is no entry for this file create a file entry in the map
// and add a new position map.
const positionMap = new Map<number, ParseGeneric>();
positionMap.set(location.position, value);
LOOKUP_TABLE.set(location.path, positionMap);
}
/**
* @description
* Finds the parent generic in the lookup table according to the provided position of the
* node. The parent generic is always the generic with the same name that has the closest position
* number related to the nodes position. If undefined is returned it is not a generic and we can assume
* that it is a type reference (interface, class or type).
*/
protected getGenericFromLookupTable(node: ParseReferenceType): ParseGeneric | undefined {
const location = node.location;
const value = node.name;
const positionMap = LOOKUP_TABLE.get(location.path);
// if the file is not in the position map return undefined
if (!positionMap) {
return;
}
// find the position of the parent generic
const genericPosition = Array.from(positionMap.keys())
// sort table descending to find the first smaller number
.sort((a: number, b: number) => b - a)
// find the next smaller position to identify the parent generic
.find((pos: number) =>
pos < location.position &&
positionMap.get(pos).name === value);
return positionMap.get(genericPosition) || undefined;
}
} | the_stack |
import * as accepts from "accepts";
import * as assert from "assert";
import { IncomingMessage, ServerResponse } from "http";
import { v4 as createUUID } from "node-uuid";
import * as querystring from "querystring";
import * as url from "url";
import {
as2ObjectIsActivity,
publicCollectionId,
targetAndDeliver,
} from "./activitypub";
import { internalUrlRewriter } from "./distbin-html/url-rewriter";
import { createLogger } from "./logger";
import {
Activity,
ActivityMap,
ASObject,
Extendable,
JSONLD,
LDValue,
} from "./types";
import {
debuglog,
ensureArray,
first,
flatten,
jsonld,
jsonldAppend,
readableToString,
requestMaxMemberCount,
route,
RoutePattern,
RouteResponderFactory,
} from "./util";
const logger = createLogger("index");
const owlSameAs = "http://www.w3.org/2002/07/owl#sameAs";
// given a non-uri activity id, return an activity URI
const uuidUri = (uuid: string) => `urn:uuid:${uuid}`;
// Factory function for another node.http handler function that defines distbin's web logic
// (routes requests to sub-handlers with common error handling)
export default function distbin({
// Juse use Map as default, but users should provide more bette data structures
// #TODO: This should be size-bound e.g. LRU
// #TODO: This should be persistent :P
activities = new Map(),
inbox = new Map(),
inboxFilter = async () => true,
// used for delivering to other inboxes so they can find this guy
externalUrl,
internalUrl,
deliverToLocalhost = false,
}: {
activities?: Map<string, object>;
inbox?: Map<string, object>;
inboxFilter?: (obj: ASObject) => Promise<boolean>;
externalUrl?: string;
internalUrl?: string;
deliverToLocalhost?: boolean;
} = {}) {
return (req: IncomingMessage, res: ServerResponse) => {
externalUrl = externalUrl || `http://${req.headers.host}`;
let handler = route(
new Map<RoutePattern, RouteResponderFactory>([
["/", () => index],
["/recent", () => recentHandler({ activities })],
[
"/activitypub/inbox",
() => inboxHandler({ activities, inbox, inboxFilter, externalUrl }),
],
[
"/activitypub/outbox",
() =>
outboxHandler({
activities,
deliverToLocalhost,
externalUrl,
internalUrl,
}),
],
[
"/activitypub/public/page",
() => publicCollectionPageHandler({ activities, externalUrl }),
],
[
"/activitypub/public",
() => publicCollectionHandler({ activities, externalUrl }),
],
// /activities/{activityUuid}.{format}
[
/^\/activities\/([^/]+?)(\.(.+))$/,
(activityUuid: string, _: string, format: string) =>
activityWithExtensionHandler({
activities,
activityUuid,
externalUrl,
format,
}),
],
// /activities/{activityUuid}
[
/^\/activities\/([^/]+)$/,
(activityUuid: string) =>
activityHandler({ activities, activityUuid, externalUrl }),
],
[
/^\/activities\/([^/]+)\/replies$/,
(activityUuid: string) =>
activityRepliesHandler({ activities, activityUuid, externalUrl }),
],
]),
req,
);
if (!handler) {
handler = errorHandler(404);
}
try {
return Promise.resolve(handler(req, res)).catch(err => {
return errorHandler(500, err)(req, res);
});
} catch (err) {
return errorHandler(500, err)(req, res);
}
};
}
function isHostedLocally(activityFreshFromStorage: Activity) {
return !activityFreshFromStorage.hasOwnProperty("url");
}
type UrnUuid = string;
type ExternalUrl = string;
function externalizeActivityId(
activityId: UrnUuid,
externalUrl: ExternalUrl,
): ExternalUrl {
const uuidMatch = activityId.match(/^urn:uuid:([^$]+)$/);
if (!uuidMatch) {
throw new Error(
`Couldn't determine UUID for activity with id: ${activityId}`,
);
}
const uuid = uuidMatch[1];
const activityUrl = url.resolve(externalUrl, "./activities/" + uuid);
return activityUrl;
}
// return a an extended version of provided activity with some extra metadata properties like 'inbox', 'url', 'replies'
// if 'baseUrl' opt is provided, those extra properties will be absolute URLs, not relative
const locallyHostedActivity = (
activity: Extendable<Activity>,
{ externalUrl }: { externalUrl: string },
) => {
if (activity.url) {
debuglog(
"Unexpected .url property when processing activity assumed to be locally" +
"hosted\n" +
JSON.stringify(activity),
);
throw new Error(
"Unexpected .url property when processing activity assumed to be locally hosted",
);
}
const uuidMatch = activity.id.match(/^urn:uuid:([^$]+)$/);
if (!uuidMatch) {
throw new Error(
`Couldn't determine UUID for activity with id: ${activity.id}`,
);
}
const uuid = uuidMatch[1];
// Each activity should have an ActivityPub/LDN inbox where it can receive notifications.
// TODO should this be an inbox specific to this activity?
const inboxUrl = url.resolve(externalUrl, "./activitypub/inbox");
const activityUrl = url.resolve(externalUrl, "./activities/" + uuid);
const repliesUrl = url.resolve(
externalUrl,
"./activities/" + uuid + "/replies",
);
return Object.assign({}, activity, {
[owlSameAs]: jsonldAppend(activity[owlSameAs], activity.id),
id: externalizeActivityId(activity.id, externalUrl),
inbox: jsonldAppend(activity.inbox, inboxUrl),
replies: repliesUrl,
url: jsonldAppend(activity.url, activityUrl),
uuid,
});
};
// get specific activity by id
function activityHandler({
activities,
activityUuid,
externalUrl,
}: {
activities: ActivityMap;
activityUuid: string;
externalUrl: ExternalUrl;
}) {
return async (req: IncomingMessage, res: ServerResponse) => {
const uri = uuidUri(activityUuid);
const activity = await Promise.resolve(activities.get(uri));
// #TODO: If the activity isn't addressed to the public, we should enforce access controls here.
if (!activity) {
res.writeHead(404);
res.end("There is no activity " + uri);
return;
}
// redirect to remote ones if we know a URL
if (!isHostedLocally(activity)) {
if (activity.url) {
// see other
res.writeHead(302, {
location: (ensureArray(activity.url).filter(
(u: any): u is string => typeof u === "string",
) as string[])[0],
});
res.end(activity.url);
return;
} else {
res.writeHead(404);
res.end(
`Activity ${activityUuid} has been seen before, but it's not canonically` +
`hosted here, and I can't seem to find it's canonical URL. Sorry.`,
);
return;
}
}
// return the activity
const extendedActivity = locallyHostedActivity(activity, { externalUrl });
// woo its here
res.writeHead(200, {
"content-type": "application/json",
});
res.end(JSON.stringify(extendedActivity, null, 2));
};
}
function activityWithExtensionHandler({
activities,
activityUuid,
format,
externalUrl,
}: {
activities: ActivityMap;
activityUuid: string;
format: string;
externalUrl: ExternalUrl;
}) {
return async (req: IncomingMessage, res: ServerResponse) => {
if (format !== "json") {
res.writeHead(404);
res.end("Unsupported activity extension ." + format);
return;
}
return activityHandler({ activities, activityUuid, externalUrl })(req, res);
};
}
function activityRepliesHandler({
activities,
activityUuid,
externalUrl,
}: {
activities: ActivityMap;
activityUuid: string;
externalUrl: ExternalUrl;
}) {
return async (req: IncomingMessage, res: ServerResponse) => {
const uri = uuidUri(activityUuid);
const parentActivity = await Promise.resolve(activities.get(uri));
// #TODO: If the parentActivity isn't addressed to the public, we should enforce access controls here.
if (!parentActivity) {
res.writeHead(404);
res.end("There is no activity " + uri);
return;
}
const replies = Array.from(await Promise.resolve(activities.entries()))
.filter(([key, activity]) => {
if (!activity) {
logger.warn("activities map has a falsy value for key", key);
return false;
}
type ParentId = string;
const filteredReplies: ASObject[] = ensureArray<any>(
activity.object,
).filter(o => typeof o === "object");
const inReplyTos = flatten(
filteredReplies.map((object: ASObject) =>
ensureArray<any>(object.inReplyTo).map(
(o: any): ParentId => {
if (typeof o === "string") {
return o;
}
if (o instanceof ASObject) {
return o.id;
}
},
),
),
).filter(Boolean);
return inReplyTos.some((inReplyTo: ParentId) => {
// TODO .inReplyTo could be a urn, http URL, something else?
const pathNameReplyCandidate = url.parse(inReplyTo).pathname;
const pathNameOfReply = url.parse(
url.resolve(externalUrl, `./activities/${activityUuid}`),
).pathname;
const isReply = pathNameReplyCandidate === pathNameOfReply;
return isReply;
});
})
.map(([id, replyActivity]) => {
if (isHostedLocally(replyActivity)) {
return locallyHostedActivity(replyActivity, { externalUrl });
}
return replyActivity;
});
res.writeHead(200, {
"content-type": "application/json",
});
res.end(
JSON.stringify(
{
// TODO: sort/paginate/limit this
items: replies,
name: "replies to item with UUID " + activityUuid,
totalItems: replies.length,
type: "Collection",
},
null,
2,
),
);
};
}
// root route, do nothing for now but 200
function index(req: IncomingMessage, res: ServerResponse) {
res.writeHead(200, {
"content-type": "application/json",
});
res.end(
JSON.stringify(
{
"@context": [
"https://www.w3.org/ns/activitystreams",
{
activitypub: "https://www.w3.org/ns/activitypub#",
inbox: "activitypub:inbox",
outbox: "activitypub:outbox",
},
],
inbox: "/activitypub/inbox",
name: "distbin",
outbox: "/activitypub/outbox",
recent: "/recent",
summary:
"A public service to store and retrieve posts and enable " +
"(federated, standards-compliant) social interaction around them",
type: "Service",
},
null,
2,
),
);
}
// fetch a collection of recent Activities/things
function recentHandler({ activities }: { activities: ActivityMap }) {
return async (req: IncomingMessage, res: ServerResponse) => {
const maxMemberCount = requestMaxMemberCount(req) || 10;
res.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"content-type": "application/json",
});
res.end(
JSON.stringify(
{
"@context": "https://www.w3.org/ns/activitystreams",
// empty string is relative URL for 'self'
current: "",
// Get recent 10 items
items: [...(await Promise.resolve(activities.values()))]
.reverse()
.slice(-1 * maxMemberCount),
summary: "Things that have recently been created",
totalItems: await activities.size,
type: "OrderedCollection",
},
null,
2,
),
);
};
}
// route for ActivityPub Inbox
// https://w3c.github.io/activitypub/#inbox
function inboxHandler({
activities,
externalUrl,
inbox,
inboxFilter,
}: {
activities: ActivityMap;
externalUrl: string;
inbox: ActivityMap;
inboxFilter?: (obj: ASObject) => Promise<boolean>;
}) {
return async (req: IncomingMessage, res: ServerResponse) => {
switch (req.method.toLowerCase()) {
case "options":
res.writeHead(200, {
"Accept-Post": [
"application/activity+json",
"application/json",
"application/ld+json",
'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
].join(", "),
});
res.end();
return;
case "get":
const idQuery = first(url.parse(req.url, true).query.id);
let responseBody;
if (idQuery) {
// trying to just get one notification
const itemWithId = await inbox.get(idQuery);
if (!itemWithId) {
res.writeHead(404);
res.end();
return;
}
responseBody = itemWithId;
} else {
// getting a bunch of notifications
const maxMemberCount = requestMaxMemberCount(req) || 10;
const items = [...(await Promise.resolve(inbox.values()))]
.slice(-1 * maxMemberCount)
.reverse();
const inboxCollection = {
"@context": "https://www.w3.org/ns/activitystreams",
"@id": "/activitypub/inbox",
// empty string is relative URL for 'self'
current: "",
items,
"ldp:contains": items.map(i => ({ id: i.id })).filter(Boolean),
totalItems: await inbox.size,
type: ["OrderedCollection", "ldp:Container"],
};
responseBody = inboxCollection;
}
const accept = accepts(req);
const serverPreferences = [
'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
"json",
"application/ld+json",
"application/activity+json",
];
const contentType =
accept.type(serverPreferences) || serverPreferences[0];
res.writeHead(200, {
"content-type": contentType,
});
res.end(JSON.stringify(responseBody, null, 2));
break;
case "post":
debuglog("receiving inbox POST");
const requestBody = await readableToString(req);
debuglog(requestBody);
let parsed;
try {
parsed = JSON.parse(requestBody);
} catch (e) {
res.writeHead(400);
res.end("Couldn't parse request body as JSON: " + requestBody);
return;
}
const inboxFilterResult = await inboxFilter(parsed);
if (!inboxFilterResult) {
res.writeHead(400);
res.end(
"This activity has been blocked by the configured inboxFilter",
);
return;
}
const existsAlreadyInInbox = parsed.id
? await Promise.resolve(inbox.get(parsed.id))
: false;
if (existsAlreadyInInbox) {
// duplicate!
res.writeHead(409);
res.end(
"There is already an activity in the inbox with id " + parsed.id,
);
return;
}
const notificationToSave = Object.assign({}, parsed);
const compacted = await jsonld.compact(notificationToSave, {});
let originalId = compacted["@id"];
// Move incomding @id to wasDerivedFrom, then provision a new @id
if (originalId) {
notificationToSave["http://www.w3.org/ns/prov#wasDerivedFrom"] = {
id: originalId,
};
} else {
// can't understand parsed's id
delete parsed["@id"];
delete parsed.id;
parsed.id = originalId = uuidUri(createUUID());
}
delete notificationToSave["@id"];
const notificationUrnUuid = uuidUri(createUUID());
const notificationUrl = `/activitypub/inbox?id=${encodeURIComponent(
notificationUrnUuid,
)}`;
notificationToSave.id = notificationUrl;
notificationToSave[owlSameAs] = { id: notificationUrnUuid };
// If receiving a notification about an activity we've seen before (e.g. it is canonically hosted here),
// this will be true
const originalIdsIncludingSameAs = [
originalId,
...ensureArray(compacted[owlSameAs]),
];
const originalIdsHave = await Promise.all(
originalIdsIncludingSameAs.map(aid => activities.has(aid)),
);
const originalAlreadySaved = originalIdsHave.some(Boolean);
if (originalAlreadySaved) {
// #TODO merge or something? Consider storing local ones and remote ones in different places
debuglog(
"Inbox received activity already stored in activities store." +
"Not overwriting internal one. But #TODO",
);
}
assert(originalId);
await Promise.all([
inbox.set(notificationUrnUuid, notificationToSave),
// todo: Probably setting on inbox should automagically add to global set of activities
originalAlreadySaved ? null : activities.set(originalId, parsed),
]);
res.writeHead(201, {
location: notificationUrl,
});
res.end();
break;
default:
return errorHandler(405, new Error("Method not allowed: "))(req, res);
}
};
}
// given a AS2 object, return it's JSON-LD @id
const getJsonLdId = (obj: string | ASObject | JSONLD) => {
if (typeof obj === "string") {
return obj;
} else if (obj instanceof JSONLD) {
return obj["@id"];
} else if (obj instanceof ASObject) {
return obj.id;
} else {
const exhaustiveCheck: never = obj;
}
};
// return whether a given activity targets another resource (e.g. in to, cc, bcc)
const activityHasTarget = (activity: Activity, target: LDValue<ASObject>) => {
const targetId = getJsonLdId(target);
if (!targetId) {
throw new Error("Couldn't determine @id of " + target);
}
for (const targetList of [activity.to, activity.cc, activity.bcc]) {
if (!targetList) {
continue;
}
const targets = ensureArray<string | ASObject>(targetList);
const idsOfTargets = targets.map((i: string | ASObject) => getJsonLdId(i));
if (idsOfTargets.includes(targetId)) {
return true;
}
}
return false;
};
// route for ActivityPub Outbox
// https://w3c.github.io/activitypub/#outbox
function outboxHandler({
activities,
// external location of distbin (used for delivery)
externalUrl,
internalUrl,
deliverToLocalhost,
}: {
activities: ActivityMap;
externalUrl: string;
internalUrl: string;
deliverToLocalhost: boolean;
}) {
return async (req: IncomingMessage, res: ServerResponse) => {
switch (req.method.toLowerCase()) {
case "get":
res.writeHead(200, {
"content-type": "application/json",
});
res.end(
JSON.stringify(
{
"@context": "https://www.w3.org/ns/activitystreams",
items: [],
type: "OrderedCollection",
},
null,
2,
),
);
break;
case "post":
const requestBody = await readableToString(req);
const newuuid = createUUID();
let parsed: { [key: string]: any };
try {
parsed = JSON.parse(requestBody);
} catch (e) {
res.writeHead(400);
res.end("Couldn't parse request body as JSON: " + requestBody);
return;
}
// https://w3c.github.io/activitypub/#object-without-create
// The server must accept a valid [ActivityStreams] object that isn't a subtype
// of Activity in the POST request to the outbox.
// The server then must attach this object as the object of a Create Activity.
const submittedActivity = as2ObjectIsActivity(parsed)
? parsed
: Object.assign(
{
"@context": "https://www.w3.org/ns/activitystreams",
object: parsed,
type: "Create",
},
// copy over audience from submitted object to activity
["to", "cc", "bcc"].reduce(
(props: { [key: string]: any }, key) => {
if (key in parsed) {
props[key] = parsed[key];
}
return props;
},
{},
),
);
const newActivity = Object.assign(
{
type: "Activity",
},
submittedActivity,
{
// #TODO: validate that newActivity wasn't submitted with an .id, even though spec says to rewrite it
id: uuidUri(newuuid),
// #TODO: what if it already had published?
published: new Date().toISOString(),
},
typeof submittedActivity.object === "object" && {
// ensure object has id
object: Object.assign(
{ id: uuidUri(createUUID()) },
submittedActivity.object,
),
},
);
// #TODO: validate the activity. Like... you probably shouldn't be able to just send '{}'
const location = "/activities/" + newuuid;
// Save
await activities.set(newActivity.id, newActivity);
res.writeHead(201, { location });
try {
// Target and Deliver to other inboxes
const activityToDeliver = locallyHostedActivity(newActivity, {
externalUrl,
});
await targetAndDeliver(
activityToDeliver,
undefined,
deliverToLocalhost,
internalUrlRewriter(internalUrl, externalUrl),
);
} catch (e) {
debuglog("Error delivering activity other inboxes", e);
if (e.name === "SomeDeliveriesFailed") {
const failures = e.failures.map((f: Error) => {
return {
message: f.message,
name: f.name,
};
});
// #TODO: Retry some day
res.end(
JSON.stringify({
content:
"Activity was created, but delivery to some others servers'" +
"inbox failed. They will not be retried.",
failures,
}),
);
await activities.set(
newActivity.id,
Object.assign({}, newActivity, {
"distbin:activityPubDeliveryFailures": failures,
"distbin:activityPubDeliverySuccesses": e.successes,
}),
);
return;
}
throw e;
}
res.end();
break;
default:
return errorHandler(405, new Error("Method not allowed: "))(req, res);
}
};
}
// route for ActivityPub Public Collection
// https://w3c.github.io/activitypub/#public-addressing
function publicCollectionHandler({
activities,
externalUrl,
}: {
activities: ActivityMap;
externalUrl: ExternalUrl;
}) {
return async (req: IncomingMessage, res: ServerResponse) => {
const maxMemberCount = requestMaxMemberCount(req) || 10;
const publicActivities = [];
const itemsForThisPage = [];
const allActivities = [...(await Promise.resolve(activities.values()))]
.sort((a, b) => {
if (a.published < b.published) {
return -1;
} else if (a.published > b.published) {
return 1;
} else {
// assume ids aren't equal. If so we have a bigger problem
return a.id < b.id ? -1 : 1;
}
})
.reverse();
for (const activity of allActivities) {
if (!activityHasTarget(activity, publicCollectionId)) {
continue;
}
publicActivities.push(activity);
if (itemsForThisPage.length < maxMemberCount) {
itemsForThisPage.push(activity);
}
}
const currentItems = itemsForThisPage.map(activity => {
if (isHostedLocally(activity)) {
return locallyHostedActivity(activity, { externalUrl });
}
return activity;
});
const totalItems = publicActivities.length;
// empty string is relative URL for 'self'
const currentUrl = [req.url, req.url.endsWith("/") ? "" : "/", "page"].join(
"",
);
const publicCollection = {
"@context": "https://www.w3.org/ns/activitystreams",
current: {
href: currentUrl,
mediaType: "application/json",
name: "Recently updated public activities",
rel: "current",
type: "Link",
},
first: currentUrl,
id: "https://www.w3.org/ns/activitypub/Public",
// Get recent 10 items
items: currentItems,
totalItems,
type: "Collection",
};
res.writeHead(200, {
"content-type": "application/json",
});
res.end(JSON.stringify(publicCollection, null, 2));
};
}
interface IPropertyFilter {
readonly [key: string]: Comparison;
}
interface IAndExpression {
and: Filter[];
}
function isAndExpression(expression: object): expression is IAndExpression {
// magic happens here
return (expression as IAndExpression).and !== undefined;
}
interface IOrExpression {
or: Filter[];
}
function isOrExpression(expression: object): expression is IOrExpression {
// magic happens here
return (expression as IOrExpression).or !== undefined;
}
type CompoundFilter = IAndExpression | IOrExpression;
function isCompoundFilter(filter: object): filter is CompoundFilter {
return isAndExpression(filter) || isOrExpression(filter);
}
type Filter = IPropertyFilter | CompoundFilter;
type FilterComparison = "lt" | "equals";
type Cursor = CompoundFilter;
interface ILessThanComparison {
lt: string;
}
function isLessThanComparison(
comparison: object,
): comparison is ILessThanComparison {
return Boolean((comparison as ILessThanComparison).lt);
}
interface IEqualsComparison {
equals: string;
}
function isEqualsComparison(
comparison: object,
): comparison is IEqualsComparison {
return Boolean((comparison as IEqualsComparison).equals);
}
type Comparison = ILessThanComparison | IEqualsComparison;
function isComparison(comparison: object): comparison is Comparison {
return Boolean(
(comparison as ILessThanComparison).lt ||
(comparison as IEqualsComparison).equals,
);
}
function getClauses(expression: CompoundFilter): Filter[] {
if (isAndExpression(expression)) {
return expression.and;
} else if (isOrExpression(expression)) {
return expression.or;
}
}
const createMatchesCursor = (cursor: CompoundFilter) => (
activity: Extendable<Activity>,
) => {
assert.equal(Object.keys(cursor).length, 1);
const clauses: Filter[] = getClauses(cursor) || [];
for (const filter of clauses) {
assert.equal(Object.keys(filter).length, 1);
const prop = Object.keys(filter)[0];
let matchesRequirement: boolean;
// if (prop instanceof IAndExpression | IOrExpression | EqualsExpression) {
if (isCompoundFilter(filter)) {
const compoundFilter: CompoundFilter = filter;
// this is another expression, recurse
matchesRequirement = createMatchesCursor(compoundFilter)(activity);
} else {
const IpropertyFilter: IPropertyFilter = filter;
const comparison: Comparison = IpropertyFilter[prop];
const propValue = activity[prop];
if (isLessThanComparison(comparison)) {
matchesRequirement = propValue < comparison.lt;
} else if (isEqualsComparison(comparison)) {
matchesRequirement = propValue === comparison.equals;
}
}
if (matchesRequirement && isOrExpression(cursor)) {
return true;
}
if (!matchesRequirement && isAndExpression(cursor)) {
return false;
}
}
if (isOrExpression(cursor)) {
return false;
}
if (isAndExpression(cursor)) {
return true;
}
};
function publicCollectionPageHandler({
activities,
externalUrl,
}: {
activities: Map<string, Activity>;
externalUrl: ExternalUrl;
}) {
return async (req: IncomingMessage, res: ServerResponse) => {
const maxMemberCount = requestMaxMemberCount(req) || 10;
const parsedUrl = url.parse(req.url, true);
let cursor;
let matchesCursor = (a: Activity) => true;
if (parsedUrl.query.cursor) {
try {
cursor = JSON.parse(first(parsedUrl.query.cursor));
} catch (error) {
res.writeHead(400);
res.end(JSON.stringify({ message: "Invalid cursor in querystring" }));
return;
}
matchesCursor = createMatchesCursor(cursor);
}
const publicActivities = [];
const itemsForThisPage = [];
// @todo ensure sorted by both published and id
const allActivities = [...(await Promise.resolve(activities.values()))]
.sort((a, b) => {
if (a.published < b.published) {
return -1;
} else if (a.published > b.published) {
return 1;
} else {
// assume ids aren't equal. If so we have a bigger problem
return a.id < b.id ? -1 : 1;
}
})
.reverse();
let itemsBeforeCursor = 0;
for (const activity of allActivities) {
if (!activityHasTarget(activity, publicCollectionId)) {
continue;
}
publicActivities.push(activity);
if (!matchesCursor(activity)) {
itemsBeforeCursor++;
continue;
}
if (itemsForThisPage.length < maxMemberCount) {
itemsForThisPage.push(activity);
}
}
const currentItems = itemsForThisPage.map(activity => {
if (isHostedLocally(activity)) {
return locallyHostedActivity(activity, { externalUrl });
}
return activity;
});
const totalItems = publicActivities.length;
let next;
if (totalItems > currentItems.length) {
const lastItem = currentItems[currentItems.length - 1];
if (lastItem) {
const nextCursor = JSON.stringify({
or: [
{ published: { lt: lastItem.published } },
{
and: [
{ published: { equals: lastItem.published } },
{ id: { lt: lastItem.id } },
],
},
],
});
next = "?" + querystring.stringify({ cursor: nextCursor });
}
}
const collectionPage = {
"@context": "https://www.w3.org/ns/activitystreams",
next,
orderedItems: currentItems,
partOf: "/activitypub/public",
startIndex: itemsBeforeCursor,
type: "OrderedCollectionPage",
};
res.writeHead(200, {
"content-type": "application/json",
});
res.end(JSON.stringify(collectionPage, null, 2));
};
}
function errorHandler(statusCode: number, error?: Error) {
if (error) {
logger.error("", error);
}
return (req: IncomingMessage, res: ServerResponse) => {
res.writeHead(statusCode);
const responseText = error ? error.toString() : statusCode.toString();
res.end(responseText);
};
} | the_stack |
import * as Long from 'long';
import {SqlRow, SqlRowImpl} from './SqlRow';
import {SqlRowMetadata} from './SqlRowMetadata';
import {SqlPage} from './SqlPage';
import {SqlServiceImpl} from './SqlService';
import {Connection} from '../network/Connection';
import {SqlQueryId} from './SqlQueryId';
import {DeferredPromise, deferredPromise} from '../util/Util';
import {HazelcastSqlException, IllegalStateError, UUID} from '../core';
import {SqlErrorCode} from './SqlErrorCode';
import {Data} from '../serialization';
/**
* An {@link SqlResult} iterates over this type if {@link SqlStatementOptions.returnRawResult} is set to `false`
* (by default `false`) while {@link SqlService.execute | executing} an SQL query.
*
* Keys are column names and values are values in the SQL row.
*/
export type SqlRowAsObject = { [key: string]: any };
/**
* Represents one of {@link SqlRow} and {@link SqlRowAsObject}.
*/
export type SqlRowType = SqlRow | SqlRowAsObject;
/**
* SQL query result. Depending on the statement type it represents a stream of rows or an update count.
*
* ### Iteration
*
* An `SqlResult` is an async iterable of {@link SqlRowType} which is either an {@link SqlRow} or regular JavaScript objects.
* By default it returns regular JavaScript objects, containing key and values. Keys represent column names, whereas
* values represent row values. The default object returning behavior can be changed via the option
* {@link SqlStatementOptions.returnRawResult}. If it is true, {@link SqlRow} objects are returned instead of regular objects.
*
* Values in SQL rows are deserialized lazily. While iterating you will get a {@link HazelcastSqlException} if a value in SQL row
* cannot be deserialized.
*
* Use {@link close} to release the resources associated with the result.
*
* An `SqlResult` can be iterated only once.
*
* #### for-await... of
*
* Refer to [for-await... of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of)
* page for more information.
*
* ```js
* for await (const row of result) {
* console.log(row);
* }
* ```
*
* #### next()
*
* Another approach of iterating rows is using the {@link next} method. Every call to `next` returns an object with `done` and
* `value` properties. `done` is `false` when there are more rows to iterate, `true` otherwise. `value` holds the current row
* value. Refer to [iterators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) for more
* information about iteration in JavaScript.
*
* ```js
* let row = await result.next();
* while (!row.done) {
* console.log(row.value);
* row = await result.next();
* }
* ```
*
* ### Usage for update count
* ```js
* const updateCount = result.updateCount; // A Long object
* ```
*
* You don't need to call {@link close} in this case.
*
*/
export interface SqlResult extends AsyncIterable<SqlRowType> {
/**
* Returns next {@link SqlRowType} iteration result. You should not call this method when result does not contain
* rows.
* @throws {@link IllegalStateError} if result does not contain rows, but update count.
* @throws {@link HazelcastSqlException} if a value in current row cannot be deserialized.
* @returns an object including `value` and `done` keys. The `done` key indicates if
* iteration is ended, i.e when there are no more results. `value` holds iteration values which are in SqlRowType type.
* `value` has undefined value if iteration has ended.
*/
next(): Promise<IteratorResult<SqlRowType>>;
/**
* Releases the resources associated with the query result.
*
* The query engine delivers the rows asynchronously. The query may become inactive even before all rows are
* consumed. The invocation of this command will cancel the execution of the query on all members if the query
* is still active. Otherwise it is no-op. For a result with an update count it is always no-op.
*/
close(): Promise<void>;
/**
* SQL row metadata if rows exist in the result; otherwise null.
*/
readonly rowMetadata: SqlRowMetadata | null;
/**
* Return whether this result has rows to iterate. False if update count is returned, true if rows are returned.
* @returns whether this result is a row set
*/
isRowSet(): boolean;
/**
* The number of rows updated by the statement or `-1` if this result is a row set.
*/
readonly updateCount: Long;
}
/** @internal */
export class SqlResultImpl implements SqlResult {
/** Update count received as a result of SQL execution. See {@link SqlExpectedResultType} */
updateCount: Long;
private currentPage: SqlPage | null;
/* The number of rows in current page */
private currentRowCount: number;
/* Current row position in current page */
private currentPosition: number;
/* Set to true when the last page is received */
private last: boolean;
/**
* Deferred promise that resolves to an SqlPage when current fetch request is completed.
*/
private fetchDeferred: DeferredPromise<SqlPage>;
/**
* Deferred promise that resolves when current close request is completed.
*/
private closeDeferred: DeferredPromise<void>;
/**
* Whether the result is closed or not. The result is closed if an update count or the last page is received.
* When true, there is no need to send the `cancel` request to the server.
*/
private closed: boolean;
/**
* Row metadata of the result. Initially null.
*/
rowMetadata: SqlRowMetadata | null;
constructor(
private readonly sqlService: SqlServiceImpl,
private readonly deserializeFn: (data: Data, isRaw: boolean) => any,
private readonly connection: Connection,
private readonly queryId: SqlQueryId,
/** The page size used for pagination */
private readonly cursorBufferSize: number,
/** If true, SqlResult is an object iterable, otherwise SqlRow iterable */
private readonly returnRawResult: boolean,
private readonly clientUUID: UUID
) {
this.closed = false;
this.last = false;
this.rowMetadata = null;
this.currentPage = null;
}
/** This symbol is needed to be included to be an async iterable */
[Symbol.asyncIterator](): AsyncIterator<SqlRowType, SqlRowType, SqlRowType> {
const nextFn = this.next.bind(this);
return {
next: nextFn
}
}
/**
* Useful for mocking. (Constructor mocking is hard/impossible)
* @returns new result object.
*/
static newResult(
sqlService: SqlServiceImpl,
deserializeFn: (data: Data, isRaw: boolean) => any,
connection: Connection,
queryId: SqlQueryId,
cursorBufferSize: number,
returnRawResult: boolean,
clientUUID: UUID
) {
return new SqlResultImpl(sqlService, deserializeFn, connection, queryId, cursorBufferSize, returnRawResult, clientUUID);
}
isRowSet(): boolean {
return this.rowMetadata !== null;
}
close(): Promise<void> {
// Return the close promise if a close request is already started
if (this.closeDeferred) {
return this.closeDeferred.promise;
}
// If already closed, return a resolved promise
if (this.closed) {
return Promise.resolve();
}
this.closeDeferred = deferredPromise<void>();
const error = new HazelcastSqlException(this.clientUUID, SqlErrorCode.CANCELLED_BY_USER,
'Query was cancelled by user');
// Prevent ongoing/future fetch requests
if (!this.fetchDeferred) {
this.fetchDeferred = deferredPromise<SqlPage>();
this.fetchDeferred.promise.catch(() => {});
}
this.fetchDeferred.reject(error);
// Send the close request.
this.sqlService.close(this.connection, this.queryId).then(() => {
this.closeDeferred.resolve();
}).catch(err => {
this.closeDeferred.reject(this.sqlService.rethrow(err, this.connection));
});
this.closed = true;
return this.closeDeferred.promise;
}
/**
* Called when next page of the result is received.
* @param page
*/
private onNextPage(page: SqlPage) {
this.currentPage = page;
this.currentRowCount = page.getRowCount();
this.currentPosition = 0;
if (page.last) {
this.last = true;
this.closed = true;
}
}
/**
* Called when an error is occurred during SQL execution.
* @param error The wrapped error that can be propagated to the user through executeDeferred.
*/
onExecuteError(error: HazelcastSqlException): void {
this.updateCount = Long.fromInt(-1);
this.rowMetadata = null;
}
/**
* Used by {@link next}.
* @returns the current row.
*/
private getCurrentRow(): SqlRowType {
if (this.returnRawResult) { // Return SqlRow
const columnCount = this.currentPage.getColumnCount();
const values = new Array(columnCount);
for (let i = 0; i < columnCount; i++) {
values[i] = this.currentPage.getValue(this.currentPosition, i);
}
// Deserialization happens lazily while getting the object.
return new SqlRowImpl(values, this.rowMetadata, this.deserializeFn);
} else { // Return objects
const result: SqlRowAsObject = {};
for (let i = 0; i < this.currentPage.getColumnCount(); i++) {
const columnMetadata = this.rowMetadata.getColumn(i);
result[columnMetadata.name] = this.deserializeFn(this.currentPage.getValue(this.currentPosition, i), false);
}
return result;
}
}
/**
* Called when a execute response is received.
* @param rowMetadata The row metadata. It is null if the response only contains the update count.
* @param rowPage The first page of the result. It is null if the response only contains the update count.
* @param updateCount The update count.
*/
onExecuteResponse(rowMetadata: SqlRowMetadata | null, rowPage: SqlPage | null, updateCount: Long) {
if (rowMetadata !== null) { // Result that includes rows
this.rowMetadata = rowMetadata;
this.onNextPage(rowPage);
this.updateCount = Long.fromInt(-1);
} else { // Result that includes update count
this.updateCount = updateCount;
this.closed = true;
}
}
/**
* Fetches the next page. Called internally by iteration logic. Pages are fetched whenever the current page is fully
* iterated.
*/
fetch(): Promise<SqlPage> {
// If there is an ongoing fetch, return that promise
if (this.fetchDeferred) {
return this.fetchDeferred.promise;
}
// Do not start a fetch if the result is already closed
if (this.closed) {
return Promise.reject(new IllegalStateError('Cannot fetch, the result is already closed'));
}
this.fetchDeferred = deferredPromise<SqlPage>();
this.sqlService.fetch(this.connection, this.queryId, this.cursorBufferSize).then(sqlPage => {
this.fetchDeferred.resolve(sqlPage);
this.fetchDeferred = undefined; // Set fetchDeferred to undefined to be able to fetch again
}).catch(err => {
this.fetchDeferred.reject(this.sqlService.rethrow(err, this.connection));
});
return this.fetchDeferred.promise;
}
/**
* Checks if there are rows to iterate in a recursive manner, similar to a non-blocking while block
*/
private checkHasNext(): Promise<boolean> {
if (this.currentPosition === this.currentRowCount) {
// Reached end of the page. Try fetching the next page if there are more.
if (!this.last) {
return this.fetch().then(page => {
this.onNextPage(page);
return this.checkHasNext();
});
} else {
// No more pages are expected, so resolve false.
return Promise.resolve(false);
}
} else {
return Promise.resolve(true);
}
}
/**
* Used by {@link next}.
* @returns if there are rows to be iterated.
*/
private hasNext(): Promise<boolean> {
if (this.rowMetadata === null) {
return Promise.reject(new IllegalStateError('This result contains only update count'));
}
return this.checkHasNext();
}
next(): Promise<IteratorResult<SqlRowType, SqlRowType | undefined>> {
return this.hasNext().then(hasNext => {
if (hasNext) {
const row = this.getCurrentRow();
this.currentPosition++;
return {
done: false,
value: row
};
} else {
return {
done: true,
value: undefined
};
}
});
}
} | the_stack |
import { ChangeDetectorRef, Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { MatDialog, MatSort, MatTableDataSource, Sort } from '@angular/material';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { LoggerService } from '@ngx-engoy/diagnostics-core';
import { User } from 'msal';
import { Subscription } from 'rxjs';
import {
BrowseCloudDocumentWithJobs,
InputType,
inputTypeToString,
JobStatus,
jobStatusToString,
jobStatusToStringDescription
} from '@browsecloud/models';
import { AuthService, BrowseCloudService, JobUpdateService } from '@browsecloud/services';
import { AddDocumentDialogComponent, EditDocumentDialogComponent } from '@browsecloud/shared';
import { Guid } from '@browsecloud/utils';
interface IFilterOptions {
filterText: string;
simpleInput: boolean;
metadataInput: boolean;
selfOwner: boolean;
otherOwner: boolean;
}
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss'],
})
export class DashboardComponent implements OnInit, OnDestroy {
@ViewChild(MatSort, { static: false }) sort: MatSort;
public displayedColumns: string[] = ['name', 'type', 'jobDate', 'status', 'options'];
public documentsWithJobs: BrowseCloudDocumentWithJobs[];
public tableDataSource: MatTableDataSource<BrowseCloudDocumentWithJobs> = new MatTableDataSource();
public filterOptions: IFilterOptions;
public currentSort: Sort;
public user: User;
public noTableElementsToShow = true;
public tableLoading = true;
private jobUpdateSubscription: Subscription;
private queryParamsSubscription: Subscription;
private unfinishedJobCount = 0;
constructor(
private authService: AuthService,
private browseCloudService: BrowseCloudService,
private dialog: MatDialog,
private loggerService: LoggerService,
private changeDetectorRef: ChangeDetectorRef,
private router: Router,
private activatedRoute: ActivatedRoute,
private titleService: Title,
private jobUpdateService: JobUpdateService
) { }
public ngOnInit(): void {
// Get current user.
this.user = this.authService.getUser();
this.titleService.setTitle('BrowseCloud | Dashboard');
this.queryParamsSubscription = this.activatedRoute.queryParams
.subscribe(
(params) => {
if (params['action'] === 'add') {
// HACK: https://github.com/angular/material2/issues/5268
setTimeout(() => this.openNewDocumentDialog(true), 0);
this.router.navigateByUrl('/');
}
}
);
// Setup data table.
this.tableDataSource.sortingDataAccessor = (row, sortHeaderId) => {
switch (sortHeaderId) {
case this.displayedColumns[0]:
return row.document.displayName;
case this.displayedColumns[1]:
return row.document.inputType;
case this.displayedColumns[2]:
return row.jobs[0] == null ? -1 : row.jobs[0].submitDateTime.getTime();
case this.displayedColumns[3]:
return row.jobs[0].jobStatus;
}
};
this.filterOptions = {
filterText: null,
otherOwner: true,
selfOwner: true,
simpleInput: true,
metadataInput: true,
};
this.currentSort = {
active: 'jobDate',
direction: 'desc',
};
// Get data.
this.browseCloudService.getAllDocumentsWithJobs(false)
.subscribe(
// No unsubscribe needed. Observable completes.
(docs) => {
this.documentsWithJobs = docs;
this.updateTableDataSource();
this.tableLoading = false;
// Set initial unfinished jobs count.
// At this point, jobs are cached, so just grab them from the service.
this.browseCloudService.getAllJobs(false)
// No unsubscribe needed. Observable completes.
.subscribe(
(jobs) => {
this.unfinishedJobCount = jobs
.filter((j) => j.jobStatus !== JobStatus.Success && j.jobStatus !== JobStatus.Failure).length;
if (this.unfinishedJobCount > 0) {
this.connectJobStatusUpdates();
}
}
);
},
(error) => {
this.tableLoading = false;
}
);
this.loggerService.event('Dashboard.Load');
}
public ngOnDestroy(): void {
if (this.jobUpdateSubscription != null) {
this.jobUpdateSubscription.unsubscribe();
}
if (this.queryParamsSubscription != null) {
this.queryParamsSubscription.unsubscribe();
}
}
public onDeleteDocument(documentWithJobs: BrowseCloudDocumentWithJobs): void {
this.tableLoading = true;
const documentId = documentWithJobs.document.id;
const index = this.documentsWithJobs.findIndex((d) => d.document.id === documentId);
this.browseCloudService.deleteDocument(documentId)
.subscribe(
// No unsubscribe needed. Observable completes.
() => {
this.documentsWithJobs.splice(index, 1);
this.updateTableDataSource();
this.tableLoading = false;
this.loggerService.event('Dashboard.Document.Delete', {
documentId,
});
},
(error) => {
this.tableLoading = false;
}
);
}
public onEditDocument(documentWithJobs: BrowseCloudDocumentWithJobs): void {
const dialogRef = this.dialog.open(EditDocumentDialogComponent);
dialogRef.componentInstance.setDocument(documentWithJobs.document);
this.loggerService.event('Dashboard.Document.Edit.Start', {
documentId: documentWithJobs.document.id,
});
dialogRef.afterClosed()
.subscribe(
// No unsubscribe needed. Observable completes.
(result) => {
if (result != null) {
const index = this.documentsWithJobs.findIndex((d) => d.document.id === documentWithJobs.document.id);
this.documentsWithJobs[index].document = result;
this.updateTableDataSource();
this.loggerService.event('Dashboard.Document.Edit.Complete', {
documentId: documentWithJobs.document.id,
});
}
}
);
}
public openNewDocumentDialog(addToGallery: boolean = false): void {
const dialogRef = this.dialog.open(AddDocumentDialogComponent);
dialogRef.componentInstance.isPublic = addToGallery;
const correlationId = Guid.newGuid().toString();
this.loggerService.event('Dashboard.Document.New.Start', {
correlationId,
});
dialogRef.afterClosed()
.subscribe(
// No unsubscribe needed. Observable completes.
(result) => {
if (result != null) {
this.unfinishedJobCount += 1;
this.connectJobStatusUpdates();
this.documentsWithJobs.push(result as BrowseCloudDocumentWithJobs);
this.updateTableDataSource();
this.loggerService.event('Dashboard.Document.New.Complete', {
correlationId,
});
}
}
);
}
public updateTableDataSource(): void {
const filteredData = this.getFilteredData();
this.noTableElementsToShow = filteredData.length === 0;
this.tableDataSource.data = filteredData;
// Detect changes, because the matTable needs to be displayed to make this.sort available.
this.changeDetectorRef.detectChanges();
this.tableDataSource.sort = this.sort;
}
public onViewDocument(documentWithJobs: BrowseCloudDocumentWithJobs): void {
this.router.navigate([`/visualization/${documentWithJobs.document.id}`]);
}
public inputTypeToString(inputType: InputType): string {
return inputTypeToString(inputType);
}
public jobStatusToString(jobStatus: JobStatus): string {
return jobStatusToString(jobStatus);
}
public jobStatusToStringDescription(jobStatus: JobStatus): string {
return jobStatusToStringDescription(jobStatus);
}
private getFilteredData(): BrowseCloudDocumentWithJobs[] {
return this.documentsWithJobs.filter((row) => {
let showBasedOnSearch = true;
if (this.filterOptions.filterText != null) {
showBasedOnSearch = row.document.displayName.trim().toLowerCase().includes(
this.filterOptions.filterText.trim().toLowerCase()
);
}
return showBasedOnSearch
&& ((this.filterOptions.simpleInput && row.document.inputType === InputType.SimpleInput)
|| (this.filterOptions.metadataInput && row.document.inputType === InputType.MetadataInput))
&& ((this.filterOptions.selfOwner && row.document.owner.principalName === this.user.displayableId)
|| (this.filterOptions.otherOwner && row.document.owner.principalName !== this.user.displayableId));
});
}
private connectJobStatusUpdates(): void {
// Start signalr connection subscription if it does not exist yet.
if (this.jobUpdateSubscription == null) {
this.jobUpdateSubscription = this.jobUpdateService.startConnection()
.subscribe(
(job) => {
if (job == null) {
return;
}
this.browseCloudService.updateJobCache(job);
const docIndex = this.documentsWithJobs.findIndex((d) => d.document.id === job.documentId);
if (docIndex !== -1) {
const jobList = this.documentsWithJobs[docIndex].jobs;
const jobIndex = jobList.findIndex((j) => j.id === job.id);
if (jobIndex !== -1) {
this.documentsWithJobs[docIndex].jobs[jobIndex] = job;
}
this.updateTableDataSource();
}
if (job.jobStatus === JobStatus.Success || job.jobStatus === JobStatus.Failure) {
this.unfinishedJobCount -= 1;
if (this.unfinishedJobCount <= 0) {
this.jobUpdateSubscription.unsubscribe();
// No unsubscribe needed. Observable completes.
this.jobUpdateService.stopConnection().subscribe();
}
}
}
);
}
}
} | the_stack |
declare function require(arg: string): string;
import {
DownloadMethod,
DownloadMethodKeys,
DownloadQuality,
DownloadQualityKeys,
IEpisode,
Intent,
IRuntimeMessage,
Server,
} from "../common";
import * as utils from "../utils";
// see core.ts to understand what the variables
// below mean.
let server: Server = Server.Default;
let method: DownloadMethod = DownloadMethod.Browser;
let isDownloading = false;
let ts = "";
let animeName = "";
// --- added on 25-11-2017
// ID of current selected server
let serverId = "";
// Contains most of the selectors used. Can be
// used to quickly access the required selectors
// without having to remember the names.
const selectors = {
closeBtn: ".nac__modal__close",
copyLinks: "#nac__dl-all__copy-links", /* linksModal */
dlBtn: ".nac__dl-all__btn", /* Page */
download: "#nac__dl-all__download", /* epModal */
epModal: "#nac__dl-all__ep-modal", /* epModal */
links: "#nac__dl-all__links", /* linksModal */
linksModal: "#nac__dl-all__links-modal", /* linksModal */
method: "#nac__dl-all__method", /* epModal */
quality: "#nac__dl-all__quality", /* epModal */
selectAll: "#nac__dl-all__select-all", /* linksModal */
status: "#nac__dl-all__status", /* Page */
statusBar: ".nac__dl-all__status-bar", /* Page */
};
interface ISetupOptions {
name: string;
ts: string;
}
// Setup
export function setup(options: ISetupOptions) {
animeName = options.name;
ts = options.ts;
// Rest of the setup process
let body = $("body");
let servers = $(".server.row > label");
$("#servers").prepend(statusBar());
body.append(epModal());
body.append(linksModal());
// attach the download all buttons to the server labels
for (let s of servers) {
let serverLabel = $(s).text();
// Basically what we are doing here is testing
// the labels and adding appropriate dl buttons.
if (/Server\s+F/i.test(serverLabel)) {
$(s).append(downloadBtn(Server.Default));
} else if (/Server\s+G/i.test(serverLabel)) {
$(s).append(downloadBtn(Server.Default));
} else if (/RapidVideo/i.test(serverLabel)) {
$(s).append(downloadBtn(Server.RapidVideo));
}
}
}
// *** Animations ***
function showModal(selector: string): void {
let modal = $(selector);
$(modal).show();
$(modal).find(".container").addClass("fade_in");
$("body").css("overflow", "hidden");
setTimeout(() => {
$(modal).find(".container").removeClass("fade_in");
}, 500);
}
function hideModal(selector: string): void {
let modal = $(selector);
$(modal).find(".container").addClass("fade_out");
setTimeout(() => {
$(modal).find(".container").removeClass("fade_out");
$(modal).hide();
$("body").css("overflow", "auto");
}, 500);
}
function shakeModal(selector: string): void {
let modal = $(selector);
$(modal).find(".container").addClass("shake");
setTimeout(() => {
$(modal).find(".container").removeClass("shake");
}, 820);
}
function disableInputs(): void {
$(selectors.dlBtn).attr("disabled", "disabled");
}
function enableInputs(): void {
$(selectors.dlBtn).removeAttr("disabled");
}
export function statusBar() {
return `
<div class="nac__dl-all__status-bar" style="display: none;">
<span>Status:</span>
<div id="nac__dl-all__status">ready to download...</div>
</div>`;
}
/**
* Returns a 'Download' button.
* @param {Server} targetServer
* The server from which episodes will be downloaded.
* Allowed types are Server.Default and Server.RapidVideo.
* @returns
* A nicely generated 'Download' button
*/
export function downloadBtn(targetServer: Server): JQuery<HTMLElement> {
let btn = $(`<button data-type="${targetServer}" class="nac__dl-all__btn">Download</button>`);
btn.on("click", e => {
// This array hold's all the the episodes of the current
// anime for a particular server (ex: RapidVideo, F2, F4)
let episodes: IEpisode[] = [];
server = $(e.currentTarget).data("type");
// TODO: maybe all of this should be generated only once or somehow cached
// Every time the 'Download' button is clicked,
// all the episodes for the current server are
// fetched and added to "episodes".
let epLinks = $(e.currentTarget).parents(".server.row").find(".episodes > li > a");
for (let ep of epLinks) {
let id = $(ep).data("id");
let num = $(ep).data("base");
if (id && num) {
episodes.push({
id, /* short hand property. "id" means id: id */
num: utils.pad(num),
});
}
}
// Then we iterate through "episodes" and add each
// episode to the "epModal". The user can then take
// further action.
let modalBody = $(selectors.epModal).find(".body");
const episodesContainer = $(`<div class="nac__dl-all__episodes-container"></div>`);
// Delete the earlier episodes and start fresh
modalBody.empty();
for (let ep of episodes) {
let epSpan = $(
// TODO: do we really need the animeName in the download box? looks a bit crowded
`<span class="nac__dl-all__episode">
<input type="checkbox" id="${ep.id}" data-num="${ep.num}">
<label for="${ep.id}">${animeName}: Ep. ${ep.num}</label>
</span>`);
episodesContainer.append(epSpan);
}
modalBody.append(episodesContainer);
/* --- Server ID added on 25-11-2017 --- */
serverId = btn.parents(".server.row").data("id");
/* --- ~~~ --- */
showModal(selectors.epModal);
});
return btn;
}
/**
* Returns a modal which will be used for displaying links
* when download method external is chosen.
* @returns
* The Links Modal
*/
export function linksModal(): JQuery<HTMLElement> {
let template = require("html-loader!../../templates/dlAll_linksModal.html");
let modal = $(template);
let clipboardIcon = chrome.extension.getURL("images/clipboard.png");
// 1> Add the clipboard icon to the button
modal.find(selectors.copyLinks).find("img").attr("src", clipboardIcon);
// 2> When the overlay is clicked, the modal hides
modal.on("click", e => {
if (e.target === modal[0]) {
hideModal(selectors.linksModal);
}
});
// 3> When the close btn is clicked, the modal hides
modal.find(selectors.closeBtn).on("click", e => {
hideModal(selectors.linksModal);
});
// 4> Bind functionality to the 'Copy to clipboard' button.
modal.find(selectors.copyLinks).on("click", () => {
$(selectors.links).select();
document.execCommand("copy");
});
// When the modal is first attached, it should be hidden.
// Not to be confused with hideModal() function.
modal.hide();
return modal;
}
/**
* Returns a modal which will be used for displaying the
* episodes checklist, quality preference and downloader
* select before the user downloads.
* @returns
* The Episode Select Modal
*/
export function epModal(): JQuery<HTMLElement> {
// We wil start by loading the template from an external file.
let template = require("html-loader!../../templates/dlAll_epModal.html");
let modal = $(template);
// Get the last download quality. This is basically a convenience feature.
// This was suggested in #6.
let lastQuality = localStorage.getItem("9AC__lastDownloadQuality");
if (lastQuality) {
modal.find("#nac__dl-all__quality").val(lastQuality);
}
// 1> Add the anime name to the "header"
modal.find(".title").text(`Download ${animeName} episodes:`);
// 2> When the overlay is clicked, the modal hides
modal.on("click", e => {
if (e.target === modal[0]) {
hideModal(selectors.epModal);
}
});
// 3> When the close btn is clicked, the modal hides
modal.find(selectors.closeBtn).on("click", e => {
hideModal(selectors.epModal);
});
// 4> Bind functionality for the "Select All" button
modal.find(selectors.selectAll).on("click", () => {
$(selectors.epModal).find(".body input[type='checkbox']").prop("checked", true);
});
// 5> Bind functionality for the "Download" button
modal.find(selectors.download).on("click", () => {
if (!isDownloading) {
let selectedEpisodes: IEpisode[] = [];
// This part might look a bit complex but what its actually doing is
// mapping the select value in the modal to DownloadQuality and
// DownloadMethod types.
let quality: DownloadQuality = DownloadQuality[$(selectors.quality).val() as DownloadQualityKeys]
|| DownloadQuality["360p"];
method = DownloadMethod[$(selectors.method).val() as DownloadMethodKeys] || DownloadMethod.Browser;
// First, we get all the checked episodes in the
// modal and push these to selectedEpisodes.
$(selectors.epModal)
.find(".body input[type='checkbox']:checked")
.each((i, el) => {
selectedEpisodes.push({
id: $(el).attr("id") || "",
num: $(el).data("num"),
});
});
// And... let it rip!
if (selectedEpisodes.length > 0) {
isDownloading = true;
disableInputs();
hideModal(selectors.epModal);
$(selectors.statusBar).slideDown();
// Well since content scripts cant really download
// we will send a message to the background script
// which will do it for us.
chrome.runtime.sendMessage({
animeName,
// Note: location.origin is not supported in all browser
baseUrl: window.location.origin,
server,
intent: Intent.Download_All,
method,
quality,
selectedEpisodes,
serverId,
ts,
});
// Save the last chosen download quality to the browser local storage.
localStorage.setItem("9AC__lastDownloadQuality", DownloadQuality[quality]);
} else {
// Gotta select some episodes!!!
shakeModal(selectors.epModal);
}
}
});
// When the modal is first attached, it should be hidden.
// Not to be confused with hideModal() function.
modal.hide();
return modal;
}
/**
* This part will notify us when the downloads are complete.
*/
chrome.runtime.onMessage.addListener((message: IRuntimeMessage) => {
switch (message.intent) {
case Intent.Download_Complete:
// If method is external, display the aggregate links.
// We just need to make sure that if links are empty,
// which can happen if all the downloads failed, then
// we don't show the links modal.
if (method === DownloadMethod.External && message.links) {
$(selectors.links).text(message.links);
showModal(selectors.linksModal);
}
$(selectors.statusBar).slideUp();
isDownloading = false;
enableInputs();
break;
case Intent.Download_Status:
$(selectors.status).text(message.status);
break;
default:
break;
}
}); | the_stack |
import { EventListenerRegister, HumiditySensor, OnOff, ScryptedDevice, ScryptedDeviceBase, ScryptedInterface, ScryptedInterfaceProperty, Setting, Settings, SettingValue, TemperatureSetting, TemperatureUnit, Thermometer, ThermostatMode } from '@scrypted/sdk';
import { StorageSettings } from "../../../common/src/settings"
class ThermostatDevice extends ScryptedDeviceBase implements TemperatureSetting, Thermometer, HumiditySensor, Settings {
sensor: Thermometer & HumiditySensor & ScryptedDevice;
heater: OnOff & ScryptedDevice;
cooler: OnOff & ScryptedDevice;
listeners: EventListenerRegister[] = [];
storageSettings = new StorageSettings(this, {
sensor: {
title: 'Thermometer',
description: 'The thermometer used by this virtual thermostat to regulate the temperature.',
type: 'device',
deviceFilter: `interfaces.includes("${ScryptedInterface.Thermometer}")`,
onPut: () => this.updateSettings(),
},
heater: {
title: 'Heating Switch',
description: 'Optional: The switch that controls your heating unit.',
type: `device`,
deviceFilter: `interfaces.includes("${ScryptedInterface.OnOff}")`,
onPut: () => this.updateSettings(),
},
cooler: {
title: 'Cooling Switch',
description: 'Optional: The switch that controls your cooling unit.',
type: `device`,
deviceFilter: `interfaces.includes("${ScryptedInterface.OnOff}")`,
onPut: () => this.updateSettings(),
},
temperatureUnit: {
title: 'Temperature Unit',
choices: ['C', 'F'],
defaultValue: 'C',
onPut: () => this.updateSettings(),
}
})
constructor() {
super();
this.updateSettings();
this.temperature = this.sensor?.temperature;
this.temperatureUnit = this.storageSettings.values.temperatureUnit;
this.humidity = this.sensor?.humidity;
const modes: ThermostatMode[] = [];
modes.push(ThermostatMode.Off);
if (this.cooler) {
modes.push(ThermostatMode.Cool);
}
if (this.heater) {
modes.push(ThermostatMode.Heat);
}
if (this.heater && this.cooler) {
modes.push(ThermostatMode.HeatCool);
}
modes.push(ThermostatMode.On);
this.thermostatAvailableModes = modes;
if (!this.thermostatMode) {
this.thermostatMode = ThermostatMode.Off;
}
}
async setTemperatureUnit(temperatureUnit: TemperatureUnit): Promise<void> {
this.storageSettings.values.temperatureUnit = temperatureUnit;
this.temperatureUnit = temperatureUnit;
}
manageListener(listener: EventListenerRegister) {
this.listeners.push(listener);
}
clearListeners() {
for (const listener of this.listeners) {
listener.removeListener();
}
this.listeners = [];
}
updateSettings() {
this.clearListeners();
this.sensor = this.storageSettings.values.sensor;
this.heater = this.storageSettings.values.heater;
this.cooler = this.storageSettings.values.cooler;
this.log.clearAlerts();
if (!this.sensor) {
this.log.a('Setup Incomplete: Select a thermometer.');
return;
}
if (!this.heater && !this.cooler) {
this.log.a('Setup Incomplete: Assign the switch that controls the heater or air conditioner devices.');
return;
}
if (!this.sensor) {
this.log.a('Setup Incomplete: Assign a thermometer and humidity sensor to the "sensor" variable.');
return;
}
// register to listen for temperature change events
this.sensor.listen(ScryptedInterface.Thermometer, (s, d, data) => {
if (d.property === ScryptedInterfaceProperty.temperature) {
this.temperature = this.sensor.temperature;
this.updateState();
}
});
// listen to humidity events too, and pass those along
this.sensor.listen(ScryptedInterface.Thermometer, (s, d, data) => {
if (d.property === ScryptedInterfaceProperty.humidity) {
this.humidity = this.sensor.humidity;
}
});
// Watch for on/off events, some of them may be physical
// button presses, and those will need to be resolved by
// checking the state versus the event.
this.heater?.listen(ScryptedInterface.OnOff, (s, d, data) => {
this.manageEvent(this.heater.on, 'Heating');
})
this.cooler?.listen(ScryptedInterface.OnOff, (s, d, data) => {
this.manageEvent(this.cooler.on, 'Cooling');
})
}
getSettings(): Promise<Setting[]> {
return this.storageSettings.getSettings();
}
putSetting(key: string, value: SettingValue): Promise<void> {
return this.storageSettings.putSetting(key, value);
}
// whenever the temperature changes, or a new command is sent, this updates the current state accordingly.
updateState() {
const threshold = 2;
const thermostatMode = this.thermostatMode || ThermostatMode.Off;
if (!thermostatMode) {
this.console.error('thermostat mode not set');
return;
}
// this holds the last known state of the thermostat.
// ie, what it decided to do, the last time it updated its state.
const thermostatState = this.storage.getItem('thermostatState');
// set the state before turning any devices on or off.
// on/off events will need to be resolved by looking at the state to
// determine if it is manual user input.
const setState = (state: string) => {
if (state == thermostatState) {
// this.console.log('Thermostat state unchanged. ' + state)
return;
}
this.console.log('Thermostat state changed. ' + state);
this.storage.setItem('thermostatState', state);
}
const manageSetpoint = (temperatureDifference: number, er: OnOff & ScryptedDevice, other: OnOff & ScryptedDevice, ing: string, ed: string) => {
if (!er) {
this.console.error('Thermostat mode set to ' + thermostatMode + ', but ' + thermostatMode + 'er variable is not defined.');
return;
}
// turn off the other one. if heating, turn off cooler. if cooling, turn off heater.
if (other && other.on) {
other.turnOff();
}
if (temperatureDifference < 0) {
setState(ed);
if (er.on) {
er.turnOff();
}
return;
}
// start cooling/heating if way over threshold, or if it is not in the cooling/heating state
if (temperatureDifference > threshold || thermostatState != ing) {
setState(ing);
if (!er.on) {
er.turnOn();
}
return;
}
setState(ed);
if (er.on) {
er.turnOff();
}
}
const allOff = () => {
if (this.heater && this.heater.on) {
this.heater.turnOff();
}
if (this.cooler && this.cooler.on) {
this.cooler.turnOff();
}
}
if (thermostatMode == 'Off') {
setState('Off');
allOff();
return;
} else if (thermostatMode == 'Cool') {
let thermostatSetpoint = this.thermostatSetpoint || this.sensor.temperature;
if (!thermostatSetpoint) {
this.console.error('No thermostat setpoint is defined.');
return;
}
const temperatureDifference = this.sensor.temperature - thermostatSetpoint;
manageSetpoint(temperatureDifference, this.cooler, this.heater, 'Cooling', 'Cooled');
return;
} else if (thermostatMode == 'Heat') {
let thermostatSetpoint = this.thermostatSetpoint || this.sensor.temperature;
if (!thermostatSetpoint) {
this.console.error('No thermostat setpoint is defined.');
return;
}
const temperatureDifference = thermostatSetpoint - this.sensor.temperature;
manageSetpoint(temperatureDifference, this.heater, this.cooler, 'Heating', 'Heated');
return;
} else if (thermostatMode == 'HeatCool') {
const temperature = this.sensor.temperature;
const thermostatSetpointLow = this.thermostatSetpointLow || this.sensor.temperature;
const thermostatSetpointHigh = this.thermostatSetpointHigh || this.sensor.temperature;
if (!thermostatSetpointLow || !thermostatSetpointHigh) {
this.console.error('No thermostat setpoint low/high is defined.');
return;
}
// see if this is within HeatCool tolerance. This prevents immediately cooling after heating all the way to the high setpoint.
if ((thermostatState == 'HeatCooled' || thermostatState == 'Heated' || thermostatState == 'Cooled')
&& temperature > thermostatSetpointLow - threshold
&& temperature < thermostatSetpointHigh + threshold) {
// normalize the state into HeatCooled
setState('HeatCooled');
allOff();
return;
}
// if already heating or cooling or way out of tolerance, continue doing it until state changes.
if (temperature < thermostatSetpointLow || thermostatState == 'Heating') {
const temperatureDifference = thermostatSetpointHigh - temperature;
manageSetpoint(temperatureDifference, this.heater, null, 'Heating', 'Heated');
return;
} else if (temperature > thermostatSetpointHigh || thermostatState == 'Cooling') {
const temperatureDifference = temperature - thermostatSetpointLow;
manageSetpoint(temperatureDifference, this.cooler, null, 'Cooling', 'Cooled');
return;
}
// temperature is within tolerance, so this is now HeatCooled
setState('HeatCooled');
allOff();
return;
}
this.console.error('Unknown mode ' + thermostatMode);
}
// implementation of TemperatureSetting
async setThermostatSetpoint(thermostatSetpoint: number) {
this.console.log('thermostatSetpoint changed ' + thermostatSetpoint);
this.thermostatSetpoint = thermostatSetpoint;
this.updateState();
}
async setThermostatSetpointLow(thermostatSetpointLow: number) {
this.console.log('thermostatSetpointLow changed ' + thermostatSetpointLow);
this.thermostatSetpointLow = thermostatSetpointLow;
this.updateState();
}
async setThermostatSetpointHigh(thermostatSetpointHigh: number) {
this.console.log('thermostatSetpointHigh changed ' + thermostatSetpointHigh);
this.thermostatSetpointHigh = thermostatSetpointHigh;
this.updateState();
}
async setThermostatMode(mode: ThermostatMode) {
this.console.log('thermostat mode set to ' + mode);
if (mode === ThermostatMode.On || mode == ThermostatMode.Auto) {
mode = this.storage.getItem("lastThermostatMode") as ThermostatMode;
}
else if (mode != ThermostatMode.Off) {
this.storage.setItem("lastThermostatMode", mode);
}
this.thermostatMode = mode;
this.updateState();
}
// end implementation of TemperatureSetting
// If the heater or cooler gets turned on or off manually (or programatically),
// make this resolve with the current state. This relies on the state being set
// before any devices are turned on or off (as mentioned above) to avoid race
// conditions.
manageEvent(on: boolean, ing: string) {
const state = this.storage.getItem('thermostatState');
if (on) {
// on implies it must be heating/cooling
if (state != ing) {
// should this be Heat/Cool?
this.setThermostatMode(ThermostatMode.On);
return;
}
return;
}
// off implies that it must NOT be heating/cooling
if (state == ing) {
this.setThermostatMode(ThermostatMode.Off);
return;
}
}
}
export default new ThermostatDevice(); | the_stack |
import {
Agile,
CallbackSubscriptionContainer,
ComponentSubscriptionContainer,
Observer,
SubController,
} from '../../../../src';
import * as Utils from '@agile-ts/utils';
import { LogMock } from '../../../helper/logMock';
describe('SubController Tests', () => {
let dummyAgile: Agile;
beforeEach(() => {
LogMock.mockLogs();
dummyAgile = new Agile();
jest.clearAllMocks();
});
it('should create SubController', () => {
const subController = new SubController(dummyAgile);
expect(subController.agileInstance()).toBe(dummyAgile);
expect(Array.from(subController.callbackSubs)).toStrictEqual([]);
expect(Array.from(subController.componentSubs)).toStrictEqual([]);
});
describe('SubController Function Tests', () => {
let subController: SubController;
let dummyObserver1: Observer;
let dummyObserver2: Observer;
beforeEach(() => {
dummyObserver1 = new Observer(dummyAgile, {
key: 'dummyObserver1',
value: 'dummyObserver1Value',
});
dummyObserver2 = new Observer(dummyAgile, {
key: 'dummyObserver2',
value: 'dummyObserver2Value',
});
subController = new SubController(dummyAgile);
});
describe('subscribe function tests', () => {
beforeEach(() => {
jest.spyOn(subController, 'createCallbackSubscriptionContainer');
jest.spyOn(subController, 'createComponentSubscriptionContainer');
});
it(
'should create a Component based Subscription Container with specified Component Instance ' +
'and assign the in an object specified Observers to it',
() => {
dummyAgile.config.waitForMount = 'aFakeBoolean' as any;
const dummyIntegration: any = {
dummy: 'integration',
};
const returnValue = subController.subscribe(
dummyIntegration,
{ observer1: dummyObserver1, observer2: dummyObserver2 },
{
key: 'subscriptionContainerKey',
componentId: 'testID',
waitForMount: true,
}
);
expect(returnValue.subscriptionContainer).toBeInstanceOf(
ComponentSubscriptionContainer
);
expect(returnValue.props).toStrictEqual({
observer1: dummyObserver1.value,
observer2: dummyObserver2.value,
});
expect(
subController.createComponentSubscriptionContainer
).toHaveBeenCalledWith(
dummyIntegration,
{ observer1: dummyObserver1, observer2: dummyObserver2 },
{
key: 'subscriptionContainerKey',
componentId: 'testID',
waitForMount: true,
}
);
expect(
subController.createCallbackSubscriptionContainer
).not.toHaveBeenCalled();
}
);
it(
'should create a Component based Subscription Container with specified Component Instance ' +
'and assign the in an array specified Observers to it',
() => {
dummyAgile.config.waitForMount = 'aFakeBoolean' as any;
const dummyIntegration: any = {
dummy: 'integration',
};
const returnValue = subController.subscribe(
dummyIntegration,
[dummyObserver1, dummyObserver2],
{ key: 'subscriptionContainerKey', componentId: 'testID' }
);
expect(returnValue).toBeInstanceOf(ComponentSubscriptionContainer);
expect(
subController.createComponentSubscriptionContainer
).toHaveBeenCalledWith(
dummyIntegration,
[dummyObserver1, dummyObserver2],
{
key: 'subscriptionContainerKey',
componentId: 'testID',
waitForMount: 'aFakeBoolean',
}
);
expect(
subController.createCallbackSubscriptionContainer
).not.toHaveBeenCalled();
}
);
it(
'should create a Callback based Subscription Container with specified callback function ' +
'and assign the in an object specified Observers to it',
() => {
dummyAgile.config.waitForMount = 'aFakeBoolean' as any;
const dummyIntegration = () => {
/* empty function */
};
const returnValue = subController.subscribe(
dummyIntegration,
{ observer1: dummyObserver1, observer2: dummyObserver2 },
{
key: 'subscriptionContainerKey',
componentId: 'testID',
}
);
expect(returnValue.subscriptionContainer).toBeInstanceOf(
CallbackSubscriptionContainer
);
expect(returnValue.props).toStrictEqual({
observer1: dummyObserver1.value,
observer2: dummyObserver2.value,
});
expect(
subController.createCallbackSubscriptionContainer
).toHaveBeenCalledWith(
dummyIntegration,
{ observer1: dummyObserver1, observer2: dummyObserver2 },
{
key: 'subscriptionContainerKey',
componentId: 'testID',
waitForMount: 'aFakeBoolean',
}
);
expect(
subController.createComponentSubscriptionContainer
).not.toHaveBeenCalled();
}
);
it(
'should create a Callback based Subscription Container with specified callback function ' +
'and assign the in an array specified Observers to it',
() => {
dummyAgile.config.waitForMount = 'aFakeBoolean' as any;
const dummyIntegration = () => {
/* empty function */
};
const returnValue = subController.subscribe(
dummyIntegration,
[dummyObserver1, dummyObserver2],
{
key: 'subscriptionContainerKey',
componentId: 'testID',
waitForMount: false,
}
);
expect(returnValue).toBeInstanceOf(CallbackSubscriptionContainer);
expect(
subController.createCallbackSubscriptionContainer
).toHaveBeenCalledWith(
dummyIntegration,
[dummyObserver1, dummyObserver2],
{
key: 'subscriptionContainerKey',
componentId: 'testID',
waitForMount: false,
}
);
expect(
subController.createComponentSubscriptionContainer
).not.toHaveBeenCalled();
}
);
});
describe('unsubscribe function tests', () => {
it('should unsubscribe Callback based Subscription Container', () => {
const dummyIntegration = () => {
/* empty function */
};
const callbackSubscriptionContainer =
subController.createCallbackSubscriptionContainer(dummyIntegration, [
dummyObserver1,
dummyObserver2,
]);
callbackSubscriptionContainer.removeSubscription = jest.fn();
subController.unsubscribe(callbackSubscriptionContainer);
expect(Array.from(subController.callbackSubs)).toStrictEqual([]);
expect(callbackSubscriptionContainer.ready).toBeFalsy();
expect(
callbackSubscriptionContainer.removeSubscription
).toHaveBeenCalledTimes(2);
expect(
callbackSubscriptionContainer.removeSubscription
).toHaveBeenCalledWith(dummyObserver1);
expect(
callbackSubscriptionContainer.removeSubscription
).toHaveBeenCalledWith(dummyObserver2);
});
it('should unsubscribe Component Subscription Container', () => {
const dummyIntegration: any = {
dummy: 'integration',
};
const componentSubscriptionContainer =
subController.createComponentSubscriptionContainer(dummyIntegration, [
dummyObserver1,
dummyObserver2,
]);
componentSubscriptionContainer.removeSubscription = jest.fn();
subController.unsubscribe(componentSubscriptionContainer);
expect(Array.from(subController.componentSubs)).toStrictEqual([]);
expect(componentSubscriptionContainer.ready).toBeFalsy();
expect(
componentSubscriptionContainer.removeSubscription
).toHaveBeenCalledTimes(2);
expect(
componentSubscriptionContainer.removeSubscription
).toHaveBeenCalledWith(dummyObserver1);
expect(
componentSubscriptionContainer.removeSubscription
).toHaveBeenCalledWith(dummyObserver2);
});
it(
'should unsubscribe Component based Subscription Container ' +
'from specified object (UI-Component) that contains an instance of the Component Subscription Container',
() => {
const dummyIntegration: any = {
dummy: 'integration',
componentSubscriptionContainers: [],
};
const componentSubscriptionContainer =
subController.createComponentSubscriptionContainer(
dummyIntegration,
[dummyObserver1, dummyObserver2]
);
componentSubscriptionContainer.removeSubscription = jest.fn();
const componentSubscriptionContainer2 =
subController.createComponentSubscriptionContainer(
dummyIntegration,
[dummyObserver1, dummyObserver2]
);
componentSubscriptionContainer2.removeSubscription = jest.fn();
subController.unsubscribe(dummyIntegration);
expect(Array.from(subController.componentSubs)).toStrictEqual([]);
expect(componentSubscriptionContainer.ready).toBeFalsy();
expect(
componentSubscriptionContainer.removeSubscription
).toHaveBeenCalledTimes(2);
expect(
componentSubscriptionContainer.removeSubscription
).toHaveBeenCalledWith(dummyObserver1);
expect(
componentSubscriptionContainer.removeSubscription
).toHaveBeenCalledWith(dummyObserver2);
expect(componentSubscriptionContainer2.ready).toBeFalsy();
expect(
componentSubscriptionContainer2.removeSubscription
).toHaveBeenCalledTimes(2);
expect(
componentSubscriptionContainer2.removeSubscription
).toHaveBeenCalledWith(dummyObserver1);
expect(
componentSubscriptionContainer2.removeSubscription
).toHaveBeenCalledWith(dummyObserver2);
}
);
});
describe('createComponentSubscriptionContainer function tests', () => {
it(
'should return ready Component based Subscription Container ' +
"and add an instance of it to the not existing 'componentSubscriptions' property " +
'in the dummyIntegration (default config)',
() => {
jest.spyOn(Utils, 'generateId').mockReturnValueOnce('generatedKey');
const dummyIntegration: any = {
dummy: 'integration',
};
const componentSubscriptionContainer =
subController.createComponentSubscriptionContainer(
dummyIntegration,
[dummyObserver1, dummyObserver2],
{ waitForMount: false }
);
expect(componentSubscriptionContainer).toBeInstanceOf(
ComponentSubscriptionContainer
);
expect(componentSubscriptionContainer.component).toStrictEqual(
dummyIntegration
);
expect(componentSubscriptionContainer.ready).toBeTruthy();
expect(Array.from(subController.componentSubs)).toStrictEqual([
componentSubscriptionContainer,
]);
expect(
dummyIntegration.componentSubscriptionContainers
).toStrictEqual([componentSubscriptionContainer]);
// Check if ComponentSubscriptionContainer was called with correct parameters
expect(componentSubscriptionContainer.key).toBe('generatedKey');
expect(componentSubscriptionContainer.componentId).toBeUndefined();
expect(
Array.from(componentSubscriptionContainer.subscribers)
).toStrictEqual([dummyObserver1, dummyObserver2]);
}
);
it(
'should return ready Component based Subscription Container ' +
"and add an instance of it to the existing 'componentSubscriptions' property " +
'in the dummyIntegration (default config)',
() => {
jest.spyOn(Utils, 'generateId').mockReturnValueOnce('generatedKey');
const dummyIntegration: any = {
dummy: 'integration',
componentSubscriptionContainers: [],
};
const componentSubscriptionContainer =
subController.createComponentSubscriptionContainer(
dummyIntegration,
[dummyObserver1, dummyObserver2],
{ waitForMount: false }
);
expect(
dummyIntegration.componentSubscriptionContainers
).toStrictEqual([componentSubscriptionContainer]);
}
);
it(
'should return ready Component based Subscription Container ' +
"and add an instance of it to the not existing 'componentSubscriptions' property " +
'in the dummyIntegration (specific config)',
() => {
const dummyIntegration: any = {
dummy: 'integration',
};
const componentSubscriptionContainer =
subController.createComponentSubscriptionContainer(
dummyIntegration,
[dummyObserver1, dummyObserver2],
{ waitForMount: false, componentId: 'testID', key: 'dummyKey' }
);
expect(componentSubscriptionContainer).toBeInstanceOf(
ComponentSubscriptionContainer
);
expect(componentSubscriptionContainer.component).toStrictEqual(
dummyIntegration
);
expect(componentSubscriptionContainer.ready).toBeTruthy();
expect(Array.from(subController.componentSubs)).toStrictEqual([
componentSubscriptionContainer,
]);
expect(
dummyIntegration.componentSubscriptionContainers
).toStrictEqual([componentSubscriptionContainer]);
// Check if ComponentSubscriptionContainer was called with correct parameters
expect(componentSubscriptionContainer.key).toBe('dummyKey');
expect(componentSubscriptionContainer.componentId).toBe('testID');
expect(
Array.from(componentSubscriptionContainer.subscribers)
).toStrictEqual([dummyObserver1, dummyObserver2]);
}
);
it("should return not ready Component based Subscription Container if componentInstance isn't mounted (config.waitForMount = true)", () => {
jest.spyOn(Utils, 'generateId').mockReturnValueOnce('generatedKey');
const dummyIntegration: any = {
dummy: 'integration',
};
const componentSubscriptionContainer =
subController.createComponentSubscriptionContainer(
dummyIntegration,
[dummyObserver1, dummyObserver2],
{ waitForMount: true }
);
expect(componentSubscriptionContainer).toBeInstanceOf(
ComponentSubscriptionContainer
);
expect(componentSubscriptionContainer.component).toStrictEqual(
dummyIntegration
);
expect(componentSubscriptionContainer.ready).toBeFalsy();
expect(Array.from(subController.componentSubs)).toStrictEqual([
componentSubscriptionContainer,
]);
// Check if ComponentSubscriptionContainer was called with correct parameters
expect(componentSubscriptionContainer.key).toBe('generatedKey');
expect(componentSubscriptionContainer.componentId).toBeUndefined();
expect(
Array.from(componentSubscriptionContainer.subscribers)
).toStrictEqual([dummyObserver1, dummyObserver2]);
});
it('should return ready Component based Subscription Container if componentInstance is mounted (config.waitForMount = true)', () => {
jest.spyOn(Utils, 'generateId').mockReturnValueOnce('generatedKey');
const dummyIntegration: any = {
dummy: 'integration',
};
subController.mount(dummyIntegration);
const componentSubscriptionContainer =
subController.createComponentSubscriptionContainer(
dummyIntegration,
[dummyObserver1, dummyObserver2],
{ waitForMount: true }
);
expect(componentSubscriptionContainer).toBeInstanceOf(
ComponentSubscriptionContainer
);
expect(componentSubscriptionContainer.component).toStrictEqual(
dummyIntegration
);
expect(componentSubscriptionContainer.ready).toBeTruthy();
expect(Array.from(subController.componentSubs)).toStrictEqual([
componentSubscriptionContainer,
]);
// Check if ComponentSubscriptionContainer was called with correct parameters
expect(componentSubscriptionContainer.key).toBe('generatedKey');
expect(componentSubscriptionContainer.componentId).toBeUndefined();
expect(
Array.from(componentSubscriptionContainer.subscribers)
).toStrictEqual([dummyObserver1, dummyObserver2]);
});
});
describe('registerCallbackSubscription function tests', () => {
it('should return Callback based Subscription Container (default config)', () => {
jest.spyOn(Utils, 'generateId').mockReturnValueOnce('generatedKey');
const dummyIntegration = () => {
/* empty function */
};
const callbackSubscriptionContainer =
subController.createCallbackSubscriptionContainer(dummyIntegration, [
dummyObserver1,
dummyObserver2,
]);
expect(callbackSubscriptionContainer).toBeInstanceOf(
CallbackSubscriptionContainer
);
expect(callbackSubscriptionContainer.callback).toBe(dummyIntegration);
expect(callbackSubscriptionContainer.ready).toBeTruthy();
expect(Array.from(subController.callbackSubs)).toStrictEqual([
callbackSubscriptionContainer,
]);
// TODO find a way to spy on a class constructor without overwriting it.
// https://stackoverflow.com/questions/48219267/how-to-spy-on-a-class-constructor-jest/48486214
// Because the below tests are not really related to this test.
// They are checking if the CallbackSubscriptionContainer was called with the correct parameters
// by checking if the CallbackSubscriptionContainer has correctly set properties.
// Note: This 'issue' happens in multiple parts of the AgileTs test!
expect(callbackSubscriptionContainer.key).toBe('generatedKey');
expect(callbackSubscriptionContainer.componentId).toBeUndefined();
expect(
Array.from(callbackSubscriptionContainer.subscribers)
).toStrictEqual([dummyObserver1, dummyObserver2]);
});
it('should return Callback based Subscription Container (specific config)', () => {
const dummyIntegration = () => {
/* empty function */
};
const callbackSubscriptionContainer =
subController.createCallbackSubscriptionContainer(
dummyIntegration,
[dummyObserver1, dummyObserver2],
{
waitForMount: false,
componentId: 'testID',
key: 'dummyKey',
}
);
expect(callbackSubscriptionContainer).toBeInstanceOf(
CallbackSubscriptionContainer
);
expect(callbackSubscriptionContainer.callback).toBe(dummyIntegration);
expect(callbackSubscriptionContainer.ready).toBeTruthy();
expect(Array.from(subController.callbackSubs)).toStrictEqual([
callbackSubscriptionContainer,
]);
// Check if CallbackSubscriptionContainer was called with correct parameters
expect(callbackSubscriptionContainer.key).toBe('dummyKey');
expect(callbackSubscriptionContainer.componentId).toBe('testID');
expect(
Array.from(callbackSubscriptionContainer.subscribers)
).toStrictEqual([dummyObserver1, dummyObserver2]);
});
});
describe('mount function tests', () => {
const dummyIntegration: any = {
dummy: 'integration',
};
let componentSubscriptionContainer: ComponentSubscriptionContainer;
beforeEach(() => {
dummyAgile.config.waitForMount = true;
componentSubscriptionContainer =
subController.createComponentSubscriptionContainer(dummyIntegration, [
dummyObserver1,
dummyObserver2,
]);
});
it(
"should add specified 'componentInstance' to the 'mountedComponents' " +
'and set the Subscription Container representing the mounted Component to ready',
() => {
subController.mount(dummyIntegration);
expect(componentSubscriptionContainer.ready).toBeTruthy();
expect(Array.from(subController.mountedComponents)).toStrictEqual([
dummyIntegration,
]);
}
);
});
describe('unmount function tests', () => {
const dummyIntegration: any = {
dummy: 'integration',
};
let componentSubscriptionContainer: ComponentSubscriptionContainer;
beforeEach(() => {
dummyAgile.config.waitForMount = true;
componentSubscriptionContainer =
subController.createComponentSubscriptionContainer(dummyIntegration, [
dummyObserver1,
dummyObserver2,
]);
subController.mount(dummyIntegration);
});
it(
"should remove specified 'componentInstance' to the 'mountedComponents' " +
'and set the Subscription Container representing the mounted Component to not ready',
() => {
subController.unmount(dummyIntegration);
expect(componentSubscriptionContainer.ready).toBeFalsy();
expect(Array.from(subController.mountedComponents)).toStrictEqual([]);
}
);
});
});
}); | the_stack |
import * as Long from "long";
import {protobuf as $protobuf} from "../../../../src";
/** Namespace google. */
export namespace google {
/** Namespace showcase. */
namespace showcase {
/** Namespace v1beta1. */
namespace v1beta1 {
/** Represents an Echo */
class Echo extends $protobuf.rpc.Service {
/**
* Constructs a new Echo service.
* @param rpcImpl RPC implementation
* @param [requestDelimited=false] Whether requests are length-delimited
* @param [responseDelimited=false] Whether responses are length-delimited
*/
constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean);
/**
* Creates new Echo service using the specified rpc implementation.
* @param rpcImpl RPC implementation
* @param [requestDelimited=false] Whether requests are length-delimited
* @param [responseDelimited=false] Whether responses are length-delimited
* @returns RPC service. Useful where requests and/or responses are streamed.
*/
public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Echo;
/**
* Calls Echo.
* @param request EchoRequest message or plain object
* @param callback Node-style callback called with the error, if any, and EchoResponse
*/
public echo(request: google.showcase.v1beta1.IEchoRequest, callback: google.showcase.v1beta1.Echo.EchoCallback): void;
/**
* Calls Echo.
* @param request EchoRequest message or plain object
* @returns Promise
*/
public echo(request: google.showcase.v1beta1.IEchoRequest): Promise<google.showcase.v1beta1.EchoResponse>;
/**
* Calls Expand.
* @param request ExpandRequest message or plain object
* @param callback Node-style callback called with the error, if any, and EchoResponse
*/
public expand(request: google.showcase.v1beta1.IExpandRequest, callback: google.showcase.v1beta1.Echo.ExpandCallback): void;
/**
* Calls Expand.
* @param request ExpandRequest message or plain object
* @returns Promise
*/
public expand(request: google.showcase.v1beta1.IExpandRequest): Promise<google.showcase.v1beta1.EchoResponse>;
/**
* Calls Collect.
* @param request EchoRequest message or plain object
* @param callback Node-style callback called with the error, if any, and EchoResponse
*/
public collect(request: google.showcase.v1beta1.IEchoRequest, callback: google.showcase.v1beta1.Echo.CollectCallback): void;
/**
* Calls Collect.
* @param request EchoRequest message or plain object
* @returns Promise
*/
public collect(request: google.showcase.v1beta1.IEchoRequest): Promise<google.showcase.v1beta1.EchoResponse>;
/**
* Calls Chat.
* @param request EchoRequest message or plain object
* @param callback Node-style callback called with the error, if any, and EchoResponse
*/
public chat(request: google.showcase.v1beta1.IEchoRequest, callback: google.showcase.v1beta1.Echo.ChatCallback): void;
/**
* Calls Chat.
* @param request EchoRequest message or plain object
* @returns Promise
*/
public chat(request: google.showcase.v1beta1.IEchoRequest): Promise<google.showcase.v1beta1.EchoResponse>;
/**
* Calls PagedExpand.
* @param request PagedExpandRequest message or plain object
* @param callback Node-style callback called with the error, if any, and PagedExpandResponse
*/
public pagedExpand(request: google.showcase.v1beta1.IPagedExpandRequest, callback: google.showcase.v1beta1.Echo.PagedExpandCallback): void;
/**
* Calls PagedExpand.
* @param request PagedExpandRequest message or plain object
* @returns Promise
*/
public pagedExpand(request: google.showcase.v1beta1.IPagedExpandRequest): Promise<google.showcase.v1beta1.PagedExpandResponse>;
/**
* Calls Wait.
* @param request WaitRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Operation
*/
public wait(request: google.showcase.v1beta1.IWaitRequest, callback: google.showcase.v1beta1.Echo.WaitCallback): void;
/**
* Calls Wait.
* @param request WaitRequest message or plain object
* @returns Promise
*/
public wait(request: google.showcase.v1beta1.IWaitRequest): Promise<google.longrunning.Operation>;
/**
* Calls Block.
* @param request BlockRequest message or plain object
* @param callback Node-style callback called with the error, if any, and BlockResponse
*/
public block(request: google.showcase.v1beta1.IBlockRequest, callback: google.showcase.v1beta1.Echo.BlockCallback): void;
/**
* Calls Block.
* @param request BlockRequest message or plain object
* @returns Promise
*/
public block(request: google.showcase.v1beta1.IBlockRequest): Promise<google.showcase.v1beta1.BlockResponse>;
}
namespace Echo {
/**
* Callback as used by {@link google.showcase.v1beta1.Echo#echo}.
* @param error Error, if any
* @param [response] EchoResponse
*/
type EchoCallback = (error: (Error|null), response?: google.showcase.v1beta1.EchoResponse) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Echo#expand}.
* @param error Error, if any
* @param [response] EchoResponse
*/
type ExpandCallback = (error: (Error|null), response?: google.showcase.v1beta1.EchoResponse) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Echo#collect}.
* @param error Error, if any
* @param [response] EchoResponse
*/
type CollectCallback = (error: (Error|null), response?: google.showcase.v1beta1.EchoResponse) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Echo#chat}.
* @param error Error, if any
* @param [response] EchoResponse
*/
type ChatCallback = (error: (Error|null), response?: google.showcase.v1beta1.EchoResponse) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Echo#pagedExpand}.
* @param error Error, if any
* @param [response] PagedExpandResponse
*/
type PagedExpandCallback = (error: (Error|null), response?: google.showcase.v1beta1.PagedExpandResponse) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Echo#wait}.
* @param error Error, if any
* @param [response] Operation
*/
type WaitCallback = (error: (Error|null), response?: google.longrunning.Operation) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Echo#block}.
* @param error Error, if any
* @param [response] BlockResponse
*/
type BlockCallback = (error: (Error|null), response?: google.showcase.v1beta1.BlockResponse) => void;
}
/** Properties of an EchoRequest. */
interface IEchoRequest {
/** EchoRequest content */
content?: (string|null);
/** EchoRequest error */
error?: (google.rpc.IStatus|null);
}
/** Represents an EchoRequest. */
class EchoRequest implements IEchoRequest {
/**
* Constructs a new EchoRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IEchoRequest);
/** EchoRequest content. */
public content?: (string|null);
/** EchoRequest error. */
public error?: (google.rpc.IStatus|null);
/** EchoRequest response. */
public response?: ("content"|"error");
/**
* Creates a new EchoRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns EchoRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IEchoRequest): google.showcase.v1beta1.EchoRequest;
/**
* Encodes the specified EchoRequest message. Does not implicitly {@link google.showcase.v1beta1.EchoRequest.verify|verify} messages.
* @param message EchoRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IEchoRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified EchoRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.EchoRequest.verify|verify} messages.
* @param message EchoRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IEchoRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an EchoRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns EchoRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.EchoRequest;
/**
* Decodes an EchoRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns EchoRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.EchoRequest;
/**
* Verifies an EchoRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an EchoRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns EchoRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.EchoRequest;
/**
* Creates a plain object from an EchoRequest message. Also converts values to other types if specified.
* @param message EchoRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.EchoRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this EchoRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an EchoResponse. */
interface IEchoResponse {
/** EchoResponse content */
content?: (string|null);
}
/** Represents an EchoResponse. */
class EchoResponse implements IEchoResponse {
/**
* Constructs a new EchoResponse.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IEchoResponse);
/** EchoResponse content. */
public content: string;
/**
* Creates a new EchoResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns EchoResponse instance
*/
public static create(properties?: google.showcase.v1beta1.IEchoResponse): google.showcase.v1beta1.EchoResponse;
/**
* Encodes the specified EchoResponse message. Does not implicitly {@link google.showcase.v1beta1.EchoResponse.verify|verify} messages.
* @param message EchoResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IEchoResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified EchoResponse message, length delimited. Does not implicitly {@link google.showcase.v1beta1.EchoResponse.verify|verify} messages.
* @param message EchoResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IEchoResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an EchoResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns EchoResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.EchoResponse;
/**
* Decodes an EchoResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns EchoResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.EchoResponse;
/**
* Verifies an EchoResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an EchoResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns EchoResponse
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.EchoResponse;
/**
* Creates a plain object from an EchoResponse message. Also converts values to other types if specified.
* @param message EchoResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.EchoResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this EchoResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an ExpandRequest. */
interface IExpandRequest {
/** ExpandRequest content */
content?: (string|null);
/** ExpandRequest error */
error?: (google.rpc.IStatus|null);
}
/** Represents an ExpandRequest. */
class ExpandRequest implements IExpandRequest {
/**
* Constructs a new ExpandRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IExpandRequest);
/** ExpandRequest content. */
public content: string;
/** ExpandRequest error. */
public error?: (google.rpc.IStatus|null);
/**
* Creates a new ExpandRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ExpandRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IExpandRequest): google.showcase.v1beta1.ExpandRequest;
/**
* Encodes the specified ExpandRequest message. Does not implicitly {@link google.showcase.v1beta1.ExpandRequest.verify|verify} messages.
* @param message ExpandRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IExpandRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ExpandRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.ExpandRequest.verify|verify} messages.
* @param message ExpandRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IExpandRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ExpandRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ExpandRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.ExpandRequest;
/**
* Decodes an ExpandRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ExpandRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.ExpandRequest;
/**
* Verifies an ExpandRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ExpandRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ExpandRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.ExpandRequest;
/**
* Creates a plain object from an ExpandRequest message. Also converts values to other types if specified.
* @param message ExpandRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.ExpandRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ExpandRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PagedExpandRequest. */
interface IPagedExpandRequest {
/** PagedExpandRequest content */
content?: (string|null);
/** PagedExpandRequest pageSize */
pageSize?: (number|null);
/** PagedExpandRequest pageToken */
pageToken?: (string|null);
}
/** Represents a PagedExpandRequest. */
class PagedExpandRequest implements IPagedExpandRequest {
/**
* Constructs a new PagedExpandRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IPagedExpandRequest);
/** PagedExpandRequest content. */
public content: string;
/** PagedExpandRequest pageSize. */
public pageSize: number;
/** PagedExpandRequest pageToken. */
public pageToken: string;
/**
* Creates a new PagedExpandRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns PagedExpandRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IPagedExpandRequest): google.showcase.v1beta1.PagedExpandRequest;
/**
* Encodes the specified PagedExpandRequest message. Does not implicitly {@link google.showcase.v1beta1.PagedExpandRequest.verify|verify} messages.
* @param message PagedExpandRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IPagedExpandRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PagedExpandRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.PagedExpandRequest.verify|verify} messages.
* @param message PagedExpandRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IPagedExpandRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PagedExpandRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PagedExpandRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.PagedExpandRequest;
/**
* Decodes a PagedExpandRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PagedExpandRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.PagedExpandRequest;
/**
* Verifies a PagedExpandRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PagedExpandRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PagedExpandRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.PagedExpandRequest;
/**
* Creates a plain object from a PagedExpandRequest message. Also converts values to other types if specified.
* @param message PagedExpandRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.PagedExpandRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PagedExpandRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PagedExpandResponse. */
interface IPagedExpandResponse {
/** PagedExpandResponse responses */
responses?: (google.showcase.v1beta1.IEchoResponse[]|null);
/** PagedExpandResponse nextPageToken */
nextPageToken?: (string|null);
}
/** Represents a PagedExpandResponse. */
class PagedExpandResponse implements IPagedExpandResponse {
/**
* Constructs a new PagedExpandResponse.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IPagedExpandResponse);
/** PagedExpandResponse responses. */
public responses: google.showcase.v1beta1.IEchoResponse[];
/** PagedExpandResponse nextPageToken. */
public nextPageToken: string;
/**
* Creates a new PagedExpandResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns PagedExpandResponse instance
*/
public static create(properties?: google.showcase.v1beta1.IPagedExpandResponse): google.showcase.v1beta1.PagedExpandResponse;
/**
* Encodes the specified PagedExpandResponse message. Does not implicitly {@link google.showcase.v1beta1.PagedExpandResponse.verify|verify} messages.
* @param message PagedExpandResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IPagedExpandResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PagedExpandResponse message, length delimited. Does not implicitly {@link google.showcase.v1beta1.PagedExpandResponse.verify|verify} messages.
* @param message PagedExpandResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IPagedExpandResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PagedExpandResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PagedExpandResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.PagedExpandResponse;
/**
* Decodes a PagedExpandResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PagedExpandResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.PagedExpandResponse;
/**
* Verifies a PagedExpandResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PagedExpandResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PagedExpandResponse
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.PagedExpandResponse;
/**
* Creates a plain object from a PagedExpandResponse message. Also converts values to other types if specified.
* @param message PagedExpandResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.PagedExpandResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PagedExpandResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a WaitRequest. */
interface IWaitRequest {
/** WaitRequest endTime */
endTime?: (google.protobuf.ITimestamp|null);
/** WaitRequest ttl */
ttl?: (google.protobuf.IDuration|null);
/** WaitRequest error */
error?: (google.rpc.IStatus|null);
/** WaitRequest success */
success?: (google.showcase.v1beta1.IWaitResponse|null);
}
/** Represents a WaitRequest. */
class WaitRequest implements IWaitRequest {
/**
* Constructs a new WaitRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IWaitRequest);
/** WaitRequest endTime. */
public endTime?: (google.protobuf.ITimestamp|null);
/** WaitRequest ttl. */
public ttl?: (google.protobuf.IDuration|null);
/** WaitRequest error. */
public error?: (google.rpc.IStatus|null);
/** WaitRequest success. */
public success?: (google.showcase.v1beta1.IWaitResponse|null);
/** WaitRequest end. */
public end?: ("endTime"|"ttl");
/** WaitRequest response. */
public response?: ("error"|"success");
/**
* Creates a new WaitRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns WaitRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IWaitRequest): google.showcase.v1beta1.WaitRequest;
/**
* Encodes the specified WaitRequest message. Does not implicitly {@link google.showcase.v1beta1.WaitRequest.verify|verify} messages.
* @param message WaitRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IWaitRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified WaitRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.WaitRequest.verify|verify} messages.
* @param message WaitRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IWaitRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a WaitRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns WaitRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.WaitRequest;
/**
* Decodes a WaitRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns WaitRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.WaitRequest;
/**
* Verifies a WaitRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a WaitRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns WaitRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.WaitRequest;
/**
* Creates a plain object from a WaitRequest message. Also converts values to other types if specified.
* @param message WaitRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.WaitRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this WaitRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a WaitResponse. */
interface IWaitResponse {
/** WaitResponse content */
content?: (string|null);
}
/** Represents a WaitResponse. */
class WaitResponse implements IWaitResponse {
/**
* Constructs a new WaitResponse.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IWaitResponse);
/** WaitResponse content. */
public content: string;
/**
* Creates a new WaitResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns WaitResponse instance
*/
public static create(properties?: google.showcase.v1beta1.IWaitResponse): google.showcase.v1beta1.WaitResponse;
/**
* Encodes the specified WaitResponse message. Does not implicitly {@link google.showcase.v1beta1.WaitResponse.verify|verify} messages.
* @param message WaitResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IWaitResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified WaitResponse message, length delimited. Does not implicitly {@link google.showcase.v1beta1.WaitResponse.verify|verify} messages.
* @param message WaitResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IWaitResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a WaitResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns WaitResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.WaitResponse;
/**
* Decodes a WaitResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns WaitResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.WaitResponse;
/**
* Verifies a WaitResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a WaitResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns WaitResponse
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.WaitResponse;
/**
* Creates a plain object from a WaitResponse message. Also converts values to other types if specified.
* @param message WaitResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.WaitResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this WaitResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a WaitMetadata. */
interface IWaitMetadata {
/** WaitMetadata endTime */
endTime?: (google.protobuf.ITimestamp|null);
}
/** Represents a WaitMetadata. */
class WaitMetadata implements IWaitMetadata {
/**
* Constructs a new WaitMetadata.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IWaitMetadata);
/** WaitMetadata endTime. */
public endTime?: (google.protobuf.ITimestamp|null);
/**
* Creates a new WaitMetadata instance using the specified properties.
* @param [properties] Properties to set
* @returns WaitMetadata instance
*/
public static create(properties?: google.showcase.v1beta1.IWaitMetadata): google.showcase.v1beta1.WaitMetadata;
/**
* Encodes the specified WaitMetadata message. Does not implicitly {@link google.showcase.v1beta1.WaitMetadata.verify|verify} messages.
* @param message WaitMetadata message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IWaitMetadata, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified WaitMetadata message, length delimited. Does not implicitly {@link google.showcase.v1beta1.WaitMetadata.verify|verify} messages.
* @param message WaitMetadata message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IWaitMetadata, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a WaitMetadata message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns WaitMetadata
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.WaitMetadata;
/**
* Decodes a WaitMetadata message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns WaitMetadata
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.WaitMetadata;
/**
* Verifies a WaitMetadata message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a WaitMetadata message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns WaitMetadata
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.WaitMetadata;
/**
* Creates a plain object from a WaitMetadata message. Also converts values to other types if specified.
* @param message WaitMetadata
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.WaitMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this WaitMetadata to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a BlockRequest. */
interface IBlockRequest {
/** BlockRequest responseDelay */
responseDelay?: (google.protobuf.IDuration|null);
/** BlockRequest error */
error?: (google.rpc.IStatus|null);
/** BlockRequest success */
success?: (google.showcase.v1beta1.IBlockResponse|null);
}
/** Represents a BlockRequest. */
class BlockRequest implements IBlockRequest {
/**
* Constructs a new BlockRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IBlockRequest);
/** BlockRequest responseDelay. */
public responseDelay?: (google.protobuf.IDuration|null);
/** BlockRequest error. */
public error?: (google.rpc.IStatus|null);
/** BlockRequest success. */
public success?: (google.showcase.v1beta1.IBlockResponse|null);
/** BlockRequest response. */
public response?: ("error"|"success");
/**
* Creates a new BlockRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns BlockRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IBlockRequest): google.showcase.v1beta1.BlockRequest;
/**
* Encodes the specified BlockRequest message. Does not implicitly {@link google.showcase.v1beta1.BlockRequest.verify|verify} messages.
* @param message BlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IBlockRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified BlockRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.BlockRequest.verify|verify} messages.
* @param message BlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IBlockRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a BlockRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns BlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.BlockRequest;
/**
* Decodes a BlockRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns BlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.BlockRequest;
/**
* Verifies a BlockRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a BlockRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns BlockRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.BlockRequest;
/**
* Creates a plain object from a BlockRequest message. Also converts values to other types if specified.
* @param message BlockRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.BlockRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this BlockRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a BlockResponse. */
interface IBlockResponse {
/** BlockResponse content */
content?: (string|null);
}
/** Represents a BlockResponse. */
class BlockResponse implements IBlockResponse {
/**
* Constructs a new BlockResponse.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IBlockResponse);
/** BlockResponse content. */
public content: string;
/**
* Creates a new BlockResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns BlockResponse instance
*/
public static create(properties?: google.showcase.v1beta1.IBlockResponse): google.showcase.v1beta1.BlockResponse;
/**
* Encodes the specified BlockResponse message. Does not implicitly {@link google.showcase.v1beta1.BlockResponse.verify|verify} messages.
* @param message BlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IBlockResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified BlockResponse message, length delimited. Does not implicitly {@link google.showcase.v1beta1.BlockResponse.verify|verify} messages.
* @param message BlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IBlockResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a BlockResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns BlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.BlockResponse;
/**
* Decodes a BlockResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns BlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.BlockResponse;
/**
* Verifies a BlockResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a BlockResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns BlockResponse
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.BlockResponse;
/**
* Creates a plain object from a BlockResponse message. Also converts values to other types if specified.
* @param message BlockResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.BlockResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this BlockResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Represents an Identity */
class Identity extends $protobuf.rpc.Service {
/**
* Constructs a new Identity service.
* @param rpcImpl RPC implementation
* @param [requestDelimited=false] Whether requests are length-delimited
* @param [responseDelimited=false] Whether responses are length-delimited
*/
constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean);
/**
* Creates new Identity service using the specified rpc implementation.
* @param rpcImpl RPC implementation
* @param [requestDelimited=false] Whether requests are length-delimited
* @param [responseDelimited=false] Whether responses are length-delimited
* @returns RPC service. Useful where requests and/or responses are streamed.
*/
public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Identity;
/**
* Calls CreateUser.
* @param request CreateUserRequest message or plain object
* @param callback Node-style callback called with the error, if any, and User
*/
public createUser(request: google.showcase.v1beta1.ICreateUserRequest, callback: google.showcase.v1beta1.Identity.CreateUserCallback): void;
/**
* Calls CreateUser.
* @param request CreateUserRequest message or plain object
* @returns Promise
*/
public createUser(request: google.showcase.v1beta1.ICreateUserRequest): Promise<google.showcase.v1beta1.User>;
/**
* Calls GetUser.
* @param request GetUserRequest message or plain object
* @param callback Node-style callback called with the error, if any, and User
*/
public getUser(request: google.showcase.v1beta1.IGetUserRequest, callback: google.showcase.v1beta1.Identity.GetUserCallback): void;
/**
* Calls GetUser.
* @param request GetUserRequest message or plain object
* @returns Promise
*/
public getUser(request: google.showcase.v1beta1.IGetUserRequest): Promise<google.showcase.v1beta1.User>;
/**
* Calls UpdateUser.
* @param request UpdateUserRequest message or plain object
* @param callback Node-style callback called with the error, if any, and User
*/
public updateUser(request: google.showcase.v1beta1.IUpdateUserRequest, callback: google.showcase.v1beta1.Identity.UpdateUserCallback): void;
/**
* Calls UpdateUser.
* @param request UpdateUserRequest message or plain object
* @returns Promise
*/
public updateUser(request: google.showcase.v1beta1.IUpdateUserRequest): Promise<google.showcase.v1beta1.User>;
/**
* Calls DeleteUser.
* @param request DeleteUserRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Empty
*/
public deleteUser(request: google.showcase.v1beta1.IDeleteUserRequest, callback: google.showcase.v1beta1.Identity.DeleteUserCallback): void;
/**
* Calls DeleteUser.
* @param request DeleteUserRequest message or plain object
* @returns Promise
*/
public deleteUser(request: google.showcase.v1beta1.IDeleteUserRequest): Promise<google.protobuf.Empty>;
/**
* Calls ListUsers.
* @param request ListUsersRequest message or plain object
* @param callback Node-style callback called with the error, if any, and ListUsersResponse
*/
public listUsers(request: google.showcase.v1beta1.IListUsersRequest, callback: google.showcase.v1beta1.Identity.ListUsersCallback): void;
/**
* Calls ListUsers.
* @param request ListUsersRequest message or plain object
* @returns Promise
*/
public listUsers(request: google.showcase.v1beta1.IListUsersRequest): Promise<google.showcase.v1beta1.ListUsersResponse>;
}
namespace Identity {
/**
* Callback as used by {@link google.showcase.v1beta1.Identity#createUser}.
* @param error Error, if any
* @param [response] User
*/
type CreateUserCallback = (error: (Error|null), response?: google.showcase.v1beta1.User) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Identity#getUser}.
* @param error Error, if any
* @param [response] User
*/
type GetUserCallback = (error: (Error|null), response?: google.showcase.v1beta1.User) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Identity#updateUser}.
* @param error Error, if any
* @param [response] User
*/
type UpdateUserCallback = (error: (Error|null), response?: google.showcase.v1beta1.User) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Identity#deleteUser}.
* @param error Error, if any
* @param [response] Empty
*/
type DeleteUserCallback = (error: (Error|null), response?: google.protobuf.Empty) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Identity#listUsers}.
* @param error Error, if any
* @param [response] ListUsersResponse
*/
type ListUsersCallback = (error: (Error|null), response?: google.showcase.v1beta1.ListUsersResponse) => void;
}
/** Properties of a User. */
interface IUser {
/** User name */
name?: (string|null);
/** User displayName */
displayName?: (string|null);
/** User email */
email?: (string|null);
/** User createTime */
createTime?: (google.protobuf.ITimestamp|null);
/** User updateTime */
updateTime?: (google.protobuf.ITimestamp|null);
}
/** Represents a User. */
class User implements IUser {
/**
* Constructs a new User.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IUser);
/** User name. */
public name: string;
/** User displayName. */
public displayName: string;
/** User email. */
public email: string;
/** User createTime. */
public createTime?: (google.protobuf.ITimestamp|null);
/** User updateTime. */
public updateTime?: (google.protobuf.ITimestamp|null);
/**
* Creates a new User instance using the specified properties.
* @param [properties] Properties to set
* @returns User instance
*/
public static create(properties?: google.showcase.v1beta1.IUser): google.showcase.v1beta1.User;
/**
* Encodes the specified User message. Does not implicitly {@link google.showcase.v1beta1.User.verify|verify} messages.
* @param message User message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IUser, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified User message, length delimited. Does not implicitly {@link google.showcase.v1beta1.User.verify|verify} messages.
* @param message User message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IUser, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a User message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns User
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.User;
/**
* Decodes a User message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns User
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.User;
/**
* Verifies a User message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a User message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns User
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.User;
/**
* Creates a plain object from a User message. Also converts values to other types if specified.
* @param message User
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.User, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this User to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a CreateUserRequest. */
interface ICreateUserRequest {
/** CreateUserRequest user */
user?: (google.showcase.v1beta1.IUser|null);
}
/** Represents a CreateUserRequest. */
class CreateUserRequest implements ICreateUserRequest {
/**
* Constructs a new CreateUserRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.ICreateUserRequest);
/** CreateUserRequest user. */
public user?: (google.showcase.v1beta1.IUser|null);
/**
* Creates a new CreateUserRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns CreateUserRequest instance
*/
public static create(properties?: google.showcase.v1beta1.ICreateUserRequest): google.showcase.v1beta1.CreateUserRequest;
/**
* Encodes the specified CreateUserRequest message. Does not implicitly {@link google.showcase.v1beta1.CreateUserRequest.verify|verify} messages.
* @param message CreateUserRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.ICreateUserRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified CreateUserRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.CreateUserRequest.verify|verify} messages.
* @param message CreateUserRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.ICreateUserRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a CreateUserRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns CreateUserRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.CreateUserRequest;
/**
* Decodes a CreateUserRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns CreateUserRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.CreateUserRequest;
/**
* Verifies a CreateUserRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a CreateUserRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns CreateUserRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.CreateUserRequest;
/**
* Creates a plain object from a CreateUserRequest message. Also converts values to other types if specified.
* @param message CreateUserRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.CreateUserRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this CreateUserRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a GetUserRequest. */
interface IGetUserRequest {
/** GetUserRequest name */
name?: (string|null);
}
/** Represents a GetUserRequest. */
class GetUserRequest implements IGetUserRequest {
/**
* Constructs a new GetUserRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IGetUserRequest);
/** GetUserRequest name. */
public name: string;
/**
* Creates a new GetUserRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns GetUserRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IGetUserRequest): google.showcase.v1beta1.GetUserRequest;
/**
* Encodes the specified GetUserRequest message. Does not implicitly {@link google.showcase.v1beta1.GetUserRequest.verify|verify} messages.
* @param message GetUserRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IGetUserRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GetUserRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.GetUserRequest.verify|verify} messages.
* @param message GetUserRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IGetUserRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GetUserRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GetUserRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.GetUserRequest;
/**
* Decodes a GetUserRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GetUserRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.GetUserRequest;
/**
* Verifies a GetUserRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a GetUserRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GetUserRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.GetUserRequest;
/**
* Creates a plain object from a GetUserRequest message. Also converts values to other types if specified.
* @param message GetUserRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.GetUserRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this GetUserRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an UpdateUserRequest. */
interface IUpdateUserRequest {
/** UpdateUserRequest user */
user?: (google.showcase.v1beta1.IUser|null);
/** UpdateUserRequest updateMask */
updateMask?: (google.protobuf.IFieldMask|null);
}
/** Represents an UpdateUserRequest. */
class UpdateUserRequest implements IUpdateUserRequest {
/**
* Constructs a new UpdateUserRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IUpdateUserRequest);
/** UpdateUserRequest user. */
public user?: (google.showcase.v1beta1.IUser|null);
/** UpdateUserRequest updateMask. */
public updateMask?: (google.protobuf.IFieldMask|null);
/**
* Creates a new UpdateUserRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns UpdateUserRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IUpdateUserRequest): google.showcase.v1beta1.UpdateUserRequest;
/**
* Encodes the specified UpdateUserRequest message. Does not implicitly {@link google.showcase.v1beta1.UpdateUserRequest.verify|verify} messages.
* @param message UpdateUserRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IUpdateUserRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified UpdateUserRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.UpdateUserRequest.verify|verify} messages.
* @param message UpdateUserRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IUpdateUserRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an UpdateUserRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns UpdateUserRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.UpdateUserRequest;
/**
* Decodes an UpdateUserRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns UpdateUserRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.UpdateUserRequest;
/**
* Verifies an UpdateUserRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an UpdateUserRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns UpdateUserRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.UpdateUserRequest;
/**
* Creates a plain object from an UpdateUserRequest message. Also converts values to other types if specified.
* @param message UpdateUserRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.UpdateUserRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this UpdateUserRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a DeleteUserRequest. */
interface IDeleteUserRequest {
/** DeleteUserRequest name */
name?: (string|null);
}
/** Represents a DeleteUserRequest. */
class DeleteUserRequest implements IDeleteUserRequest {
/**
* Constructs a new DeleteUserRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IDeleteUserRequest);
/** DeleteUserRequest name. */
public name: string;
/**
* Creates a new DeleteUserRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns DeleteUserRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IDeleteUserRequest): google.showcase.v1beta1.DeleteUserRequest;
/**
* Encodes the specified DeleteUserRequest message. Does not implicitly {@link google.showcase.v1beta1.DeleteUserRequest.verify|verify} messages.
* @param message DeleteUserRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IDeleteUserRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified DeleteUserRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.DeleteUserRequest.verify|verify} messages.
* @param message DeleteUserRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IDeleteUserRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a DeleteUserRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns DeleteUserRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.DeleteUserRequest;
/**
* Decodes a DeleteUserRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns DeleteUserRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.DeleteUserRequest;
/**
* Verifies a DeleteUserRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a DeleteUserRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns DeleteUserRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.DeleteUserRequest;
/**
* Creates a plain object from a DeleteUserRequest message. Also converts values to other types if specified.
* @param message DeleteUserRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.DeleteUserRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this DeleteUserRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ListUsersRequest. */
interface IListUsersRequest {
/** ListUsersRequest pageSize */
pageSize?: (number|null);
/** ListUsersRequest pageToken */
pageToken?: (string|null);
}
/** Represents a ListUsersRequest. */
class ListUsersRequest implements IListUsersRequest {
/**
* Constructs a new ListUsersRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IListUsersRequest);
/** ListUsersRequest pageSize. */
public pageSize: number;
/** ListUsersRequest pageToken. */
public pageToken: string;
/**
* Creates a new ListUsersRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ListUsersRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IListUsersRequest): google.showcase.v1beta1.ListUsersRequest;
/**
* Encodes the specified ListUsersRequest message. Does not implicitly {@link google.showcase.v1beta1.ListUsersRequest.verify|verify} messages.
* @param message ListUsersRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IListUsersRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ListUsersRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.ListUsersRequest.verify|verify} messages.
* @param message ListUsersRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IListUsersRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ListUsersRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ListUsersRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.ListUsersRequest;
/**
* Decodes a ListUsersRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ListUsersRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.ListUsersRequest;
/**
* Verifies a ListUsersRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ListUsersRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ListUsersRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.ListUsersRequest;
/**
* Creates a plain object from a ListUsersRequest message. Also converts values to other types if specified.
* @param message ListUsersRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.ListUsersRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ListUsersRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ListUsersResponse. */
interface IListUsersResponse {
/** ListUsersResponse users */
users?: (google.showcase.v1beta1.IUser[]|null);
/** ListUsersResponse nextPageToken */
nextPageToken?: (string|null);
}
/** Represents a ListUsersResponse. */
class ListUsersResponse implements IListUsersResponse {
/**
* Constructs a new ListUsersResponse.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IListUsersResponse);
/** ListUsersResponse users. */
public users: google.showcase.v1beta1.IUser[];
/** ListUsersResponse nextPageToken. */
public nextPageToken: string;
/**
* Creates a new ListUsersResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ListUsersResponse instance
*/
public static create(properties?: google.showcase.v1beta1.IListUsersResponse): google.showcase.v1beta1.ListUsersResponse;
/**
* Encodes the specified ListUsersResponse message. Does not implicitly {@link google.showcase.v1beta1.ListUsersResponse.verify|verify} messages.
* @param message ListUsersResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IListUsersResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ListUsersResponse message, length delimited. Does not implicitly {@link google.showcase.v1beta1.ListUsersResponse.verify|verify} messages.
* @param message ListUsersResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IListUsersResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ListUsersResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ListUsersResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.ListUsersResponse;
/**
* Decodes a ListUsersResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ListUsersResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.ListUsersResponse;
/**
* Verifies a ListUsersResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ListUsersResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ListUsersResponse
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.ListUsersResponse;
/**
* Creates a plain object from a ListUsersResponse message. Also converts values to other types if specified.
* @param message ListUsersResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.ListUsersResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ListUsersResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Represents a Messaging */
class Messaging extends $protobuf.rpc.Service {
/**
* Constructs a new Messaging service.
* @param rpcImpl RPC implementation
* @param [requestDelimited=false] Whether requests are length-delimited
* @param [responseDelimited=false] Whether responses are length-delimited
*/
constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean);
/**
* Creates new Messaging service using the specified rpc implementation.
* @param rpcImpl RPC implementation
* @param [requestDelimited=false] Whether requests are length-delimited
* @param [responseDelimited=false] Whether responses are length-delimited
* @returns RPC service. Useful where requests and/or responses are streamed.
*/
public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Messaging;
/**
* Calls CreateRoom.
* @param request CreateRoomRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Room
*/
public createRoom(request: google.showcase.v1beta1.ICreateRoomRequest, callback: google.showcase.v1beta1.Messaging.CreateRoomCallback): void;
/**
* Calls CreateRoom.
* @param request CreateRoomRequest message or plain object
* @returns Promise
*/
public createRoom(request: google.showcase.v1beta1.ICreateRoomRequest): Promise<google.showcase.v1beta1.Room>;
/**
* Calls GetRoom.
* @param request GetRoomRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Room
*/
public getRoom(request: google.showcase.v1beta1.IGetRoomRequest, callback: google.showcase.v1beta1.Messaging.GetRoomCallback): void;
/**
* Calls GetRoom.
* @param request GetRoomRequest message or plain object
* @returns Promise
*/
public getRoom(request: google.showcase.v1beta1.IGetRoomRequest): Promise<google.showcase.v1beta1.Room>;
/**
* Calls UpdateRoom.
* @param request UpdateRoomRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Room
*/
public updateRoom(request: google.showcase.v1beta1.IUpdateRoomRequest, callback: google.showcase.v1beta1.Messaging.UpdateRoomCallback): void;
/**
* Calls UpdateRoom.
* @param request UpdateRoomRequest message or plain object
* @returns Promise
*/
public updateRoom(request: google.showcase.v1beta1.IUpdateRoomRequest): Promise<google.showcase.v1beta1.Room>;
/**
* Calls DeleteRoom.
* @param request DeleteRoomRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Empty
*/
public deleteRoom(request: google.showcase.v1beta1.IDeleteRoomRequest, callback: google.showcase.v1beta1.Messaging.DeleteRoomCallback): void;
/**
* Calls DeleteRoom.
* @param request DeleteRoomRequest message or plain object
* @returns Promise
*/
public deleteRoom(request: google.showcase.v1beta1.IDeleteRoomRequest): Promise<google.protobuf.Empty>;
/**
* Calls ListRooms.
* @param request ListRoomsRequest message or plain object
* @param callback Node-style callback called with the error, if any, and ListRoomsResponse
*/
public listRooms(request: google.showcase.v1beta1.IListRoomsRequest, callback: google.showcase.v1beta1.Messaging.ListRoomsCallback): void;
/**
* Calls ListRooms.
* @param request ListRoomsRequest message or plain object
* @returns Promise
*/
public listRooms(request: google.showcase.v1beta1.IListRoomsRequest): Promise<google.showcase.v1beta1.ListRoomsResponse>;
/**
* Calls CreateBlurb.
* @param request CreateBlurbRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Blurb
*/
public createBlurb(request: google.showcase.v1beta1.ICreateBlurbRequest, callback: google.showcase.v1beta1.Messaging.CreateBlurbCallback): void;
/**
* Calls CreateBlurb.
* @param request CreateBlurbRequest message or plain object
* @returns Promise
*/
public createBlurb(request: google.showcase.v1beta1.ICreateBlurbRequest): Promise<google.showcase.v1beta1.Blurb>;
/**
* Calls GetBlurb.
* @param request GetBlurbRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Blurb
*/
public getBlurb(request: google.showcase.v1beta1.IGetBlurbRequest, callback: google.showcase.v1beta1.Messaging.GetBlurbCallback): void;
/**
* Calls GetBlurb.
* @param request GetBlurbRequest message or plain object
* @returns Promise
*/
public getBlurb(request: google.showcase.v1beta1.IGetBlurbRequest): Promise<google.showcase.v1beta1.Blurb>;
/**
* Calls UpdateBlurb.
* @param request UpdateBlurbRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Blurb
*/
public updateBlurb(request: google.showcase.v1beta1.IUpdateBlurbRequest, callback: google.showcase.v1beta1.Messaging.UpdateBlurbCallback): void;
/**
* Calls UpdateBlurb.
* @param request UpdateBlurbRequest message or plain object
* @returns Promise
*/
public updateBlurb(request: google.showcase.v1beta1.IUpdateBlurbRequest): Promise<google.showcase.v1beta1.Blurb>;
/**
* Calls DeleteBlurb.
* @param request DeleteBlurbRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Empty
*/
public deleteBlurb(request: google.showcase.v1beta1.IDeleteBlurbRequest, callback: google.showcase.v1beta1.Messaging.DeleteBlurbCallback): void;
/**
* Calls DeleteBlurb.
* @param request DeleteBlurbRequest message or plain object
* @returns Promise
*/
public deleteBlurb(request: google.showcase.v1beta1.IDeleteBlurbRequest): Promise<google.protobuf.Empty>;
/**
* Calls ListBlurbs.
* @param request ListBlurbsRequest message or plain object
* @param callback Node-style callback called with the error, if any, and ListBlurbsResponse
*/
public listBlurbs(request: google.showcase.v1beta1.IListBlurbsRequest, callback: google.showcase.v1beta1.Messaging.ListBlurbsCallback): void;
/**
* Calls ListBlurbs.
* @param request ListBlurbsRequest message or plain object
* @returns Promise
*/
public listBlurbs(request: google.showcase.v1beta1.IListBlurbsRequest): Promise<google.showcase.v1beta1.ListBlurbsResponse>;
/**
* Calls SearchBlurbs.
* @param request SearchBlurbsRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Operation
*/
public searchBlurbs(request: google.showcase.v1beta1.ISearchBlurbsRequest, callback: google.showcase.v1beta1.Messaging.SearchBlurbsCallback): void;
/**
* Calls SearchBlurbs.
* @param request SearchBlurbsRequest message or plain object
* @returns Promise
*/
public searchBlurbs(request: google.showcase.v1beta1.ISearchBlurbsRequest): Promise<google.longrunning.Operation>;
/**
* Calls StreamBlurbs.
* @param request StreamBlurbsRequest message or plain object
* @param callback Node-style callback called with the error, if any, and StreamBlurbsResponse
*/
public streamBlurbs(request: google.showcase.v1beta1.IStreamBlurbsRequest, callback: google.showcase.v1beta1.Messaging.StreamBlurbsCallback): void;
/**
* Calls StreamBlurbs.
* @param request StreamBlurbsRequest message or plain object
* @returns Promise
*/
public streamBlurbs(request: google.showcase.v1beta1.IStreamBlurbsRequest): Promise<google.showcase.v1beta1.StreamBlurbsResponse>;
/**
* Calls SendBlurbs.
* @param request CreateBlurbRequest message or plain object
* @param callback Node-style callback called with the error, if any, and SendBlurbsResponse
*/
public sendBlurbs(request: google.showcase.v1beta1.ICreateBlurbRequest, callback: google.showcase.v1beta1.Messaging.SendBlurbsCallback): void;
/**
* Calls SendBlurbs.
* @param request CreateBlurbRequest message or plain object
* @returns Promise
*/
public sendBlurbs(request: google.showcase.v1beta1.ICreateBlurbRequest): Promise<google.showcase.v1beta1.SendBlurbsResponse>;
/**
* Calls Connect.
* @param request ConnectRequest message or plain object
* @param callback Node-style callback called with the error, if any, and StreamBlurbsResponse
*/
public connect(request: google.showcase.v1beta1.IConnectRequest, callback: google.showcase.v1beta1.Messaging.ConnectCallback): void;
/**
* Calls Connect.
* @param request ConnectRequest message or plain object
* @returns Promise
*/
public connect(request: google.showcase.v1beta1.IConnectRequest): Promise<google.showcase.v1beta1.StreamBlurbsResponse>;
}
namespace Messaging {
/**
* Callback as used by {@link google.showcase.v1beta1.Messaging#createRoom}.
* @param error Error, if any
* @param [response] Room
*/
type CreateRoomCallback = (error: (Error|null), response?: google.showcase.v1beta1.Room) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Messaging#getRoom}.
* @param error Error, if any
* @param [response] Room
*/
type GetRoomCallback = (error: (Error|null), response?: google.showcase.v1beta1.Room) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Messaging#updateRoom}.
* @param error Error, if any
* @param [response] Room
*/
type UpdateRoomCallback = (error: (Error|null), response?: google.showcase.v1beta1.Room) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Messaging#deleteRoom}.
* @param error Error, if any
* @param [response] Empty
*/
type DeleteRoomCallback = (error: (Error|null), response?: google.protobuf.Empty) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Messaging#listRooms}.
* @param error Error, if any
* @param [response] ListRoomsResponse
*/
type ListRoomsCallback = (error: (Error|null), response?: google.showcase.v1beta1.ListRoomsResponse) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Messaging#createBlurb}.
* @param error Error, if any
* @param [response] Blurb
*/
type CreateBlurbCallback = (error: (Error|null), response?: google.showcase.v1beta1.Blurb) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Messaging#getBlurb}.
* @param error Error, if any
* @param [response] Blurb
*/
type GetBlurbCallback = (error: (Error|null), response?: google.showcase.v1beta1.Blurb) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Messaging#updateBlurb}.
* @param error Error, if any
* @param [response] Blurb
*/
type UpdateBlurbCallback = (error: (Error|null), response?: google.showcase.v1beta1.Blurb) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Messaging#deleteBlurb}.
* @param error Error, if any
* @param [response] Empty
*/
type DeleteBlurbCallback = (error: (Error|null), response?: google.protobuf.Empty) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Messaging#listBlurbs}.
* @param error Error, if any
* @param [response] ListBlurbsResponse
*/
type ListBlurbsCallback = (error: (Error|null), response?: google.showcase.v1beta1.ListBlurbsResponse) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Messaging#searchBlurbs}.
* @param error Error, if any
* @param [response] Operation
*/
type SearchBlurbsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Messaging#streamBlurbs}.
* @param error Error, if any
* @param [response] StreamBlurbsResponse
*/
type StreamBlurbsCallback = (error: (Error|null), response?: google.showcase.v1beta1.StreamBlurbsResponse) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Messaging#sendBlurbs}.
* @param error Error, if any
* @param [response] SendBlurbsResponse
*/
type SendBlurbsCallback = (error: (Error|null), response?: google.showcase.v1beta1.SendBlurbsResponse) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Messaging#connect}.
* @param error Error, if any
* @param [response] StreamBlurbsResponse
*/
type ConnectCallback = (error: (Error|null), response?: google.showcase.v1beta1.StreamBlurbsResponse) => void;
}
/** Properties of a Room. */
interface IRoom {
/** Room name */
name?: (string|null);
/** Room displayName */
displayName?: (string|null);
/** Room description */
description?: (string|null);
/** Room createTime */
createTime?: (google.protobuf.ITimestamp|null);
/** Room updateTime */
updateTime?: (google.protobuf.ITimestamp|null);
}
/** Represents a Room. */
class Room implements IRoom {
/**
* Constructs a new Room.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IRoom);
/** Room name. */
public name: string;
/** Room displayName. */
public displayName: string;
/** Room description. */
public description: string;
/** Room createTime. */
public createTime?: (google.protobuf.ITimestamp|null);
/** Room updateTime. */
public updateTime?: (google.protobuf.ITimestamp|null);
/**
* Creates a new Room instance using the specified properties.
* @param [properties] Properties to set
* @returns Room instance
*/
public static create(properties?: google.showcase.v1beta1.IRoom): google.showcase.v1beta1.Room;
/**
* Encodes the specified Room message. Does not implicitly {@link google.showcase.v1beta1.Room.verify|verify} messages.
* @param message Room message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IRoom, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Room message, length delimited. Does not implicitly {@link google.showcase.v1beta1.Room.verify|verify} messages.
* @param message Room message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IRoom, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Room message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Room
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.Room;
/**
* Decodes a Room message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Room
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.Room;
/**
* Verifies a Room message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Room message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Room
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.Room;
/**
* Creates a plain object from a Room message. Also converts values to other types if specified.
* @param message Room
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.Room, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Room to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a CreateRoomRequest. */
interface ICreateRoomRequest {
/** CreateRoomRequest room */
room?: (google.showcase.v1beta1.IRoom|null);
}
/** Represents a CreateRoomRequest. */
class CreateRoomRequest implements ICreateRoomRequest {
/**
* Constructs a new CreateRoomRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.ICreateRoomRequest);
/** CreateRoomRequest room. */
public room?: (google.showcase.v1beta1.IRoom|null);
/**
* Creates a new CreateRoomRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns CreateRoomRequest instance
*/
public static create(properties?: google.showcase.v1beta1.ICreateRoomRequest): google.showcase.v1beta1.CreateRoomRequest;
/**
* Encodes the specified CreateRoomRequest message. Does not implicitly {@link google.showcase.v1beta1.CreateRoomRequest.verify|verify} messages.
* @param message CreateRoomRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.ICreateRoomRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified CreateRoomRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.CreateRoomRequest.verify|verify} messages.
* @param message CreateRoomRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.ICreateRoomRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a CreateRoomRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns CreateRoomRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.CreateRoomRequest;
/**
* Decodes a CreateRoomRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns CreateRoomRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.CreateRoomRequest;
/**
* Verifies a CreateRoomRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a CreateRoomRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns CreateRoomRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.CreateRoomRequest;
/**
* Creates a plain object from a CreateRoomRequest message. Also converts values to other types if specified.
* @param message CreateRoomRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.CreateRoomRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this CreateRoomRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a GetRoomRequest. */
interface IGetRoomRequest {
/** GetRoomRequest name */
name?: (string|null);
}
/** Represents a GetRoomRequest. */
class GetRoomRequest implements IGetRoomRequest {
/**
* Constructs a new GetRoomRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IGetRoomRequest);
/** GetRoomRequest name. */
public name: string;
/**
* Creates a new GetRoomRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns GetRoomRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IGetRoomRequest): google.showcase.v1beta1.GetRoomRequest;
/**
* Encodes the specified GetRoomRequest message. Does not implicitly {@link google.showcase.v1beta1.GetRoomRequest.verify|verify} messages.
* @param message GetRoomRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IGetRoomRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GetRoomRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.GetRoomRequest.verify|verify} messages.
* @param message GetRoomRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IGetRoomRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GetRoomRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GetRoomRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.GetRoomRequest;
/**
* Decodes a GetRoomRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GetRoomRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.GetRoomRequest;
/**
* Verifies a GetRoomRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a GetRoomRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GetRoomRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.GetRoomRequest;
/**
* Creates a plain object from a GetRoomRequest message. Also converts values to other types if specified.
* @param message GetRoomRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.GetRoomRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this GetRoomRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an UpdateRoomRequest. */
interface IUpdateRoomRequest {
/** UpdateRoomRequest room */
room?: (google.showcase.v1beta1.IRoom|null);
/** UpdateRoomRequest updateMask */
updateMask?: (google.protobuf.IFieldMask|null);
}
/** Represents an UpdateRoomRequest. */
class UpdateRoomRequest implements IUpdateRoomRequest {
/**
* Constructs a new UpdateRoomRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IUpdateRoomRequest);
/** UpdateRoomRequest room. */
public room?: (google.showcase.v1beta1.IRoom|null);
/** UpdateRoomRequest updateMask. */
public updateMask?: (google.protobuf.IFieldMask|null);
/**
* Creates a new UpdateRoomRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns UpdateRoomRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IUpdateRoomRequest): google.showcase.v1beta1.UpdateRoomRequest;
/**
* Encodes the specified UpdateRoomRequest message. Does not implicitly {@link google.showcase.v1beta1.UpdateRoomRequest.verify|verify} messages.
* @param message UpdateRoomRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IUpdateRoomRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified UpdateRoomRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.UpdateRoomRequest.verify|verify} messages.
* @param message UpdateRoomRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IUpdateRoomRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an UpdateRoomRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns UpdateRoomRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.UpdateRoomRequest;
/**
* Decodes an UpdateRoomRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns UpdateRoomRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.UpdateRoomRequest;
/**
* Verifies an UpdateRoomRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an UpdateRoomRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns UpdateRoomRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.UpdateRoomRequest;
/**
* Creates a plain object from an UpdateRoomRequest message. Also converts values to other types if specified.
* @param message UpdateRoomRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.UpdateRoomRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this UpdateRoomRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a DeleteRoomRequest. */
interface IDeleteRoomRequest {
/** DeleteRoomRequest name */
name?: (string|null);
}
/** Represents a DeleteRoomRequest. */
class DeleteRoomRequest implements IDeleteRoomRequest {
/**
* Constructs a new DeleteRoomRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IDeleteRoomRequest);
/** DeleteRoomRequest name. */
public name: string;
/**
* Creates a new DeleteRoomRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns DeleteRoomRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IDeleteRoomRequest): google.showcase.v1beta1.DeleteRoomRequest;
/**
* Encodes the specified DeleteRoomRequest message. Does not implicitly {@link google.showcase.v1beta1.DeleteRoomRequest.verify|verify} messages.
* @param message DeleteRoomRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IDeleteRoomRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified DeleteRoomRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.DeleteRoomRequest.verify|verify} messages.
* @param message DeleteRoomRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IDeleteRoomRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a DeleteRoomRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns DeleteRoomRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.DeleteRoomRequest;
/**
* Decodes a DeleteRoomRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns DeleteRoomRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.DeleteRoomRequest;
/**
* Verifies a DeleteRoomRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a DeleteRoomRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns DeleteRoomRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.DeleteRoomRequest;
/**
* Creates a plain object from a DeleteRoomRequest message. Also converts values to other types if specified.
* @param message DeleteRoomRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.DeleteRoomRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this DeleteRoomRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ListRoomsRequest. */
interface IListRoomsRequest {
/** ListRoomsRequest pageSize */
pageSize?: (number|null);
/** ListRoomsRequest pageToken */
pageToken?: (string|null);
}
/** Represents a ListRoomsRequest. */
class ListRoomsRequest implements IListRoomsRequest {
/**
* Constructs a new ListRoomsRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IListRoomsRequest);
/** ListRoomsRequest pageSize. */
public pageSize: number;
/** ListRoomsRequest pageToken. */
public pageToken: string;
/**
* Creates a new ListRoomsRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ListRoomsRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IListRoomsRequest): google.showcase.v1beta1.ListRoomsRequest;
/**
* Encodes the specified ListRoomsRequest message. Does not implicitly {@link google.showcase.v1beta1.ListRoomsRequest.verify|verify} messages.
* @param message ListRoomsRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IListRoomsRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ListRoomsRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.ListRoomsRequest.verify|verify} messages.
* @param message ListRoomsRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IListRoomsRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ListRoomsRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ListRoomsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.ListRoomsRequest;
/**
* Decodes a ListRoomsRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ListRoomsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.ListRoomsRequest;
/**
* Verifies a ListRoomsRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ListRoomsRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ListRoomsRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.ListRoomsRequest;
/**
* Creates a plain object from a ListRoomsRequest message. Also converts values to other types if specified.
* @param message ListRoomsRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.ListRoomsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ListRoomsRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ListRoomsResponse. */
interface IListRoomsResponse {
/** ListRoomsResponse rooms */
rooms?: (google.showcase.v1beta1.IRoom[]|null);
/** ListRoomsResponse nextPageToken */
nextPageToken?: (string|null);
}
/** Represents a ListRoomsResponse. */
class ListRoomsResponse implements IListRoomsResponse {
/**
* Constructs a new ListRoomsResponse.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IListRoomsResponse);
/** ListRoomsResponse rooms. */
public rooms: google.showcase.v1beta1.IRoom[];
/** ListRoomsResponse nextPageToken. */
public nextPageToken: string;
/**
* Creates a new ListRoomsResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ListRoomsResponse instance
*/
public static create(properties?: google.showcase.v1beta1.IListRoomsResponse): google.showcase.v1beta1.ListRoomsResponse;
/**
* Encodes the specified ListRoomsResponse message. Does not implicitly {@link google.showcase.v1beta1.ListRoomsResponse.verify|verify} messages.
* @param message ListRoomsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IListRoomsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ListRoomsResponse message, length delimited. Does not implicitly {@link google.showcase.v1beta1.ListRoomsResponse.verify|verify} messages.
* @param message ListRoomsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IListRoomsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ListRoomsResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ListRoomsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.ListRoomsResponse;
/**
* Decodes a ListRoomsResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ListRoomsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.ListRoomsResponse;
/**
* Verifies a ListRoomsResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ListRoomsResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ListRoomsResponse
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.ListRoomsResponse;
/**
* Creates a plain object from a ListRoomsResponse message. Also converts values to other types if specified.
* @param message ListRoomsResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.ListRoomsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ListRoomsResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Blurb. */
interface IBlurb {
/** Blurb name */
name?: (string|null);
/** Blurb user */
user?: (string|null);
/** Blurb text */
text?: (string|null);
/** Blurb image */
image?: (Uint8Array|string|null);
/** Blurb createTime */
createTime?: (google.protobuf.ITimestamp|null);
/** Blurb updateTime */
updateTime?: (google.protobuf.ITimestamp|null);
}
/** Represents a Blurb. */
class Blurb implements IBlurb {
/**
* Constructs a new Blurb.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IBlurb);
/** Blurb name. */
public name: string;
/** Blurb user. */
public user: string;
/** Blurb text. */
public text?: (string|null);
/** Blurb image. */
public image?: (Uint8Array|string|null);
/** Blurb createTime. */
public createTime?: (google.protobuf.ITimestamp|null);
/** Blurb updateTime. */
public updateTime?: (google.protobuf.ITimestamp|null);
/** Blurb content. */
public content?: ("text"|"image");
/**
* Creates a new Blurb instance using the specified properties.
* @param [properties] Properties to set
* @returns Blurb instance
*/
public static create(properties?: google.showcase.v1beta1.IBlurb): google.showcase.v1beta1.Blurb;
/**
* Encodes the specified Blurb message. Does not implicitly {@link google.showcase.v1beta1.Blurb.verify|verify} messages.
* @param message Blurb message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IBlurb, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Blurb message, length delimited. Does not implicitly {@link google.showcase.v1beta1.Blurb.verify|verify} messages.
* @param message Blurb message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IBlurb, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Blurb message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Blurb
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.Blurb;
/**
* Decodes a Blurb message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Blurb
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.Blurb;
/**
* Verifies a Blurb message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Blurb message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Blurb
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.Blurb;
/**
* Creates a plain object from a Blurb message. Also converts values to other types if specified.
* @param message Blurb
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.Blurb, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Blurb to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a CreateBlurbRequest. */
interface ICreateBlurbRequest {
/** CreateBlurbRequest parent */
parent?: (string|null);
/** CreateBlurbRequest blurb */
blurb?: (google.showcase.v1beta1.IBlurb|null);
}
/** Represents a CreateBlurbRequest. */
class CreateBlurbRequest implements ICreateBlurbRequest {
/**
* Constructs a new CreateBlurbRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.ICreateBlurbRequest);
/** CreateBlurbRequest parent. */
public parent: string;
/** CreateBlurbRequest blurb. */
public blurb?: (google.showcase.v1beta1.IBlurb|null);
/**
* Creates a new CreateBlurbRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns CreateBlurbRequest instance
*/
public static create(properties?: google.showcase.v1beta1.ICreateBlurbRequest): google.showcase.v1beta1.CreateBlurbRequest;
/**
* Encodes the specified CreateBlurbRequest message. Does not implicitly {@link google.showcase.v1beta1.CreateBlurbRequest.verify|verify} messages.
* @param message CreateBlurbRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.ICreateBlurbRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified CreateBlurbRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.CreateBlurbRequest.verify|verify} messages.
* @param message CreateBlurbRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.ICreateBlurbRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a CreateBlurbRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns CreateBlurbRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.CreateBlurbRequest;
/**
* Decodes a CreateBlurbRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns CreateBlurbRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.CreateBlurbRequest;
/**
* Verifies a CreateBlurbRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a CreateBlurbRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns CreateBlurbRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.CreateBlurbRequest;
/**
* Creates a plain object from a CreateBlurbRequest message. Also converts values to other types if specified.
* @param message CreateBlurbRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.CreateBlurbRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this CreateBlurbRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a GetBlurbRequest. */
interface IGetBlurbRequest {
/** GetBlurbRequest name */
name?: (string|null);
}
/** Represents a GetBlurbRequest. */
class GetBlurbRequest implements IGetBlurbRequest {
/**
* Constructs a new GetBlurbRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IGetBlurbRequest);
/** GetBlurbRequest name. */
public name: string;
/**
* Creates a new GetBlurbRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns GetBlurbRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IGetBlurbRequest): google.showcase.v1beta1.GetBlurbRequest;
/**
* Encodes the specified GetBlurbRequest message. Does not implicitly {@link google.showcase.v1beta1.GetBlurbRequest.verify|verify} messages.
* @param message GetBlurbRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IGetBlurbRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GetBlurbRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.GetBlurbRequest.verify|verify} messages.
* @param message GetBlurbRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IGetBlurbRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GetBlurbRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GetBlurbRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.GetBlurbRequest;
/**
* Decodes a GetBlurbRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GetBlurbRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.GetBlurbRequest;
/**
* Verifies a GetBlurbRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a GetBlurbRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GetBlurbRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.GetBlurbRequest;
/**
* Creates a plain object from a GetBlurbRequest message. Also converts values to other types if specified.
* @param message GetBlurbRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.GetBlurbRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this GetBlurbRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an UpdateBlurbRequest. */
interface IUpdateBlurbRequest {
/** UpdateBlurbRequest blurb */
blurb?: (google.showcase.v1beta1.IBlurb|null);
/** UpdateBlurbRequest updateMask */
updateMask?: (google.protobuf.IFieldMask|null);
}
/** Represents an UpdateBlurbRequest. */
class UpdateBlurbRequest implements IUpdateBlurbRequest {
/**
* Constructs a new UpdateBlurbRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IUpdateBlurbRequest);
/** UpdateBlurbRequest blurb. */
public blurb?: (google.showcase.v1beta1.IBlurb|null);
/** UpdateBlurbRequest updateMask. */
public updateMask?: (google.protobuf.IFieldMask|null);
/**
* Creates a new UpdateBlurbRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns UpdateBlurbRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IUpdateBlurbRequest): google.showcase.v1beta1.UpdateBlurbRequest;
/**
* Encodes the specified UpdateBlurbRequest message. Does not implicitly {@link google.showcase.v1beta1.UpdateBlurbRequest.verify|verify} messages.
* @param message UpdateBlurbRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IUpdateBlurbRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified UpdateBlurbRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.UpdateBlurbRequest.verify|verify} messages.
* @param message UpdateBlurbRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IUpdateBlurbRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an UpdateBlurbRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns UpdateBlurbRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.UpdateBlurbRequest;
/**
* Decodes an UpdateBlurbRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns UpdateBlurbRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.UpdateBlurbRequest;
/**
* Verifies an UpdateBlurbRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an UpdateBlurbRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns UpdateBlurbRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.UpdateBlurbRequest;
/**
* Creates a plain object from an UpdateBlurbRequest message. Also converts values to other types if specified.
* @param message UpdateBlurbRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.UpdateBlurbRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this UpdateBlurbRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a DeleteBlurbRequest. */
interface IDeleteBlurbRequest {
/** DeleteBlurbRequest name */
name?: (string|null);
}
/** Represents a DeleteBlurbRequest. */
class DeleteBlurbRequest implements IDeleteBlurbRequest {
/**
* Constructs a new DeleteBlurbRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IDeleteBlurbRequest);
/** DeleteBlurbRequest name. */
public name: string;
/**
* Creates a new DeleteBlurbRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns DeleteBlurbRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IDeleteBlurbRequest): google.showcase.v1beta1.DeleteBlurbRequest;
/**
* Encodes the specified DeleteBlurbRequest message. Does not implicitly {@link google.showcase.v1beta1.DeleteBlurbRequest.verify|verify} messages.
* @param message DeleteBlurbRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IDeleteBlurbRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified DeleteBlurbRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.DeleteBlurbRequest.verify|verify} messages.
* @param message DeleteBlurbRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IDeleteBlurbRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a DeleteBlurbRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns DeleteBlurbRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.DeleteBlurbRequest;
/**
* Decodes a DeleteBlurbRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns DeleteBlurbRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.DeleteBlurbRequest;
/**
* Verifies a DeleteBlurbRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a DeleteBlurbRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns DeleteBlurbRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.DeleteBlurbRequest;
/**
* Creates a plain object from a DeleteBlurbRequest message. Also converts values to other types if specified.
* @param message DeleteBlurbRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.DeleteBlurbRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this DeleteBlurbRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ListBlurbsRequest. */
interface IListBlurbsRequest {
/** ListBlurbsRequest parent */
parent?: (string|null);
/** ListBlurbsRequest pageSize */
pageSize?: (number|null);
/** ListBlurbsRequest pageToken */
pageToken?: (string|null);
}
/** Represents a ListBlurbsRequest. */
class ListBlurbsRequest implements IListBlurbsRequest {
/**
* Constructs a new ListBlurbsRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IListBlurbsRequest);
/** ListBlurbsRequest parent. */
public parent: string;
/** ListBlurbsRequest pageSize. */
public pageSize: number;
/** ListBlurbsRequest pageToken. */
public pageToken: string;
/**
* Creates a new ListBlurbsRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ListBlurbsRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IListBlurbsRequest): google.showcase.v1beta1.ListBlurbsRequest;
/**
* Encodes the specified ListBlurbsRequest message. Does not implicitly {@link google.showcase.v1beta1.ListBlurbsRequest.verify|verify} messages.
* @param message ListBlurbsRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IListBlurbsRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ListBlurbsRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.ListBlurbsRequest.verify|verify} messages.
* @param message ListBlurbsRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IListBlurbsRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ListBlurbsRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ListBlurbsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.ListBlurbsRequest;
/**
* Decodes a ListBlurbsRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ListBlurbsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.ListBlurbsRequest;
/**
* Verifies a ListBlurbsRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ListBlurbsRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ListBlurbsRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.ListBlurbsRequest;
/**
* Creates a plain object from a ListBlurbsRequest message. Also converts values to other types if specified.
* @param message ListBlurbsRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.ListBlurbsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ListBlurbsRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ListBlurbsResponse. */
interface IListBlurbsResponse {
/** ListBlurbsResponse blurbs */
blurbs?: (google.showcase.v1beta1.IBlurb[]|null);
/** ListBlurbsResponse nextPageToken */
nextPageToken?: (string|null);
}
/** Represents a ListBlurbsResponse. */
class ListBlurbsResponse implements IListBlurbsResponse {
/**
* Constructs a new ListBlurbsResponse.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IListBlurbsResponse);
/** ListBlurbsResponse blurbs. */
public blurbs: google.showcase.v1beta1.IBlurb[];
/** ListBlurbsResponse nextPageToken. */
public nextPageToken: string;
/**
* Creates a new ListBlurbsResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ListBlurbsResponse instance
*/
public static create(properties?: google.showcase.v1beta1.IListBlurbsResponse): google.showcase.v1beta1.ListBlurbsResponse;
/**
* Encodes the specified ListBlurbsResponse message. Does not implicitly {@link google.showcase.v1beta1.ListBlurbsResponse.verify|verify} messages.
* @param message ListBlurbsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IListBlurbsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ListBlurbsResponse message, length delimited. Does not implicitly {@link google.showcase.v1beta1.ListBlurbsResponse.verify|verify} messages.
* @param message ListBlurbsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IListBlurbsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ListBlurbsResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ListBlurbsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.ListBlurbsResponse;
/**
* Decodes a ListBlurbsResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ListBlurbsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.ListBlurbsResponse;
/**
* Verifies a ListBlurbsResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ListBlurbsResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ListBlurbsResponse
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.ListBlurbsResponse;
/**
* Creates a plain object from a ListBlurbsResponse message. Also converts values to other types if specified.
* @param message ListBlurbsResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.ListBlurbsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ListBlurbsResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a SearchBlurbsRequest. */
interface ISearchBlurbsRequest {
/** SearchBlurbsRequest query */
query?: (string|null);
/** SearchBlurbsRequest parent */
parent?: (string|null);
/** SearchBlurbsRequest pageSize */
pageSize?: (number|null);
/** SearchBlurbsRequest pageToken */
pageToken?: (string|null);
}
/** Represents a SearchBlurbsRequest. */
class SearchBlurbsRequest implements ISearchBlurbsRequest {
/**
* Constructs a new SearchBlurbsRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.ISearchBlurbsRequest);
/** SearchBlurbsRequest query. */
public query: string;
/** SearchBlurbsRequest parent. */
public parent: string;
/** SearchBlurbsRequest pageSize. */
public pageSize: number;
/** SearchBlurbsRequest pageToken. */
public pageToken: string;
/**
* Creates a new SearchBlurbsRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns SearchBlurbsRequest instance
*/
public static create(properties?: google.showcase.v1beta1.ISearchBlurbsRequest): google.showcase.v1beta1.SearchBlurbsRequest;
/**
* Encodes the specified SearchBlurbsRequest message. Does not implicitly {@link google.showcase.v1beta1.SearchBlurbsRequest.verify|verify} messages.
* @param message SearchBlurbsRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.ISearchBlurbsRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified SearchBlurbsRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.SearchBlurbsRequest.verify|verify} messages.
* @param message SearchBlurbsRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.ISearchBlurbsRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a SearchBlurbsRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns SearchBlurbsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.SearchBlurbsRequest;
/**
* Decodes a SearchBlurbsRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns SearchBlurbsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.SearchBlurbsRequest;
/**
* Verifies a SearchBlurbsRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a SearchBlurbsRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns SearchBlurbsRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.SearchBlurbsRequest;
/**
* Creates a plain object from a SearchBlurbsRequest message. Also converts values to other types if specified.
* @param message SearchBlurbsRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.SearchBlurbsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this SearchBlurbsRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a SearchBlurbsMetadata. */
interface ISearchBlurbsMetadata {
/** SearchBlurbsMetadata retryInfo */
retryInfo?: (google.rpc.IRetryInfo|null);
}
/** Represents a SearchBlurbsMetadata. */
class SearchBlurbsMetadata implements ISearchBlurbsMetadata {
/**
* Constructs a new SearchBlurbsMetadata.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.ISearchBlurbsMetadata);
/** SearchBlurbsMetadata retryInfo. */
public retryInfo?: (google.rpc.IRetryInfo|null);
/**
* Creates a new SearchBlurbsMetadata instance using the specified properties.
* @param [properties] Properties to set
* @returns SearchBlurbsMetadata instance
*/
public static create(properties?: google.showcase.v1beta1.ISearchBlurbsMetadata): google.showcase.v1beta1.SearchBlurbsMetadata;
/**
* Encodes the specified SearchBlurbsMetadata message. Does not implicitly {@link google.showcase.v1beta1.SearchBlurbsMetadata.verify|verify} messages.
* @param message SearchBlurbsMetadata message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.ISearchBlurbsMetadata, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified SearchBlurbsMetadata message, length delimited. Does not implicitly {@link google.showcase.v1beta1.SearchBlurbsMetadata.verify|verify} messages.
* @param message SearchBlurbsMetadata message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.ISearchBlurbsMetadata, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a SearchBlurbsMetadata message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns SearchBlurbsMetadata
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.SearchBlurbsMetadata;
/**
* Decodes a SearchBlurbsMetadata message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns SearchBlurbsMetadata
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.SearchBlurbsMetadata;
/**
* Verifies a SearchBlurbsMetadata message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a SearchBlurbsMetadata message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns SearchBlurbsMetadata
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.SearchBlurbsMetadata;
/**
* Creates a plain object from a SearchBlurbsMetadata message. Also converts values to other types if specified.
* @param message SearchBlurbsMetadata
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.SearchBlurbsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this SearchBlurbsMetadata to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a SearchBlurbsResponse. */
interface ISearchBlurbsResponse {
/** SearchBlurbsResponse blurbs */
blurbs?: (google.showcase.v1beta1.IBlurb[]|null);
/** SearchBlurbsResponse nextPageToken */
nextPageToken?: (string|null);
}
/** Represents a SearchBlurbsResponse. */
class SearchBlurbsResponse implements ISearchBlurbsResponse {
/**
* Constructs a new SearchBlurbsResponse.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.ISearchBlurbsResponse);
/** SearchBlurbsResponse blurbs. */
public blurbs: google.showcase.v1beta1.IBlurb[];
/** SearchBlurbsResponse nextPageToken. */
public nextPageToken: string;
/**
* Creates a new SearchBlurbsResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns SearchBlurbsResponse instance
*/
public static create(properties?: google.showcase.v1beta1.ISearchBlurbsResponse): google.showcase.v1beta1.SearchBlurbsResponse;
/**
* Encodes the specified SearchBlurbsResponse message. Does not implicitly {@link google.showcase.v1beta1.SearchBlurbsResponse.verify|verify} messages.
* @param message SearchBlurbsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.ISearchBlurbsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified SearchBlurbsResponse message, length delimited. Does not implicitly {@link google.showcase.v1beta1.SearchBlurbsResponse.verify|verify} messages.
* @param message SearchBlurbsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.ISearchBlurbsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a SearchBlurbsResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns SearchBlurbsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.SearchBlurbsResponse;
/**
* Decodes a SearchBlurbsResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns SearchBlurbsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.SearchBlurbsResponse;
/**
* Verifies a SearchBlurbsResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a SearchBlurbsResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns SearchBlurbsResponse
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.SearchBlurbsResponse;
/**
* Creates a plain object from a SearchBlurbsResponse message. Also converts values to other types if specified.
* @param message SearchBlurbsResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.SearchBlurbsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this SearchBlurbsResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a StreamBlurbsRequest. */
interface IStreamBlurbsRequest {
/** StreamBlurbsRequest name */
name?: (string|null);
/** StreamBlurbsRequest expireTime */
expireTime?: (google.protobuf.ITimestamp|null);
}
/** Represents a StreamBlurbsRequest. */
class StreamBlurbsRequest implements IStreamBlurbsRequest {
/**
* Constructs a new StreamBlurbsRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IStreamBlurbsRequest);
/** StreamBlurbsRequest name. */
public name: string;
/** StreamBlurbsRequest expireTime. */
public expireTime?: (google.protobuf.ITimestamp|null);
/**
* Creates a new StreamBlurbsRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns StreamBlurbsRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IStreamBlurbsRequest): google.showcase.v1beta1.StreamBlurbsRequest;
/**
* Encodes the specified StreamBlurbsRequest message. Does not implicitly {@link google.showcase.v1beta1.StreamBlurbsRequest.verify|verify} messages.
* @param message StreamBlurbsRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IStreamBlurbsRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified StreamBlurbsRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.StreamBlurbsRequest.verify|verify} messages.
* @param message StreamBlurbsRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IStreamBlurbsRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a StreamBlurbsRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns StreamBlurbsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.StreamBlurbsRequest;
/**
* Decodes a StreamBlurbsRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns StreamBlurbsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.StreamBlurbsRequest;
/**
* Verifies a StreamBlurbsRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a StreamBlurbsRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns StreamBlurbsRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.StreamBlurbsRequest;
/**
* Creates a plain object from a StreamBlurbsRequest message. Also converts values to other types if specified.
* @param message StreamBlurbsRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.StreamBlurbsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this StreamBlurbsRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a StreamBlurbsResponse. */
interface IStreamBlurbsResponse {
/** StreamBlurbsResponse blurb */
blurb?: (google.showcase.v1beta1.IBlurb|null);
/** StreamBlurbsResponse action */
action?: (google.showcase.v1beta1.StreamBlurbsResponse.Action|keyof typeof google.showcase.v1beta1.StreamBlurbsResponse.Action|null);
}
/** Represents a StreamBlurbsResponse. */
class StreamBlurbsResponse implements IStreamBlurbsResponse {
/**
* Constructs a new StreamBlurbsResponse.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IStreamBlurbsResponse);
/** StreamBlurbsResponse blurb. */
public blurb?: (google.showcase.v1beta1.IBlurb|null);
/** StreamBlurbsResponse action. */
public action: (google.showcase.v1beta1.StreamBlurbsResponse.Action|keyof typeof google.showcase.v1beta1.StreamBlurbsResponse.Action);
/**
* Creates a new StreamBlurbsResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns StreamBlurbsResponse instance
*/
public static create(properties?: google.showcase.v1beta1.IStreamBlurbsResponse): google.showcase.v1beta1.StreamBlurbsResponse;
/**
* Encodes the specified StreamBlurbsResponse message. Does not implicitly {@link google.showcase.v1beta1.StreamBlurbsResponse.verify|verify} messages.
* @param message StreamBlurbsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IStreamBlurbsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified StreamBlurbsResponse message, length delimited. Does not implicitly {@link google.showcase.v1beta1.StreamBlurbsResponse.verify|verify} messages.
* @param message StreamBlurbsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IStreamBlurbsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a StreamBlurbsResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns StreamBlurbsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.StreamBlurbsResponse;
/**
* Decodes a StreamBlurbsResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns StreamBlurbsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.StreamBlurbsResponse;
/**
* Verifies a StreamBlurbsResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a StreamBlurbsResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns StreamBlurbsResponse
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.StreamBlurbsResponse;
/**
* Creates a plain object from a StreamBlurbsResponse message. Also converts values to other types if specified.
* @param message StreamBlurbsResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.StreamBlurbsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this StreamBlurbsResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace StreamBlurbsResponse {
/** Action enum. */
enum Action {
ACTION_UNSPECIFIED = 0,
CREATE = 1,
UPDATE = 2,
DELETE = 3
}
}
/** Properties of a SendBlurbsResponse. */
interface ISendBlurbsResponse {
/** SendBlurbsResponse names */
names?: (string[]|null);
}
/** Represents a SendBlurbsResponse. */
class SendBlurbsResponse implements ISendBlurbsResponse {
/**
* Constructs a new SendBlurbsResponse.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.ISendBlurbsResponse);
/** SendBlurbsResponse names. */
public names: string[];
/**
* Creates a new SendBlurbsResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns SendBlurbsResponse instance
*/
public static create(properties?: google.showcase.v1beta1.ISendBlurbsResponse): google.showcase.v1beta1.SendBlurbsResponse;
/**
* Encodes the specified SendBlurbsResponse message. Does not implicitly {@link google.showcase.v1beta1.SendBlurbsResponse.verify|verify} messages.
* @param message SendBlurbsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.ISendBlurbsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified SendBlurbsResponse message, length delimited. Does not implicitly {@link google.showcase.v1beta1.SendBlurbsResponse.verify|verify} messages.
* @param message SendBlurbsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.ISendBlurbsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a SendBlurbsResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns SendBlurbsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.SendBlurbsResponse;
/**
* Decodes a SendBlurbsResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns SendBlurbsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.SendBlurbsResponse;
/**
* Verifies a SendBlurbsResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a SendBlurbsResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns SendBlurbsResponse
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.SendBlurbsResponse;
/**
* Creates a plain object from a SendBlurbsResponse message. Also converts values to other types if specified.
* @param message SendBlurbsResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.SendBlurbsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this SendBlurbsResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConnectRequest. */
interface IConnectRequest {
/** ConnectRequest config */
config?: (google.showcase.v1beta1.ConnectRequest.IConnectConfig|null);
/** ConnectRequest blurb */
blurb?: (google.showcase.v1beta1.IBlurb|null);
}
/** Represents a ConnectRequest. */
class ConnectRequest implements IConnectRequest {
/**
* Constructs a new ConnectRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IConnectRequest);
/** ConnectRequest config. */
public config?: (google.showcase.v1beta1.ConnectRequest.IConnectConfig|null);
/** ConnectRequest blurb. */
public blurb?: (google.showcase.v1beta1.IBlurb|null);
/** ConnectRequest request. */
public request?: ("config"|"blurb");
/**
* Creates a new ConnectRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ConnectRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IConnectRequest): google.showcase.v1beta1.ConnectRequest;
/**
* Encodes the specified ConnectRequest message. Does not implicitly {@link google.showcase.v1beta1.ConnectRequest.verify|verify} messages.
* @param message ConnectRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IConnectRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConnectRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.ConnectRequest.verify|verify} messages.
* @param message ConnectRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IConnectRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConnectRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConnectRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.ConnectRequest;
/**
* Decodes a ConnectRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConnectRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.ConnectRequest;
/**
* Verifies a ConnectRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ConnectRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConnectRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.ConnectRequest;
/**
* Creates a plain object from a ConnectRequest message. Also converts values to other types if specified.
* @param message ConnectRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.ConnectRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ConnectRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace ConnectRequest {
/** Properties of a ConnectConfig. */
interface IConnectConfig {
/** ConnectConfig parent */
parent?: (string|null);
}
/** Represents a ConnectConfig. */
class ConnectConfig implements IConnectConfig {
/**
* Constructs a new ConnectConfig.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.ConnectRequest.IConnectConfig);
/** ConnectConfig parent. */
public parent: string;
/**
* Creates a new ConnectConfig instance using the specified properties.
* @param [properties] Properties to set
* @returns ConnectConfig instance
*/
public static create(properties?: google.showcase.v1beta1.ConnectRequest.IConnectConfig): google.showcase.v1beta1.ConnectRequest.ConnectConfig;
/**
* Encodes the specified ConnectConfig message. Does not implicitly {@link google.showcase.v1beta1.ConnectRequest.ConnectConfig.verify|verify} messages.
* @param message ConnectConfig message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.ConnectRequest.IConnectConfig, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConnectConfig message, length delimited. Does not implicitly {@link google.showcase.v1beta1.ConnectRequest.ConnectConfig.verify|verify} messages.
* @param message ConnectConfig message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.ConnectRequest.IConnectConfig, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConnectConfig message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConnectConfig
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.ConnectRequest.ConnectConfig;
/**
* Decodes a ConnectConfig message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConnectConfig
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.ConnectRequest.ConnectConfig;
/**
* Verifies a ConnectConfig message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ConnectConfig message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConnectConfig
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.ConnectRequest.ConnectConfig;
/**
* Creates a plain object from a ConnectConfig message. Also converts values to other types if specified.
* @param message ConnectConfig
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.ConnectRequest.ConnectConfig, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ConnectConfig to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Represents a Testing */
class Testing extends $protobuf.rpc.Service {
/**
* Constructs a new Testing service.
* @param rpcImpl RPC implementation
* @param [requestDelimited=false] Whether requests are length-delimited
* @param [responseDelimited=false] Whether responses are length-delimited
*/
constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean);
/**
* Creates new Testing service using the specified rpc implementation.
* @param rpcImpl RPC implementation
* @param [requestDelimited=false] Whether requests are length-delimited
* @param [responseDelimited=false] Whether responses are length-delimited
* @returns RPC service. Useful where requests and/or responses are streamed.
*/
public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Testing;
/**
* Calls CreateSession.
* @param request CreateSessionRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Session
*/
public createSession(request: google.showcase.v1beta1.ICreateSessionRequest, callback: google.showcase.v1beta1.Testing.CreateSessionCallback): void;
/**
* Calls CreateSession.
* @param request CreateSessionRequest message or plain object
* @returns Promise
*/
public createSession(request: google.showcase.v1beta1.ICreateSessionRequest): Promise<google.showcase.v1beta1.Session>;
/**
* Calls GetSession.
* @param request GetSessionRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Session
*/
public getSession(request: google.showcase.v1beta1.IGetSessionRequest, callback: google.showcase.v1beta1.Testing.GetSessionCallback): void;
/**
* Calls GetSession.
* @param request GetSessionRequest message or plain object
* @returns Promise
*/
public getSession(request: google.showcase.v1beta1.IGetSessionRequest): Promise<google.showcase.v1beta1.Session>;
/**
* Calls ListSessions.
* @param request ListSessionsRequest message or plain object
* @param callback Node-style callback called with the error, if any, and ListSessionsResponse
*/
public listSessions(request: google.showcase.v1beta1.IListSessionsRequest, callback: google.showcase.v1beta1.Testing.ListSessionsCallback): void;
/**
* Calls ListSessions.
* @param request ListSessionsRequest message or plain object
* @returns Promise
*/
public listSessions(request: google.showcase.v1beta1.IListSessionsRequest): Promise<google.showcase.v1beta1.ListSessionsResponse>;
/**
* Calls DeleteSession.
* @param request DeleteSessionRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Empty
*/
public deleteSession(request: google.showcase.v1beta1.IDeleteSessionRequest, callback: google.showcase.v1beta1.Testing.DeleteSessionCallback): void;
/**
* Calls DeleteSession.
* @param request DeleteSessionRequest message or plain object
* @returns Promise
*/
public deleteSession(request: google.showcase.v1beta1.IDeleteSessionRequest): Promise<google.protobuf.Empty>;
/**
* Calls ReportSession.
* @param request ReportSessionRequest message or plain object
* @param callback Node-style callback called with the error, if any, and ReportSessionResponse
*/
public reportSession(request: google.showcase.v1beta1.IReportSessionRequest, callback: google.showcase.v1beta1.Testing.ReportSessionCallback): void;
/**
* Calls ReportSession.
* @param request ReportSessionRequest message or plain object
* @returns Promise
*/
public reportSession(request: google.showcase.v1beta1.IReportSessionRequest): Promise<google.showcase.v1beta1.ReportSessionResponse>;
/**
* Calls ListTests.
* @param request ListTestsRequest message or plain object
* @param callback Node-style callback called with the error, if any, and ListTestsResponse
*/
public listTests(request: google.showcase.v1beta1.IListTestsRequest, callback: google.showcase.v1beta1.Testing.ListTestsCallback): void;
/**
* Calls ListTests.
* @param request ListTestsRequest message or plain object
* @returns Promise
*/
public listTests(request: google.showcase.v1beta1.IListTestsRequest): Promise<google.showcase.v1beta1.ListTestsResponse>;
/**
* Calls DeleteTest.
* @param request DeleteTestRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Empty
*/
public deleteTest(request: google.showcase.v1beta1.IDeleteTestRequest, callback: google.showcase.v1beta1.Testing.DeleteTestCallback): void;
/**
* Calls DeleteTest.
* @param request DeleteTestRequest message or plain object
* @returns Promise
*/
public deleteTest(request: google.showcase.v1beta1.IDeleteTestRequest): Promise<google.protobuf.Empty>;
/**
* Calls VerifyTest.
* @param request VerifyTestRequest message or plain object
* @param callback Node-style callback called with the error, if any, and VerifyTestResponse
*/
public verifyTest(request: google.showcase.v1beta1.IVerifyTestRequest, callback: google.showcase.v1beta1.Testing.VerifyTestCallback): void;
/**
* Calls VerifyTest.
* @param request VerifyTestRequest message or plain object
* @returns Promise
*/
public verifyTest(request: google.showcase.v1beta1.IVerifyTestRequest): Promise<google.showcase.v1beta1.VerifyTestResponse>;
}
namespace Testing {
/**
* Callback as used by {@link google.showcase.v1beta1.Testing#createSession}.
* @param error Error, if any
* @param [response] Session
*/
type CreateSessionCallback = (error: (Error|null), response?: google.showcase.v1beta1.Session) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Testing#getSession}.
* @param error Error, if any
* @param [response] Session
*/
type GetSessionCallback = (error: (Error|null), response?: google.showcase.v1beta1.Session) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Testing#listSessions}.
* @param error Error, if any
* @param [response] ListSessionsResponse
*/
type ListSessionsCallback = (error: (Error|null), response?: google.showcase.v1beta1.ListSessionsResponse) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Testing#deleteSession}.
* @param error Error, if any
* @param [response] Empty
*/
type DeleteSessionCallback = (error: (Error|null), response?: google.protobuf.Empty) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Testing#reportSession}.
* @param error Error, if any
* @param [response] ReportSessionResponse
*/
type ReportSessionCallback = (error: (Error|null), response?: google.showcase.v1beta1.ReportSessionResponse) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Testing#listTests}.
* @param error Error, if any
* @param [response] ListTestsResponse
*/
type ListTestsCallback = (error: (Error|null), response?: google.showcase.v1beta1.ListTestsResponse) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Testing#deleteTest}.
* @param error Error, if any
* @param [response] Empty
*/
type DeleteTestCallback = (error: (Error|null), response?: google.protobuf.Empty) => void;
/**
* Callback as used by {@link google.showcase.v1beta1.Testing#verifyTest}.
* @param error Error, if any
* @param [response] VerifyTestResponse
*/
type VerifyTestCallback = (error: (Error|null), response?: google.showcase.v1beta1.VerifyTestResponse) => void;
}
/** Properties of a Session. */
interface ISession {
/** Session name */
name?: (string|null);
/** Session version */
version?: (google.showcase.v1beta1.Session.Version|keyof typeof google.showcase.v1beta1.Session.Version|null);
}
/** Represents a Session. */
class Session implements ISession {
/**
* Constructs a new Session.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.ISession);
/** Session name. */
public name: string;
/** Session version. */
public version: (google.showcase.v1beta1.Session.Version|keyof typeof google.showcase.v1beta1.Session.Version);
/**
* Creates a new Session instance using the specified properties.
* @param [properties] Properties to set
* @returns Session instance
*/
public static create(properties?: google.showcase.v1beta1.ISession): google.showcase.v1beta1.Session;
/**
* Encodes the specified Session message. Does not implicitly {@link google.showcase.v1beta1.Session.verify|verify} messages.
* @param message Session message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.ISession, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Session message, length delimited. Does not implicitly {@link google.showcase.v1beta1.Session.verify|verify} messages.
* @param message Session message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.ISession, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Session message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Session
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.Session;
/**
* Decodes a Session message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Session
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.Session;
/**
* Verifies a Session message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Session message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Session
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.Session;
/**
* Creates a plain object from a Session message. Also converts values to other types if specified.
* @param message Session
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.Session, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Session to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace Session {
/** Version enum. */
enum Version {
VERSION_UNSPECIFIED = 0,
V1_LATEST = 1,
V1_0 = 2
}
}
/** Properties of a CreateSessionRequest. */
interface ICreateSessionRequest {
/** CreateSessionRequest session */
session?: (google.showcase.v1beta1.ISession|null);
}
/** Represents a CreateSessionRequest. */
class CreateSessionRequest implements ICreateSessionRequest {
/**
* Constructs a new CreateSessionRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.ICreateSessionRequest);
/** CreateSessionRequest session. */
public session?: (google.showcase.v1beta1.ISession|null);
/**
* Creates a new CreateSessionRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns CreateSessionRequest instance
*/
public static create(properties?: google.showcase.v1beta1.ICreateSessionRequest): google.showcase.v1beta1.CreateSessionRequest;
/**
* Encodes the specified CreateSessionRequest message. Does not implicitly {@link google.showcase.v1beta1.CreateSessionRequest.verify|verify} messages.
* @param message CreateSessionRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.ICreateSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified CreateSessionRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.CreateSessionRequest.verify|verify} messages.
* @param message CreateSessionRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.ICreateSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a CreateSessionRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns CreateSessionRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.CreateSessionRequest;
/**
* Decodes a CreateSessionRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns CreateSessionRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.CreateSessionRequest;
/**
* Verifies a CreateSessionRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a CreateSessionRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns CreateSessionRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.CreateSessionRequest;
/**
* Creates a plain object from a CreateSessionRequest message. Also converts values to other types if specified.
* @param message CreateSessionRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.CreateSessionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this CreateSessionRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a GetSessionRequest. */
interface IGetSessionRequest {
/** GetSessionRequest name */
name?: (string|null);
}
/** Represents a GetSessionRequest. */
class GetSessionRequest implements IGetSessionRequest {
/**
* Constructs a new GetSessionRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IGetSessionRequest);
/** GetSessionRequest name. */
public name: string;
/**
* Creates a new GetSessionRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns GetSessionRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IGetSessionRequest): google.showcase.v1beta1.GetSessionRequest;
/**
* Encodes the specified GetSessionRequest message. Does not implicitly {@link google.showcase.v1beta1.GetSessionRequest.verify|verify} messages.
* @param message GetSessionRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IGetSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GetSessionRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.GetSessionRequest.verify|verify} messages.
* @param message GetSessionRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IGetSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GetSessionRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GetSessionRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.GetSessionRequest;
/**
* Decodes a GetSessionRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GetSessionRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.GetSessionRequest;
/**
* Verifies a GetSessionRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a GetSessionRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GetSessionRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.GetSessionRequest;
/**
* Creates a plain object from a GetSessionRequest message. Also converts values to other types if specified.
* @param message GetSessionRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.GetSessionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this GetSessionRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ListSessionsRequest. */
interface IListSessionsRequest {
/** ListSessionsRequest pageSize */
pageSize?: (number|null);
/** ListSessionsRequest pageToken */
pageToken?: (string|null);
}
/** Represents a ListSessionsRequest. */
class ListSessionsRequest implements IListSessionsRequest {
/**
* Constructs a new ListSessionsRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IListSessionsRequest);
/** ListSessionsRequest pageSize. */
public pageSize: number;
/** ListSessionsRequest pageToken. */
public pageToken: string;
/**
* Creates a new ListSessionsRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ListSessionsRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IListSessionsRequest): google.showcase.v1beta1.ListSessionsRequest;
/**
* Encodes the specified ListSessionsRequest message. Does not implicitly {@link google.showcase.v1beta1.ListSessionsRequest.verify|verify} messages.
* @param message ListSessionsRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IListSessionsRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ListSessionsRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.ListSessionsRequest.verify|verify} messages.
* @param message ListSessionsRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IListSessionsRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ListSessionsRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ListSessionsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.ListSessionsRequest;
/**
* Decodes a ListSessionsRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ListSessionsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.ListSessionsRequest;
/**
* Verifies a ListSessionsRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ListSessionsRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ListSessionsRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.ListSessionsRequest;
/**
* Creates a plain object from a ListSessionsRequest message. Also converts values to other types if specified.
* @param message ListSessionsRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.ListSessionsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ListSessionsRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ListSessionsResponse. */
interface IListSessionsResponse {
/** ListSessionsResponse sessions */
sessions?: (google.showcase.v1beta1.ISession[]|null);
/** ListSessionsResponse nextPageToken */
nextPageToken?: (string|null);
}
/** Represents a ListSessionsResponse. */
class ListSessionsResponse implements IListSessionsResponse {
/**
* Constructs a new ListSessionsResponse.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IListSessionsResponse);
/** ListSessionsResponse sessions. */
public sessions: google.showcase.v1beta1.ISession[];
/** ListSessionsResponse nextPageToken. */
public nextPageToken: string;
/**
* Creates a new ListSessionsResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ListSessionsResponse instance
*/
public static create(properties?: google.showcase.v1beta1.IListSessionsResponse): google.showcase.v1beta1.ListSessionsResponse;
/**
* Encodes the specified ListSessionsResponse message. Does not implicitly {@link google.showcase.v1beta1.ListSessionsResponse.verify|verify} messages.
* @param message ListSessionsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IListSessionsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ListSessionsResponse message, length delimited. Does not implicitly {@link google.showcase.v1beta1.ListSessionsResponse.verify|verify} messages.
* @param message ListSessionsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IListSessionsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ListSessionsResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ListSessionsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.ListSessionsResponse;
/**
* Decodes a ListSessionsResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ListSessionsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.ListSessionsResponse;
/**
* Verifies a ListSessionsResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ListSessionsResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ListSessionsResponse
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.ListSessionsResponse;
/**
* Creates a plain object from a ListSessionsResponse message. Also converts values to other types if specified.
* @param message ListSessionsResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.ListSessionsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ListSessionsResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a DeleteSessionRequest. */
interface IDeleteSessionRequest {
/** DeleteSessionRequest name */
name?: (string|null);
}
/** Represents a DeleteSessionRequest. */
class DeleteSessionRequest implements IDeleteSessionRequest {
/**
* Constructs a new DeleteSessionRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IDeleteSessionRequest);
/** DeleteSessionRequest name. */
public name: string;
/**
* Creates a new DeleteSessionRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns DeleteSessionRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IDeleteSessionRequest): google.showcase.v1beta1.DeleteSessionRequest;
/**
* Encodes the specified DeleteSessionRequest message. Does not implicitly {@link google.showcase.v1beta1.DeleteSessionRequest.verify|verify} messages.
* @param message DeleteSessionRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IDeleteSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified DeleteSessionRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.DeleteSessionRequest.verify|verify} messages.
* @param message DeleteSessionRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IDeleteSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a DeleteSessionRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns DeleteSessionRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.DeleteSessionRequest;
/**
* Decodes a DeleteSessionRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns DeleteSessionRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.DeleteSessionRequest;
/**
* Verifies a DeleteSessionRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a DeleteSessionRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns DeleteSessionRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.DeleteSessionRequest;
/**
* Creates a plain object from a DeleteSessionRequest message. Also converts values to other types if specified.
* @param message DeleteSessionRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.DeleteSessionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this DeleteSessionRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReportSessionRequest. */
interface IReportSessionRequest {
/** ReportSessionRequest name */
name?: (string|null);
}
/** Represents a ReportSessionRequest. */
class ReportSessionRequest implements IReportSessionRequest {
/**
* Constructs a new ReportSessionRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IReportSessionRequest);
/** ReportSessionRequest name. */
public name: string;
/**
* Creates a new ReportSessionRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ReportSessionRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IReportSessionRequest): google.showcase.v1beta1.ReportSessionRequest;
/**
* Encodes the specified ReportSessionRequest message. Does not implicitly {@link google.showcase.v1beta1.ReportSessionRequest.verify|verify} messages.
* @param message ReportSessionRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IReportSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReportSessionRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.ReportSessionRequest.verify|verify} messages.
* @param message ReportSessionRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IReportSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReportSessionRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReportSessionRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.ReportSessionRequest;
/**
* Decodes a ReportSessionRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReportSessionRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.ReportSessionRequest;
/**
* Verifies a ReportSessionRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReportSessionRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReportSessionRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.ReportSessionRequest;
/**
* Creates a plain object from a ReportSessionRequest message. Also converts values to other types if specified.
* @param message ReportSessionRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.ReportSessionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReportSessionRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReportSessionResponse. */
interface IReportSessionResponse {
/** ReportSessionResponse result */
result?: (google.showcase.v1beta1.ReportSessionResponse.Result|keyof typeof google.showcase.v1beta1.ReportSessionResponse.Result|null);
/** ReportSessionResponse testRuns */
testRuns?: (google.showcase.v1beta1.ITestRun[]|null);
}
/** Represents a ReportSessionResponse. */
class ReportSessionResponse implements IReportSessionResponse {
/**
* Constructs a new ReportSessionResponse.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IReportSessionResponse);
/** ReportSessionResponse result. */
public result: (google.showcase.v1beta1.ReportSessionResponse.Result|keyof typeof google.showcase.v1beta1.ReportSessionResponse.Result);
/** ReportSessionResponse testRuns. */
public testRuns: google.showcase.v1beta1.ITestRun[];
/**
* Creates a new ReportSessionResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ReportSessionResponse instance
*/
public static create(properties?: google.showcase.v1beta1.IReportSessionResponse): google.showcase.v1beta1.ReportSessionResponse;
/**
* Encodes the specified ReportSessionResponse message. Does not implicitly {@link google.showcase.v1beta1.ReportSessionResponse.verify|verify} messages.
* @param message ReportSessionResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IReportSessionResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReportSessionResponse message, length delimited. Does not implicitly {@link google.showcase.v1beta1.ReportSessionResponse.verify|verify} messages.
* @param message ReportSessionResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IReportSessionResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReportSessionResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReportSessionResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.ReportSessionResponse;
/**
* Decodes a ReportSessionResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReportSessionResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.ReportSessionResponse;
/**
* Verifies a ReportSessionResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReportSessionResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReportSessionResponse
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.ReportSessionResponse;
/**
* Creates a plain object from a ReportSessionResponse message. Also converts values to other types if specified.
* @param message ReportSessionResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.ReportSessionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReportSessionResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace ReportSessionResponse {
/** Result enum. */
enum Result {
RESULT_UNSPECIFIED = 0,
PASSED = 1,
FAILED = 2,
INCOMPLETE = 3
}
}
/** Properties of a Test. */
interface ITest {
/** Test name */
name?: (string|null);
/** Test expectationLevel */
expectationLevel?: (google.showcase.v1beta1.Test.ExpectationLevel|keyof typeof google.showcase.v1beta1.Test.ExpectationLevel|null);
/** Test description */
description?: (string|null);
/** Test blueprints */
blueprints?: (google.showcase.v1beta1.Test.IBlueprint[]|null);
}
/** Represents a Test. */
class Test implements ITest {
/**
* Constructs a new Test.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.ITest);
/** Test name. */
public name: string;
/** Test expectationLevel. */
public expectationLevel: (google.showcase.v1beta1.Test.ExpectationLevel|keyof typeof google.showcase.v1beta1.Test.ExpectationLevel);
/** Test description. */
public description: string;
/** Test blueprints. */
public blueprints: google.showcase.v1beta1.Test.IBlueprint[];
/**
* Creates a new Test instance using the specified properties.
* @param [properties] Properties to set
* @returns Test instance
*/
public static create(properties?: google.showcase.v1beta1.ITest): google.showcase.v1beta1.Test;
/**
* Encodes the specified Test message. Does not implicitly {@link google.showcase.v1beta1.Test.verify|verify} messages.
* @param message Test message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.ITest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Test message, length delimited. Does not implicitly {@link google.showcase.v1beta1.Test.verify|verify} messages.
* @param message Test message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.ITest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Test message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Test
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.Test;
/**
* Decodes a Test message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Test
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.Test;
/**
* Verifies a Test message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Test message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Test
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.Test;
/**
* Creates a plain object from a Test message. Also converts values to other types if specified.
* @param message Test
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.Test, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Test to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace Test {
/** ExpectationLevel enum. */
enum ExpectationLevel {
EXPECTATION_LEVEL_UNSPECIFIED = 0,
REQUIRED = 1,
RECOMMENDED = 2,
OPTIONAL = 3
}
/** Properties of a Blueprint. */
interface IBlueprint {
/** Blueprint name */
name?: (string|null);
/** Blueprint description */
description?: (string|null);
/** Blueprint request */
request?: (google.showcase.v1beta1.Test.Blueprint.IInvocation|null);
/** Blueprint additionalRequests */
additionalRequests?: (google.showcase.v1beta1.Test.Blueprint.IInvocation[]|null);
}
/** Represents a Blueprint. */
class Blueprint implements IBlueprint {
/**
* Constructs a new Blueprint.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.Test.IBlueprint);
/** Blueprint name. */
public name: string;
/** Blueprint description. */
public description: string;
/** Blueprint request. */
public request?: (google.showcase.v1beta1.Test.Blueprint.IInvocation|null);
/** Blueprint additionalRequests. */
public additionalRequests: google.showcase.v1beta1.Test.Blueprint.IInvocation[];
/**
* Creates a new Blueprint instance using the specified properties.
* @param [properties] Properties to set
* @returns Blueprint instance
*/
public static create(properties?: google.showcase.v1beta1.Test.IBlueprint): google.showcase.v1beta1.Test.Blueprint;
/**
* Encodes the specified Blueprint message. Does not implicitly {@link google.showcase.v1beta1.Test.Blueprint.verify|verify} messages.
* @param message Blueprint message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.Test.IBlueprint, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Blueprint message, length delimited. Does not implicitly {@link google.showcase.v1beta1.Test.Blueprint.verify|verify} messages.
* @param message Blueprint message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.Test.IBlueprint, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Blueprint message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Blueprint
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.Test.Blueprint;
/**
* Decodes a Blueprint message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Blueprint
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.Test.Blueprint;
/**
* Verifies a Blueprint message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Blueprint message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Blueprint
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.Test.Blueprint;
/**
* Creates a plain object from a Blueprint message. Also converts values to other types if specified.
* @param message Blueprint
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.Test.Blueprint, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Blueprint to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace Blueprint {
/** Properties of an Invocation. */
interface IInvocation {
/** Invocation method */
method?: (string|null);
/** Invocation serializedRequest */
serializedRequest?: (Uint8Array|string|null);
}
/** Represents an Invocation. */
class Invocation implements IInvocation {
/**
* Constructs a new Invocation.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.Test.Blueprint.IInvocation);
/** Invocation method. */
public method: string;
/** Invocation serializedRequest. */
public serializedRequest: (Uint8Array|string);
/**
* Creates a new Invocation instance using the specified properties.
* @param [properties] Properties to set
* @returns Invocation instance
*/
public static create(properties?: google.showcase.v1beta1.Test.Blueprint.IInvocation): google.showcase.v1beta1.Test.Blueprint.Invocation;
/**
* Encodes the specified Invocation message. Does not implicitly {@link google.showcase.v1beta1.Test.Blueprint.Invocation.verify|verify} messages.
* @param message Invocation message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.Test.Blueprint.IInvocation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Invocation message, length delimited. Does not implicitly {@link google.showcase.v1beta1.Test.Blueprint.Invocation.verify|verify} messages.
* @param message Invocation message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.Test.Blueprint.IInvocation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Invocation message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Invocation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.Test.Blueprint.Invocation;
/**
* Decodes an Invocation message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Invocation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.Test.Blueprint.Invocation;
/**
* Verifies an Invocation message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Invocation message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Invocation
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.Test.Blueprint.Invocation;
/**
* Creates a plain object from an Invocation message. Also converts values to other types if specified.
* @param message Invocation
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.Test.Blueprint.Invocation, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Invocation to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
}
/** Properties of an Issue. */
interface IIssue {
/** Issue type */
type?: (google.showcase.v1beta1.Issue.Type|keyof typeof google.showcase.v1beta1.Issue.Type|null);
/** Issue severity */
severity?: (google.showcase.v1beta1.Issue.Severity|keyof typeof google.showcase.v1beta1.Issue.Severity|null);
/** Issue description */
description?: (string|null);
}
/** Represents an Issue. */
class Issue implements IIssue {
/**
* Constructs a new Issue.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IIssue);
/** Issue type. */
public type: (google.showcase.v1beta1.Issue.Type|keyof typeof google.showcase.v1beta1.Issue.Type);
/** Issue severity. */
public severity: (google.showcase.v1beta1.Issue.Severity|keyof typeof google.showcase.v1beta1.Issue.Severity);
/** Issue description. */
public description: string;
/**
* Creates a new Issue instance using the specified properties.
* @param [properties] Properties to set
* @returns Issue instance
*/
public static create(properties?: google.showcase.v1beta1.IIssue): google.showcase.v1beta1.Issue;
/**
* Encodes the specified Issue message. Does not implicitly {@link google.showcase.v1beta1.Issue.verify|verify} messages.
* @param message Issue message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IIssue, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Issue message, length delimited. Does not implicitly {@link google.showcase.v1beta1.Issue.verify|verify} messages.
* @param message Issue message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IIssue, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Issue message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Issue
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.Issue;
/**
* Decodes an Issue message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Issue
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.Issue;
/**
* Verifies an Issue message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Issue message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Issue
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.Issue;
/**
* Creates a plain object from an Issue message. Also converts values to other types if specified.
* @param message Issue
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.Issue, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Issue to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace Issue {
/** Type enum. */
enum Type {
TYPE_UNSPECIFIED = 0,
SKIPPED = 1,
PENDING = 2,
INCORRECT_CONFIRMATION = 3
}
/** Severity enum. */
enum Severity {
SEVERITY_UNSPECIFIED = 0,
ERROR = 1,
WARNING = 2
}
}
/** Properties of a ListTestsRequest. */
interface IListTestsRequest {
/** ListTestsRequest parent */
parent?: (string|null);
/** ListTestsRequest pageSize */
pageSize?: (number|null);
/** ListTestsRequest pageToken */
pageToken?: (string|null);
}
/** Represents a ListTestsRequest. */
class ListTestsRequest implements IListTestsRequest {
/**
* Constructs a new ListTestsRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IListTestsRequest);
/** ListTestsRequest parent. */
public parent: string;
/** ListTestsRequest pageSize. */
public pageSize: number;
/** ListTestsRequest pageToken. */
public pageToken: string;
/**
* Creates a new ListTestsRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ListTestsRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IListTestsRequest): google.showcase.v1beta1.ListTestsRequest;
/**
* Encodes the specified ListTestsRequest message. Does not implicitly {@link google.showcase.v1beta1.ListTestsRequest.verify|verify} messages.
* @param message ListTestsRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IListTestsRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ListTestsRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.ListTestsRequest.verify|verify} messages.
* @param message ListTestsRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IListTestsRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ListTestsRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ListTestsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.ListTestsRequest;
/**
* Decodes a ListTestsRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ListTestsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.ListTestsRequest;
/**
* Verifies a ListTestsRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ListTestsRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ListTestsRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.ListTestsRequest;
/**
* Creates a plain object from a ListTestsRequest message. Also converts values to other types if specified.
* @param message ListTestsRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.ListTestsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ListTestsRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ListTestsResponse. */
interface IListTestsResponse {
/** ListTestsResponse tests */
tests?: (google.showcase.v1beta1.ITest[]|null);
/** ListTestsResponse nextPageToken */
nextPageToken?: (string|null);
}
/** Represents a ListTestsResponse. */
class ListTestsResponse implements IListTestsResponse {
/**
* Constructs a new ListTestsResponse.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IListTestsResponse);
/** ListTestsResponse tests. */
public tests: google.showcase.v1beta1.ITest[];
/** ListTestsResponse nextPageToken. */
public nextPageToken: string;
/**
* Creates a new ListTestsResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ListTestsResponse instance
*/
public static create(properties?: google.showcase.v1beta1.IListTestsResponse): google.showcase.v1beta1.ListTestsResponse;
/**
* Encodes the specified ListTestsResponse message. Does not implicitly {@link google.showcase.v1beta1.ListTestsResponse.verify|verify} messages.
* @param message ListTestsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IListTestsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ListTestsResponse message, length delimited. Does not implicitly {@link google.showcase.v1beta1.ListTestsResponse.verify|verify} messages.
* @param message ListTestsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IListTestsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ListTestsResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ListTestsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.ListTestsResponse;
/**
* Decodes a ListTestsResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ListTestsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.ListTestsResponse;
/**
* Verifies a ListTestsResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ListTestsResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ListTestsResponse
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.ListTestsResponse;
/**
* Creates a plain object from a ListTestsResponse message. Also converts values to other types if specified.
* @param message ListTestsResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.ListTestsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ListTestsResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TestRun. */
interface ITestRun {
/** TestRun test */
test?: (string|null);
/** TestRun issue */
issue?: (google.showcase.v1beta1.IIssue|null);
}
/** Represents a TestRun. */
class TestRun implements ITestRun {
/**
* Constructs a new TestRun.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.ITestRun);
/** TestRun test. */
public test: string;
/** TestRun issue. */
public issue?: (google.showcase.v1beta1.IIssue|null);
/**
* Creates a new TestRun instance using the specified properties.
* @param [properties] Properties to set
* @returns TestRun instance
*/
public static create(properties?: google.showcase.v1beta1.ITestRun): google.showcase.v1beta1.TestRun;
/**
* Encodes the specified TestRun message. Does not implicitly {@link google.showcase.v1beta1.TestRun.verify|verify} messages.
* @param message TestRun message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.ITestRun, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TestRun message, length delimited. Does not implicitly {@link google.showcase.v1beta1.TestRun.verify|verify} messages.
* @param message TestRun message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.ITestRun, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TestRun message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TestRun
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.TestRun;
/**
* Decodes a TestRun message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TestRun
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.TestRun;
/**
* Verifies a TestRun message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a TestRun message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TestRun
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.TestRun;
/**
* Creates a plain object from a TestRun message. Also converts values to other types if specified.
* @param message TestRun
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.TestRun, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TestRun to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a DeleteTestRequest. */
interface IDeleteTestRequest {
/** DeleteTestRequest name */
name?: (string|null);
}
/** Represents a DeleteTestRequest. */
class DeleteTestRequest implements IDeleteTestRequest {
/**
* Constructs a new DeleteTestRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IDeleteTestRequest);
/** DeleteTestRequest name. */
public name: string;
/**
* Creates a new DeleteTestRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns DeleteTestRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IDeleteTestRequest): google.showcase.v1beta1.DeleteTestRequest;
/**
* Encodes the specified DeleteTestRequest message. Does not implicitly {@link google.showcase.v1beta1.DeleteTestRequest.verify|verify} messages.
* @param message DeleteTestRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IDeleteTestRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified DeleteTestRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.DeleteTestRequest.verify|verify} messages.
* @param message DeleteTestRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IDeleteTestRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a DeleteTestRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns DeleteTestRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.DeleteTestRequest;
/**
* Decodes a DeleteTestRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns DeleteTestRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.DeleteTestRequest;
/**
* Verifies a DeleteTestRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a DeleteTestRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns DeleteTestRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.DeleteTestRequest;
/**
* Creates a plain object from a DeleteTestRequest message. Also converts values to other types if specified.
* @param message DeleteTestRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.DeleteTestRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this DeleteTestRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a VerifyTestRequest. */
interface IVerifyTestRequest {
/** VerifyTestRequest name */
name?: (string|null);
/** VerifyTestRequest answer */
answer?: (Uint8Array|string|null);
/** VerifyTestRequest answers */
answers?: (Uint8Array[]|null);
}
/** Represents a VerifyTestRequest. */
class VerifyTestRequest implements IVerifyTestRequest {
/**
* Constructs a new VerifyTestRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IVerifyTestRequest);
/** VerifyTestRequest name. */
public name: string;
/** VerifyTestRequest answer. */
public answer: (Uint8Array|string);
/** VerifyTestRequest answers. */
public answers: Uint8Array[];
/**
* Creates a new VerifyTestRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns VerifyTestRequest instance
*/
public static create(properties?: google.showcase.v1beta1.IVerifyTestRequest): google.showcase.v1beta1.VerifyTestRequest;
/**
* Encodes the specified VerifyTestRequest message. Does not implicitly {@link google.showcase.v1beta1.VerifyTestRequest.verify|verify} messages.
* @param message VerifyTestRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IVerifyTestRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified VerifyTestRequest message, length delimited. Does not implicitly {@link google.showcase.v1beta1.VerifyTestRequest.verify|verify} messages.
* @param message VerifyTestRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IVerifyTestRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a VerifyTestRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns VerifyTestRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.VerifyTestRequest;
/**
* Decodes a VerifyTestRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns VerifyTestRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.VerifyTestRequest;
/**
* Verifies a VerifyTestRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a VerifyTestRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns VerifyTestRequest
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.VerifyTestRequest;
/**
* Creates a plain object from a VerifyTestRequest message. Also converts values to other types if specified.
* @param message VerifyTestRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.VerifyTestRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this VerifyTestRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a VerifyTestResponse. */
interface IVerifyTestResponse {
/** VerifyTestResponse issue */
issue?: (google.showcase.v1beta1.IIssue|null);
}
/** Represents a VerifyTestResponse. */
class VerifyTestResponse implements IVerifyTestResponse {
/**
* Constructs a new VerifyTestResponse.
* @param [properties] Properties to set
*/
constructor(properties?: google.showcase.v1beta1.IVerifyTestResponse);
/** VerifyTestResponse issue. */
public issue?: (google.showcase.v1beta1.IIssue|null);
/**
* Creates a new VerifyTestResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns VerifyTestResponse instance
*/
public static create(properties?: google.showcase.v1beta1.IVerifyTestResponse): google.showcase.v1beta1.VerifyTestResponse;
/**
* Encodes the specified VerifyTestResponse message. Does not implicitly {@link google.showcase.v1beta1.VerifyTestResponse.verify|verify} messages.
* @param message VerifyTestResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.showcase.v1beta1.IVerifyTestResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified VerifyTestResponse message, length delimited. Does not implicitly {@link google.showcase.v1beta1.VerifyTestResponse.verify|verify} messages.
* @param message VerifyTestResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.showcase.v1beta1.IVerifyTestResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a VerifyTestResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns VerifyTestResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.showcase.v1beta1.VerifyTestResponse;
/**
* Decodes a VerifyTestResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns VerifyTestResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.showcase.v1beta1.VerifyTestResponse;
/**
* Verifies a VerifyTestResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a VerifyTestResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns VerifyTestResponse
*/
public static fromObject(object: { [k: string]: any }): google.showcase.v1beta1.VerifyTestResponse;
/**
* Creates a plain object from a VerifyTestResponse message. Also converts values to other types if specified.
* @param message VerifyTestResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.showcase.v1beta1.VerifyTestResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this VerifyTestResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
}
/** Namespace api. */
namespace api {
/** Properties of a Http. */
interface IHttp {
/** Http rules */
rules?: (google.api.IHttpRule[]|null);
/** Http fullyDecodeReservedExpansion */
fullyDecodeReservedExpansion?: (boolean|null);
}
/** Represents a Http. */
class Http implements IHttp {
/**
* Constructs a new Http.
* @param [properties] Properties to set
*/
constructor(properties?: google.api.IHttp);
/** Http rules. */
public rules: google.api.IHttpRule[];
/** Http fullyDecodeReservedExpansion. */
public fullyDecodeReservedExpansion: boolean;
/**
* Creates a new Http instance using the specified properties.
* @param [properties] Properties to set
* @returns Http instance
*/
public static create(properties?: google.api.IHttp): google.api.Http;
/**
* Encodes the specified Http message. Does not implicitly {@link google.api.Http.verify|verify} messages.
* @param message Http message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Http message, length delimited. Does not implicitly {@link google.api.Http.verify|verify} messages.
* @param message Http message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Http message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Http
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Http;
/**
* Decodes a Http message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Http
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Http;
/**
* Verifies a Http message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Http message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Http
*/
public static fromObject(object: { [k: string]: any }): google.api.Http;
/**
* Creates a plain object from a Http message. Also converts values to other types if specified.
* @param message Http
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Http to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a HttpRule. */
interface IHttpRule {
/** HttpRule selector */
selector?: (string|null);
/** HttpRule get */
get?: (string|null);
/** HttpRule put */
put?: (string|null);
/** HttpRule post */
post?: (string|null);
/** HttpRule delete */
"delete"?: (string|null);
/** HttpRule patch */
patch?: (string|null);
/** HttpRule custom */
custom?: (google.api.ICustomHttpPattern|null);
/** HttpRule body */
body?: (string|null);
/** HttpRule responseBody */
responseBody?: (string|null);
/** HttpRule additionalBindings */
additionalBindings?: (google.api.IHttpRule[]|null);
}
/** Represents a HttpRule. */
class HttpRule implements IHttpRule {
/**
* Constructs a new HttpRule.
* @param [properties] Properties to set
*/
constructor(properties?: google.api.IHttpRule);
/** HttpRule selector. */
public selector: string;
/** HttpRule get. */
public get?: (string|null);
/** HttpRule put. */
public put?: (string|null);
/** HttpRule post. */
public post?: (string|null);
/** HttpRule delete. */
public delete?: (string|null);
/** HttpRule patch. */
public patch?: (string|null);
/** HttpRule custom. */
public custom?: (google.api.ICustomHttpPattern|null);
/** HttpRule body. */
public body: string;
/** HttpRule responseBody. */
public responseBody: string;
/** HttpRule additionalBindings. */
public additionalBindings: google.api.IHttpRule[];
/** HttpRule pattern. */
public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom");
/**
* Creates a new HttpRule instance using the specified properties.
* @param [properties] Properties to set
* @returns HttpRule instance
*/
public static create(properties?: google.api.IHttpRule): google.api.HttpRule;
/**
* Encodes the specified HttpRule message. Does not implicitly {@link google.api.HttpRule.verify|verify} messages.
* @param message HttpRule message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified HttpRule message, length delimited. Does not implicitly {@link google.api.HttpRule.verify|verify} messages.
* @param message HttpRule message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a HttpRule message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns HttpRule
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.HttpRule;
/**
* Decodes a HttpRule message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns HttpRule
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.HttpRule;
/**
* Verifies a HttpRule message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a HttpRule message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns HttpRule
*/
public static fromObject(object: { [k: string]: any }): google.api.HttpRule;
/**
* Creates a plain object from a HttpRule message. Also converts values to other types if specified.
* @param message HttpRule
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this HttpRule to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a CustomHttpPattern. */
interface ICustomHttpPattern {
/** CustomHttpPattern kind */
kind?: (string|null);
/** CustomHttpPattern path */
path?: (string|null);
}
/** Represents a CustomHttpPattern. */
class CustomHttpPattern implements ICustomHttpPattern {
/**
* Constructs a new CustomHttpPattern.
* @param [properties] Properties to set
*/
constructor(properties?: google.api.ICustomHttpPattern);
/** CustomHttpPattern kind. */
public kind: string;
/** CustomHttpPattern path. */
public path: string;
/**
* Creates a new CustomHttpPattern instance using the specified properties.
* @param [properties] Properties to set
* @returns CustomHttpPattern instance
*/
public static create(properties?: google.api.ICustomHttpPattern): google.api.CustomHttpPattern;
/**
* Encodes the specified CustomHttpPattern message. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages.
* @param message CustomHttpPattern message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified CustomHttpPattern message, length delimited. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages.
* @param message CustomHttpPattern message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a CustomHttpPattern message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns CustomHttpPattern
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.CustomHttpPattern;
/**
* Decodes a CustomHttpPattern message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns CustomHttpPattern
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.CustomHttpPattern;
/**
* Verifies a CustomHttpPattern message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns CustomHttpPattern
*/
public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern;
/**
* Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified.
* @param message CustomHttpPattern
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this CustomHttpPattern to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** FieldBehavior enum. */
enum FieldBehavior {
FIELD_BEHAVIOR_UNSPECIFIED = 0,
OPTIONAL = 1,
REQUIRED = 2,
OUTPUT_ONLY = 3,
INPUT_ONLY = 4,
IMMUTABLE = 5,
UNORDERED_LIST = 6,
NON_EMPTY_DEFAULT = 7
}
/** Properties of a ResourceDescriptor. */
interface IResourceDescriptor {
/** ResourceDescriptor type */
type?: (string|null);
/** ResourceDescriptor pattern */
pattern?: (string[]|null);
/** ResourceDescriptor nameField */
nameField?: (string|null);
/** ResourceDescriptor history */
history?: (google.api.ResourceDescriptor.History|keyof typeof google.api.ResourceDescriptor.History|null);
/** ResourceDescriptor plural */
plural?: (string|null);
/** ResourceDescriptor singular */
singular?: (string|null);
/** ResourceDescriptor style */
style?: (google.api.ResourceDescriptor.Style[]|null);
}
/** Represents a ResourceDescriptor. */
class ResourceDescriptor implements IResourceDescriptor {
/**
* Constructs a new ResourceDescriptor.
* @param [properties] Properties to set
*/
constructor(properties?: google.api.IResourceDescriptor);
/** ResourceDescriptor type. */
public type: string;
/** ResourceDescriptor pattern. */
public pattern: string[];
/** ResourceDescriptor nameField. */
public nameField: string;
/** ResourceDescriptor history. */
public history: (google.api.ResourceDescriptor.History|keyof typeof google.api.ResourceDescriptor.History);
/** ResourceDescriptor plural. */
public plural: string;
/** ResourceDescriptor singular. */
public singular: string;
/** ResourceDescriptor style. */
public style: google.api.ResourceDescriptor.Style[];
/**
* Creates a new ResourceDescriptor instance using the specified properties.
* @param [properties] Properties to set
* @returns ResourceDescriptor instance
*/
public static create(properties?: google.api.IResourceDescriptor): google.api.ResourceDescriptor;
/**
* Encodes the specified ResourceDescriptor message. Does not implicitly {@link google.api.ResourceDescriptor.verify|verify} messages.
* @param message ResourceDescriptor message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.api.IResourceDescriptor, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ResourceDescriptor message, length delimited. Does not implicitly {@link google.api.ResourceDescriptor.verify|verify} messages.
* @param message ResourceDescriptor message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.api.IResourceDescriptor, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ResourceDescriptor message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ResourceDescriptor
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.ResourceDescriptor;
/**
* Decodes a ResourceDescriptor message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ResourceDescriptor
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.ResourceDescriptor;
/**
* Verifies a ResourceDescriptor message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ResourceDescriptor
*/
public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor;
/**
* Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified.
* @param message ResourceDescriptor
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ResourceDescriptor to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace ResourceDescriptor {
/** History enum. */
enum History {
HISTORY_UNSPECIFIED = 0,
ORIGINALLY_SINGLE_PATTERN = 1,
FUTURE_MULTI_PATTERN = 2
}
/** Style enum. */
enum Style {
STYLE_UNSPECIFIED = 0,
DECLARATIVE_FRIENDLY = 1
}
}
/** Properties of a ResourceReference. */
interface IResourceReference {
/** ResourceReference type */
type?: (string|null);
/** ResourceReference childType */
childType?: (string|null);
}
/** Represents a ResourceReference. */
class ResourceReference implements IResourceReference {
/**
* Constructs a new ResourceReference.
* @param [properties] Properties to set
*/
constructor(properties?: google.api.IResourceReference);
/** ResourceReference type. */
public type: string;
/** ResourceReference childType. */
public childType: string;
/**
* Creates a new ResourceReference instance using the specified properties.
* @param [properties] Properties to set
* @returns ResourceReference instance
*/
public static create(properties?: google.api.IResourceReference): google.api.ResourceReference;
/**
* Encodes the specified ResourceReference message. Does not implicitly {@link google.api.ResourceReference.verify|verify} messages.
* @param message ResourceReference message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.api.IResourceReference, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ResourceReference message, length delimited. Does not implicitly {@link google.api.ResourceReference.verify|verify} messages.
* @param message ResourceReference message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.api.IResourceReference, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ResourceReference message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ResourceReference
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.ResourceReference;
/**
* Decodes a ResourceReference message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ResourceReference
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.ResourceReference;
/**
* Verifies a ResourceReference message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ResourceReference message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ResourceReference
*/
public static fromObject(object: { [k: string]: any }): google.api.ResourceReference;
/**
* Creates a plain object from a ResourceReference message. Also converts values to other types if specified.
* @param message ResourceReference
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ResourceReference to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Namespace protobuf. */
namespace protobuf {
/** Properties of a FileDescriptorSet. */
interface IFileDescriptorSet {
/** FileDescriptorSet file */
file?: (google.protobuf.IFileDescriptorProto[]|null);
}
/** Represents a FileDescriptorSet. */
class FileDescriptorSet implements IFileDescriptorSet {
/**
* Constructs a new FileDescriptorSet.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IFileDescriptorSet);
/** FileDescriptorSet file. */
public file: google.protobuf.IFileDescriptorProto[];
/**
* Creates a new FileDescriptorSet instance using the specified properties.
* @param [properties] Properties to set
* @returns FileDescriptorSet instance
*/
public static create(properties?: google.protobuf.IFileDescriptorSet): google.protobuf.FileDescriptorSet;
/**
* Encodes the specified FileDescriptorSet message. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages.
* @param message FileDescriptorSet message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified FileDescriptorSet message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages.
* @param message FileDescriptorSet message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a FileDescriptorSet message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns FileDescriptorSet
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorSet;
/**
* Decodes a FileDescriptorSet message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns FileDescriptorSet
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorSet;
/**
* Verifies a FileDescriptorSet message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns FileDescriptorSet
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet;
/**
* Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified.
* @param message FileDescriptorSet
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this FileDescriptorSet to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a FileDescriptorProto. */
interface IFileDescriptorProto {
/** FileDescriptorProto name */
name?: (string|null);
/** FileDescriptorProto package */
"package"?: (string|null);
/** FileDescriptorProto dependency */
dependency?: (string[]|null);
/** FileDescriptorProto publicDependency */
publicDependency?: (number[]|null);
/** FileDescriptorProto weakDependency */
weakDependency?: (number[]|null);
/** FileDescriptorProto messageType */
messageType?: (google.protobuf.IDescriptorProto[]|null);
/** FileDescriptorProto enumType */
enumType?: (google.protobuf.IEnumDescriptorProto[]|null);
/** FileDescriptorProto service */
service?: (google.protobuf.IServiceDescriptorProto[]|null);
/** FileDescriptorProto extension */
extension?: (google.protobuf.IFieldDescriptorProto[]|null);
/** FileDescriptorProto options */
options?: (google.protobuf.IFileOptions|null);
/** FileDescriptorProto sourceCodeInfo */
sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null);
/** FileDescriptorProto syntax */
syntax?: (string|null);
}
/** Represents a FileDescriptorProto. */
class FileDescriptorProto implements IFileDescriptorProto {
/**
* Constructs a new FileDescriptorProto.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IFileDescriptorProto);
/** FileDescriptorProto name. */
public name: string;
/** FileDescriptorProto package. */
public package: string;
/** FileDescriptorProto dependency. */
public dependency: string[];
/** FileDescriptorProto publicDependency. */
public publicDependency: number[];
/** FileDescriptorProto weakDependency. */
public weakDependency: number[];
/** FileDescriptorProto messageType. */
public messageType: google.protobuf.IDescriptorProto[];
/** FileDescriptorProto enumType. */
public enumType: google.protobuf.IEnumDescriptorProto[];
/** FileDescriptorProto service. */
public service: google.protobuf.IServiceDescriptorProto[];
/** FileDescriptorProto extension. */
public extension: google.protobuf.IFieldDescriptorProto[];
/** FileDescriptorProto options. */
public options?: (google.protobuf.IFileOptions|null);
/** FileDescriptorProto sourceCodeInfo. */
public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null);
/** FileDescriptorProto syntax. */
public syntax: string;
/**
* Creates a new FileDescriptorProto instance using the specified properties.
* @param [properties] Properties to set
* @returns FileDescriptorProto instance
*/
public static create(properties?: google.protobuf.IFileDescriptorProto): google.protobuf.FileDescriptorProto;
/**
* Encodes the specified FileDescriptorProto message. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages.
* @param message FileDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified FileDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages.
* @param message FileDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a FileDescriptorProto message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns FileDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorProto;
/**
* Decodes a FileDescriptorProto message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns FileDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorProto;
/**
* Verifies a FileDescriptorProto message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns FileDescriptorProto
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto;
/**
* Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified.
* @param message FileDescriptorProto
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this FileDescriptorProto to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a DescriptorProto. */
interface IDescriptorProto {
/** DescriptorProto name */
name?: (string|null);
/** DescriptorProto field */
field?: (google.protobuf.IFieldDescriptorProto[]|null);
/** DescriptorProto extension */
extension?: (google.protobuf.IFieldDescriptorProto[]|null);
/** DescriptorProto nestedType */
nestedType?: (google.protobuf.IDescriptorProto[]|null);
/** DescriptorProto enumType */
enumType?: (google.protobuf.IEnumDescriptorProto[]|null);
/** DescriptorProto extensionRange */
extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null);
/** DescriptorProto oneofDecl */
oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null);
/** DescriptorProto options */
options?: (google.protobuf.IMessageOptions|null);
/** DescriptorProto reservedRange */
reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null);
/** DescriptorProto reservedName */
reservedName?: (string[]|null);
}
/** Represents a DescriptorProto. */
class DescriptorProto implements IDescriptorProto {
/**
* Constructs a new DescriptorProto.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IDescriptorProto);
/** DescriptorProto name. */
public name: string;
/** DescriptorProto field. */
public field: google.protobuf.IFieldDescriptorProto[];
/** DescriptorProto extension. */
public extension: google.protobuf.IFieldDescriptorProto[];
/** DescriptorProto nestedType. */
public nestedType: google.protobuf.IDescriptorProto[];
/** DescriptorProto enumType. */
public enumType: google.protobuf.IEnumDescriptorProto[];
/** DescriptorProto extensionRange. */
public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[];
/** DescriptorProto oneofDecl. */
public oneofDecl: google.protobuf.IOneofDescriptorProto[];
/** DescriptorProto options. */
public options?: (google.protobuf.IMessageOptions|null);
/** DescriptorProto reservedRange. */
public reservedRange: google.protobuf.DescriptorProto.IReservedRange[];
/** DescriptorProto reservedName. */
public reservedName: string[];
/**
* Creates a new DescriptorProto instance using the specified properties.
* @param [properties] Properties to set
* @returns DescriptorProto instance
*/
public static create(properties?: google.protobuf.IDescriptorProto): google.protobuf.DescriptorProto;
/**
* Encodes the specified DescriptorProto message. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages.
* @param message DescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified DescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages.
* @param message DescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a DescriptorProto message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns DescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto;
/**
* Decodes a DescriptorProto message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns DescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto;
/**
* Verifies a DescriptorProto message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns DescriptorProto
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto;
/**
* Creates a plain object from a DescriptorProto message. Also converts values to other types if specified.
* @param message DescriptorProto
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this DescriptorProto to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace DescriptorProto {
/** Properties of an ExtensionRange. */
interface IExtensionRange {
/** ExtensionRange start */
start?: (number|null);
/** ExtensionRange end */
end?: (number|null);
/** ExtensionRange options */
options?: (google.protobuf.IExtensionRangeOptions|null);
}
/** Represents an ExtensionRange. */
class ExtensionRange implements IExtensionRange {
/**
* Constructs a new ExtensionRange.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange);
/** ExtensionRange start. */
public start: number;
/** ExtensionRange end. */
public end: number;
/** ExtensionRange options. */
public options?: (google.protobuf.IExtensionRangeOptions|null);
/**
* Creates a new ExtensionRange instance using the specified properties.
* @param [properties] Properties to set
* @returns ExtensionRange instance
*/
public static create(properties?: google.protobuf.DescriptorProto.IExtensionRange): google.protobuf.DescriptorProto.ExtensionRange;
/**
* Encodes the specified ExtensionRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages.
* @param message ExtensionRange message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ExtensionRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages.
* @param message ExtensionRange message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ExtensionRange message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ExtensionRange
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ExtensionRange;
/**
* Decodes an ExtensionRange message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ExtensionRange
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ExtensionRange;
/**
* Verifies an ExtensionRange message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ExtensionRange
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange;
/**
* Creates a plain object from an ExtensionRange message. Also converts values to other types if specified.
* @param message ExtensionRange
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ExtensionRange to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReservedRange. */
interface IReservedRange {
/** ReservedRange start */
start?: (number|null);
/** ReservedRange end */
end?: (number|null);
}
/** Represents a ReservedRange. */
class ReservedRange implements IReservedRange {
/**
* Constructs a new ReservedRange.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.DescriptorProto.IReservedRange);
/** ReservedRange start. */
public start: number;
/** ReservedRange end. */
public end: number;
/**
* Creates a new ReservedRange instance using the specified properties.
* @param [properties] Properties to set
* @returns ReservedRange instance
*/
public static create(properties?: google.protobuf.DescriptorProto.IReservedRange): google.protobuf.DescriptorProto.ReservedRange;
/**
* Encodes the specified ReservedRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages.
* @param message ReservedRange message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReservedRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages.
* @param message ReservedRange message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReservedRange message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReservedRange
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ReservedRange;
/**
* Decodes a ReservedRange message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReservedRange
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ReservedRange;
/**
* Verifies a ReservedRange message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReservedRange message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReservedRange
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange;
/**
* Creates a plain object from a ReservedRange message. Also converts values to other types if specified.
* @param message ReservedRange
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReservedRange to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of an ExtensionRangeOptions. */
interface IExtensionRangeOptions {
/** ExtensionRangeOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
}
/** Represents an ExtensionRangeOptions. */
class ExtensionRangeOptions implements IExtensionRangeOptions {
/**
* Constructs a new ExtensionRangeOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IExtensionRangeOptions);
/** ExtensionRangeOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new ExtensionRangeOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns ExtensionRangeOptions instance
*/
public static create(properties?: google.protobuf.IExtensionRangeOptions): google.protobuf.ExtensionRangeOptions;
/**
* Encodes the specified ExtensionRangeOptions message. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages.
* @param message ExtensionRangeOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ExtensionRangeOptions message, length delimited. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages.
* @param message ExtensionRangeOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ExtensionRangeOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ExtensionRangeOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ExtensionRangeOptions;
/**
* Decodes an ExtensionRangeOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ExtensionRangeOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ExtensionRangeOptions;
/**
* Verifies an ExtensionRangeOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ExtensionRangeOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions;
/**
* Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified.
* @param message ExtensionRangeOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ExtensionRangeOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a FieldDescriptorProto. */
interface IFieldDescriptorProto {
/** FieldDescriptorProto name */
name?: (string|null);
/** FieldDescriptorProto number */
number?: (number|null);
/** FieldDescriptorProto label */
label?: (google.protobuf.FieldDescriptorProto.Label|keyof typeof google.protobuf.FieldDescriptorProto.Label|null);
/** FieldDescriptorProto type */
type?: (google.protobuf.FieldDescriptorProto.Type|keyof typeof google.protobuf.FieldDescriptorProto.Type|null);
/** FieldDescriptorProto typeName */
typeName?: (string|null);
/** FieldDescriptorProto extendee */
extendee?: (string|null);
/** FieldDescriptorProto defaultValue */
defaultValue?: (string|null);
/** FieldDescriptorProto oneofIndex */
oneofIndex?: (number|null);
/** FieldDescriptorProto jsonName */
jsonName?: (string|null);
/** FieldDescriptorProto options */
options?: (google.protobuf.IFieldOptions|null);
/** FieldDescriptorProto proto3Optional */
proto3Optional?: (boolean|null);
}
/** Represents a FieldDescriptorProto. */
class FieldDescriptorProto implements IFieldDescriptorProto {
/**
* Constructs a new FieldDescriptorProto.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IFieldDescriptorProto);
/** FieldDescriptorProto name. */
public name: string;
/** FieldDescriptorProto number. */
public number: number;
/** FieldDescriptorProto label. */
public label: (google.protobuf.FieldDescriptorProto.Label|keyof typeof google.protobuf.FieldDescriptorProto.Label);
/** FieldDescriptorProto type. */
public type: (google.protobuf.FieldDescriptorProto.Type|keyof typeof google.protobuf.FieldDescriptorProto.Type);
/** FieldDescriptorProto typeName. */
public typeName: string;
/** FieldDescriptorProto extendee. */
public extendee: string;
/** FieldDescriptorProto defaultValue. */
public defaultValue: string;
/** FieldDescriptorProto oneofIndex. */
public oneofIndex: number;
/** FieldDescriptorProto jsonName. */
public jsonName: string;
/** FieldDescriptorProto options. */
public options?: (google.protobuf.IFieldOptions|null);
/** FieldDescriptorProto proto3Optional. */
public proto3Optional: boolean;
/**
* Creates a new FieldDescriptorProto instance using the specified properties.
* @param [properties] Properties to set
* @returns FieldDescriptorProto instance
*/
public static create(properties?: google.protobuf.IFieldDescriptorProto): google.protobuf.FieldDescriptorProto;
/**
* Encodes the specified FieldDescriptorProto message. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages.
* @param message FieldDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified FieldDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages.
* @param message FieldDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a FieldDescriptorProto message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns FieldDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldDescriptorProto;
/**
* Decodes a FieldDescriptorProto message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns FieldDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldDescriptorProto;
/**
* Verifies a FieldDescriptorProto message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns FieldDescriptorProto
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto;
/**
* Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified.
* @param message FieldDescriptorProto
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this FieldDescriptorProto to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace FieldDescriptorProto {
/** Type enum. */
enum Type {
TYPE_DOUBLE = 1,
TYPE_FLOAT = 2,
TYPE_INT64 = 3,
TYPE_UINT64 = 4,
TYPE_INT32 = 5,
TYPE_FIXED64 = 6,
TYPE_FIXED32 = 7,
TYPE_BOOL = 8,
TYPE_STRING = 9,
TYPE_GROUP = 10,
TYPE_MESSAGE = 11,
TYPE_BYTES = 12,
TYPE_UINT32 = 13,
TYPE_ENUM = 14,
TYPE_SFIXED32 = 15,
TYPE_SFIXED64 = 16,
TYPE_SINT32 = 17,
TYPE_SINT64 = 18
}
/** Label enum. */
enum Label {
LABEL_OPTIONAL = 1,
LABEL_REQUIRED = 2,
LABEL_REPEATED = 3
}
}
/** Properties of an OneofDescriptorProto. */
interface IOneofDescriptorProto {
/** OneofDescriptorProto name */
name?: (string|null);
/** OneofDescriptorProto options */
options?: (google.protobuf.IOneofOptions|null);
}
/** Represents an OneofDescriptorProto. */
class OneofDescriptorProto implements IOneofDescriptorProto {
/**
* Constructs a new OneofDescriptorProto.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IOneofDescriptorProto);
/** OneofDescriptorProto name. */
public name: string;
/** OneofDescriptorProto options. */
public options?: (google.protobuf.IOneofOptions|null);
/**
* Creates a new OneofDescriptorProto instance using the specified properties.
* @param [properties] Properties to set
* @returns OneofDescriptorProto instance
*/
public static create(properties?: google.protobuf.IOneofDescriptorProto): google.protobuf.OneofDescriptorProto;
/**
* Encodes the specified OneofDescriptorProto message. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages.
* @param message OneofDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OneofDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages.
* @param message OneofDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OneofDescriptorProto message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OneofDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofDescriptorProto;
/**
* Decodes an OneofDescriptorProto message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OneofDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofDescriptorProto;
/**
* Verifies an OneofDescriptorProto message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OneofDescriptorProto
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto;
/**
* Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified.
* @param message OneofDescriptorProto
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OneofDescriptorProto to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an EnumDescriptorProto. */
interface IEnumDescriptorProto {
/** EnumDescriptorProto name */
name?: (string|null);
/** EnumDescriptorProto value */
value?: (google.protobuf.IEnumValueDescriptorProto[]|null);
/** EnumDescriptorProto options */
options?: (google.protobuf.IEnumOptions|null);
/** EnumDescriptorProto reservedRange */
reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null);
/** EnumDescriptorProto reservedName */
reservedName?: (string[]|null);
}
/** Represents an EnumDescriptorProto. */
class EnumDescriptorProto implements IEnumDescriptorProto {
/**
* Constructs a new EnumDescriptorProto.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IEnumDescriptorProto);
/** EnumDescriptorProto name. */
public name: string;
/** EnumDescriptorProto value. */
public value: google.protobuf.IEnumValueDescriptorProto[];
/** EnumDescriptorProto options. */
public options?: (google.protobuf.IEnumOptions|null);
/** EnumDescriptorProto reservedRange. */
public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[];
/** EnumDescriptorProto reservedName. */
public reservedName: string[];
/**
* Creates a new EnumDescriptorProto instance using the specified properties.
* @param [properties] Properties to set
* @returns EnumDescriptorProto instance
*/
public static create(properties?: google.protobuf.IEnumDescriptorProto): google.protobuf.EnumDescriptorProto;
/**
* Encodes the specified EnumDescriptorProto message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages.
* @param message EnumDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified EnumDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages.
* @param message EnumDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an EnumDescriptorProto message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns EnumDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto;
/**
* Decodes an EnumDescriptorProto message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns EnumDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto;
/**
* Verifies an EnumDescriptorProto message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns EnumDescriptorProto
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto;
/**
* Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified.
* @param message EnumDescriptorProto
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this EnumDescriptorProto to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace EnumDescriptorProto {
/** Properties of an EnumReservedRange. */
interface IEnumReservedRange {
/** EnumReservedRange start */
start?: (number|null);
/** EnumReservedRange end */
end?: (number|null);
}
/** Represents an EnumReservedRange. */
class EnumReservedRange implements IEnumReservedRange {
/**
* Constructs a new EnumReservedRange.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange);
/** EnumReservedRange start. */
public start: number;
/** EnumReservedRange end. */
public end: number;
/**
* Creates a new EnumReservedRange instance using the specified properties.
* @param [properties] Properties to set
* @returns EnumReservedRange instance
*/
public static create(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange): google.protobuf.EnumDescriptorProto.EnumReservedRange;
/**
* Encodes the specified EnumReservedRange message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages.
* @param message EnumReservedRange message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified EnumReservedRange message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages.
* @param message EnumReservedRange message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an EnumReservedRange message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns EnumReservedRange
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto.EnumReservedRange;
/**
* Decodes an EnumReservedRange message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns EnumReservedRange
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto.EnumReservedRange;
/**
* Verifies an EnumReservedRange message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns EnumReservedRange
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange;
/**
* Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified.
* @param message EnumReservedRange
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this EnumReservedRange to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of an EnumValueDescriptorProto. */
interface IEnumValueDescriptorProto {
/** EnumValueDescriptorProto name */
name?: (string|null);
/** EnumValueDescriptorProto number */
number?: (number|null);
/** EnumValueDescriptorProto options */
options?: (google.protobuf.IEnumValueOptions|null);
}
/** Represents an EnumValueDescriptorProto. */
class EnumValueDescriptorProto implements IEnumValueDescriptorProto {
/**
* Constructs a new EnumValueDescriptorProto.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IEnumValueDescriptorProto);
/** EnumValueDescriptorProto name. */
public name: string;
/** EnumValueDescriptorProto number. */
public number: number;
/** EnumValueDescriptorProto options. */
public options?: (google.protobuf.IEnumValueOptions|null);
/**
* Creates a new EnumValueDescriptorProto instance using the specified properties.
* @param [properties] Properties to set
* @returns EnumValueDescriptorProto instance
*/
public static create(properties?: google.protobuf.IEnumValueDescriptorProto): google.protobuf.EnumValueDescriptorProto;
/**
* Encodes the specified EnumValueDescriptorProto message. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages.
* @param message EnumValueDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified EnumValueDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages.
* @param message EnumValueDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an EnumValueDescriptorProto message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns EnumValueDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueDescriptorProto;
/**
* Decodes an EnumValueDescriptorProto message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns EnumValueDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueDescriptorProto;
/**
* Verifies an EnumValueDescriptorProto message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns EnumValueDescriptorProto
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto;
/**
* Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified.
* @param message EnumValueDescriptorProto
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this EnumValueDescriptorProto to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ServiceDescriptorProto. */
interface IServiceDescriptorProto {
/** ServiceDescriptorProto name */
name?: (string|null);
/** ServiceDescriptorProto method */
method?: (google.protobuf.IMethodDescriptorProto[]|null);
/** ServiceDescriptorProto options */
options?: (google.protobuf.IServiceOptions|null);
}
/** Represents a ServiceDescriptorProto. */
class ServiceDescriptorProto implements IServiceDescriptorProto {
/**
* Constructs a new ServiceDescriptorProto.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IServiceDescriptorProto);
/** ServiceDescriptorProto name. */
public name: string;
/** ServiceDescriptorProto method. */
public method: google.protobuf.IMethodDescriptorProto[];
/** ServiceDescriptorProto options. */
public options?: (google.protobuf.IServiceOptions|null);
/**
* Creates a new ServiceDescriptorProto instance using the specified properties.
* @param [properties] Properties to set
* @returns ServiceDescriptorProto instance
*/
public static create(properties?: google.protobuf.IServiceDescriptorProto): google.protobuf.ServiceDescriptorProto;
/**
* Encodes the specified ServiceDescriptorProto message. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages.
* @param message ServiceDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ServiceDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages.
* @param message ServiceDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ServiceDescriptorProto message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ServiceDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceDescriptorProto;
/**
* Decodes a ServiceDescriptorProto message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ServiceDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceDescriptorProto;
/**
* Verifies a ServiceDescriptorProto message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ServiceDescriptorProto
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto;
/**
* Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified.
* @param message ServiceDescriptorProto
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ServiceDescriptorProto to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a MethodDescriptorProto. */
interface IMethodDescriptorProto {
/** MethodDescriptorProto name */
name?: (string|null);
/** MethodDescriptorProto inputType */
inputType?: (string|null);
/** MethodDescriptorProto outputType */
outputType?: (string|null);
/** MethodDescriptorProto options */
options?: (google.protobuf.IMethodOptions|null);
/** MethodDescriptorProto clientStreaming */
clientStreaming?: (boolean|null);
/** MethodDescriptorProto serverStreaming */
serverStreaming?: (boolean|null);
}
/** Represents a MethodDescriptorProto. */
class MethodDescriptorProto implements IMethodDescriptorProto {
/**
* Constructs a new MethodDescriptorProto.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IMethodDescriptorProto);
/** MethodDescriptorProto name. */
public name: string;
/** MethodDescriptorProto inputType. */
public inputType: string;
/** MethodDescriptorProto outputType. */
public outputType: string;
/** MethodDescriptorProto options. */
public options?: (google.protobuf.IMethodOptions|null);
/** MethodDescriptorProto clientStreaming. */
public clientStreaming: boolean;
/** MethodDescriptorProto serverStreaming. */
public serverStreaming: boolean;
/**
* Creates a new MethodDescriptorProto instance using the specified properties.
* @param [properties] Properties to set
* @returns MethodDescriptorProto instance
*/
public static create(properties?: google.protobuf.IMethodDescriptorProto): google.protobuf.MethodDescriptorProto;
/**
* Encodes the specified MethodDescriptorProto message. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages.
* @param message MethodDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified MethodDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages.
* @param message MethodDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a MethodDescriptorProto message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns MethodDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodDescriptorProto;
/**
* Decodes a MethodDescriptorProto message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns MethodDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodDescriptorProto;
/**
* Verifies a MethodDescriptorProto message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns MethodDescriptorProto
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto;
/**
* Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified.
* @param message MethodDescriptorProto
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this MethodDescriptorProto to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a FileOptions. */
interface IFileOptions {
/** FileOptions javaPackage */
javaPackage?: (string|null);
/** FileOptions javaOuterClassname */
javaOuterClassname?: (string|null);
/** FileOptions javaMultipleFiles */
javaMultipleFiles?: (boolean|null);
/** FileOptions javaGenerateEqualsAndHash */
javaGenerateEqualsAndHash?: (boolean|null);
/** FileOptions javaStringCheckUtf8 */
javaStringCheckUtf8?: (boolean|null);
/** FileOptions optimizeFor */
optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|keyof typeof google.protobuf.FileOptions.OptimizeMode|null);
/** FileOptions goPackage */
goPackage?: (string|null);
/** FileOptions ccGenericServices */
ccGenericServices?: (boolean|null);
/** FileOptions javaGenericServices */
javaGenericServices?: (boolean|null);
/** FileOptions pyGenericServices */
pyGenericServices?: (boolean|null);
/** FileOptions phpGenericServices */
phpGenericServices?: (boolean|null);
/** FileOptions deprecated */
deprecated?: (boolean|null);
/** FileOptions ccEnableArenas */
ccEnableArenas?: (boolean|null);
/** FileOptions objcClassPrefix */
objcClassPrefix?: (string|null);
/** FileOptions csharpNamespace */
csharpNamespace?: (string|null);
/** FileOptions swiftPrefix */
swiftPrefix?: (string|null);
/** FileOptions phpClassPrefix */
phpClassPrefix?: (string|null);
/** FileOptions phpNamespace */
phpNamespace?: (string|null);
/** FileOptions phpMetadataNamespace */
phpMetadataNamespace?: (string|null);
/** FileOptions rubyPackage */
rubyPackage?: (string|null);
/** FileOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
/** FileOptions .google.api.resourceDefinition */
".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null);
}
/** Represents a FileOptions. */
class FileOptions implements IFileOptions {
/**
* Constructs a new FileOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IFileOptions);
/** FileOptions javaPackage. */
public javaPackage: string;
/** FileOptions javaOuterClassname. */
public javaOuterClassname: string;
/** FileOptions javaMultipleFiles. */
public javaMultipleFiles: boolean;
/** FileOptions javaGenerateEqualsAndHash. */
public javaGenerateEqualsAndHash: boolean;
/** FileOptions javaStringCheckUtf8. */
public javaStringCheckUtf8: boolean;
/** FileOptions optimizeFor. */
public optimizeFor: (google.protobuf.FileOptions.OptimizeMode|keyof typeof google.protobuf.FileOptions.OptimizeMode);
/** FileOptions goPackage. */
public goPackage: string;
/** FileOptions ccGenericServices. */
public ccGenericServices: boolean;
/** FileOptions javaGenericServices. */
public javaGenericServices: boolean;
/** FileOptions pyGenericServices. */
public pyGenericServices: boolean;
/** FileOptions phpGenericServices. */
public phpGenericServices: boolean;
/** FileOptions deprecated. */
public deprecated: boolean;
/** FileOptions ccEnableArenas. */
public ccEnableArenas: boolean;
/** FileOptions objcClassPrefix. */
public objcClassPrefix: string;
/** FileOptions csharpNamespace. */
public csharpNamespace: string;
/** FileOptions swiftPrefix. */
public swiftPrefix: string;
/** FileOptions phpClassPrefix. */
public phpClassPrefix: string;
/** FileOptions phpNamespace. */
public phpNamespace: string;
/** FileOptions phpMetadataNamespace. */
public phpMetadataNamespace: string;
/** FileOptions rubyPackage. */
public rubyPackage: string;
/** FileOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new FileOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns FileOptions instance
*/
public static create(properties?: google.protobuf.IFileOptions): google.protobuf.FileOptions;
/**
* Encodes the specified FileOptions message. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages.
* @param message FileOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified FileOptions message, length delimited. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages.
* @param message FileOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a FileOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns FileOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileOptions;
/**
* Decodes a FileOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns FileOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileOptions;
/**
* Verifies a FileOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a FileOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns FileOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions;
/**
* Creates a plain object from a FileOptions message. Also converts values to other types if specified.
* @param message FileOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this FileOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace FileOptions {
/** OptimizeMode enum. */
enum OptimizeMode {
SPEED = 1,
CODE_SIZE = 2,
LITE_RUNTIME = 3
}
}
/** Properties of a MessageOptions. */
interface IMessageOptions {
/** MessageOptions messageSetWireFormat */
messageSetWireFormat?: (boolean|null);
/** MessageOptions noStandardDescriptorAccessor */
noStandardDescriptorAccessor?: (boolean|null);
/** MessageOptions deprecated */
deprecated?: (boolean|null);
/** MessageOptions mapEntry */
mapEntry?: (boolean|null);
/** MessageOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
/** MessageOptions .google.api.resource */
".google.api.resource"?: (google.api.IResourceDescriptor|null);
}
/** Represents a MessageOptions. */
class MessageOptions implements IMessageOptions {
/**
* Constructs a new MessageOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IMessageOptions);
/** MessageOptions messageSetWireFormat. */
public messageSetWireFormat: boolean;
/** MessageOptions noStandardDescriptorAccessor. */
public noStandardDescriptorAccessor: boolean;
/** MessageOptions deprecated. */
public deprecated: boolean;
/** MessageOptions mapEntry. */
public mapEntry: boolean;
/** MessageOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new MessageOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns MessageOptions instance
*/
public static create(properties?: google.protobuf.IMessageOptions): google.protobuf.MessageOptions;
/**
* Encodes the specified MessageOptions message. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages.
* @param message MessageOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified MessageOptions message, length delimited. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages.
* @param message MessageOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a MessageOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns MessageOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MessageOptions;
/**
* Decodes a MessageOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns MessageOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MessageOptions;
/**
* Verifies a MessageOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a MessageOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns MessageOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions;
/**
* Creates a plain object from a MessageOptions message. Also converts values to other types if specified.
* @param message MessageOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this MessageOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a FieldOptions. */
interface IFieldOptions {
/** FieldOptions ctype */
ctype?: (google.protobuf.FieldOptions.CType|keyof typeof google.protobuf.FieldOptions.CType|null);
/** FieldOptions packed */
packed?: (boolean|null);
/** FieldOptions jstype */
jstype?: (google.protobuf.FieldOptions.JSType|keyof typeof google.protobuf.FieldOptions.JSType|null);
/** FieldOptions lazy */
lazy?: (boolean|null);
/** FieldOptions deprecated */
deprecated?: (boolean|null);
/** FieldOptions weak */
weak?: (boolean|null);
/** FieldOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
/** FieldOptions .google.api.fieldBehavior */
".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null);
/** FieldOptions .google.api.resourceReference */
".google.api.resourceReference"?: (google.api.IResourceReference|null);
}
/** Represents a FieldOptions. */
class FieldOptions implements IFieldOptions {
/**
* Constructs a new FieldOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IFieldOptions);
/** FieldOptions ctype. */
public ctype: (google.protobuf.FieldOptions.CType|keyof typeof google.protobuf.FieldOptions.CType);
/** FieldOptions packed. */
public packed: boolean;
/** FieldOptions jstype. */
public jstype: (google.protobuf.FieldOptions.JSType|keyof typeof google.protobuf.FieldOptions.JSType);
/** FieldOptions lazy. */
public lazy: boolean;
/** FieldOptions deprecated. */
public deprecated: boolean;
/** FieldOptions weak. */
public weak: boolean;
/** FieldOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new FieldOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns FieldOptions instance
*/
public static create(properties?: google.protobuf.IFieldOptions): google.protobuf.FieldOptions;
/**
* Encodes the specified FieldOptions message. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages.
* @param message FieldOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified FieldOptions message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages.
* @param message FieldOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a FieldOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns FieldOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions;
/**
* Decodes a FieldOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns FieldOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions;
/**
* Verifies a FieldOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a FieldOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns FieldOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions;
/**
* Creates a plain object from a FieldOptions message. Also converts values to other types if specified.
* @param message FieldOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this FieldOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace FieldOptions {
/** CType enum. */
enum CType {
STRING = 0,
CORD = 1,
STRING_PIECE = 2
}
/** JSType enum. */
enum JSType {
JS_NORMAL = 0,
JS_STRING = 1,
JS_NUMBER = 2
}
}
/** Properties of an OneofOptions. */
interface IOneofOptions {
/** OneofOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
}
/** Represents an OneofOptions. */
class OneofOptions implements IOneofOptions {
/**
* Constructs a new OneofOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IOneofOptions);
/** OneofOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new OneofOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns OneofOptions instance
*/
public static create(properties?: google.protobuf.IOneofOptions): google.protobuf.OneofOptions;
/**
* Encodes the specified OneofOptions message. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages.
* @param message OneofOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OneofOptions message, length delimited. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages.
* @param message OneofOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OneofOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OneofOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofOptions;
/**
* Decodes an OneofOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OneofOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofOptions;
/**
* Verifies an OneofOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OneofOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OneofOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions;
/**
* Creates a plain object from an OneofOptions message. Also converts values to other types if specified.
* @param message OneofOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OneofOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an EnumOptions. */
interface IEnumOptions {
/** EnumOptions allowAlias */
allowAlias?: (boolean|null);
/** EnumOptions deprecated */
deprecated?: (boolean|null);
/** EnumOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
}
/** Represents an EnumOptions. */
class EnumOptions implements IEnumOptions {
/**
* Constructs a new EnumOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IEnumOptions);
/** EnumOptions allowAlias. */
public allowAlias: boolean;
/** EnumOptions deprecated. */
public deprecated: boolean;
/** EnumOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new EnumOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns EnumOptions instance
*/
public static create(properties?: google.protobuf.IEnumOptions): google.protobuf.EnumOptions;
/**
* Encodes the specified EnumOptions message. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages.
* @param message EnumOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified EnumOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages.
* @param message EnumOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an EnumOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns EnumOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumOptions;
/**
* Decodes an EnumOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns EnumOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumOptions;
/**
* Verifies an EnumOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an EnumOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns EnumOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions;
/**
* Creates a plain object from an EnumOptions message. Also converts values to other types if specified.
* @param message EnumOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this EnumOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an EnumValueOptions. */
interface IEnumValueOptions {
/** EnumValueOptions deprecated */
deprecated?: (boolean|null);
/** EnumValueOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
}
/** Represents an EnumValueOptions. */
class EnumValueOptions implements IEnumValueOptions {
/**
* Constructs a new EnumValueOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IEnumValueOptions);
/** EnumValueOptions deprecated. */
public deprecated: boolean;
/** EnumValueOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new EnumValueOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns EnumValueOptions instance
*/
public static create(properties?: google.protobuf.IEnumValueOptions): google.protobuf.EnumValueOptions;
/**
* Encodes the specified EnumValueOptions message. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages.
* @param message EnumValueOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified EnumValueOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages.
* @param message EnumValueOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an EnumValueOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns EnumValueOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueOptions;
/**
* Decodes an EnumValueOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns EnumValueOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueOptions;
/**
* Verifies an EnumValueOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns EnumValueOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions;
/**
* Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified.
* @param message EnumValueOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this EnumValueOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ServiceOptions. */
interface IServiceOptions {
/** ServiceOptions deprecated */
deprecated?: (boolean|null);
/** ServiceOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
/** ServiceOptions .google.api.defaultHost */
".google.api.defaultHost"?: (string|null);
/** ServiceOptions .google.api.oauthScopes */
".google.api.oauthScopes"?: (string|null);
}
/** Represents a ServiceOptions. */
class ServiceOptions implements IServiceOptions {
/**
* Constructs a new ServiceOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IServiceOptions);
/** ServiceOptions deprecated. */
public deprecated: boolean;
/** ServiceOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new ServiceOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns ServiceOptions instance
*/
public static create(properties?: google.protobuf.IServiceOptions): google.protobuf.ServiceOptions;
/**
* Encodes the specified ServiceOptions message. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages.
* @param message ServiceOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ServiceOptions message, length delimited. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages.
* @param message ServiceOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ServiceOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ServiceOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceOptions;
/**
* Decodes a ServiceOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ServiceOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceOptions;
/**
* Verifies a ServiceOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ServiceOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions;
/**
* Creates a plain object from a ServiceOptions message. Also converts values to other types if specified.
* @param message ServiceOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ServiceOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a MethodOptions. */
interface IMethodOptions {
/** MethodOptions deprecated */
deprecated?: (boolean|null);
/** MethodOptions idempotencyLevel */
idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|keyof typeof google.protobuf.MethodOptions.IdempotencyLevel|null);
/** MethodOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
/** MethodOptions .google.api.http */
".google.api.http"?: (google.api.IHttpRule|null);
/** MethodOptions .google.api.methodSignature */
".google.api.methodSignature"?: (string[]|null);
/** MethodOptions .google.longrunning.operationInfo */
".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null);
}
/** Represents a MethodOptions. */
class MethodOptions implements IMethodOptions {
/**
* Constructs a new MethodOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IMethodOptions);
/** MethodOptions deprecated. */
public deprecated: boolean;
/** MethodOptions idempotencyLevel. */
public idempotencyLevel: (google.protobuf.MethodOptions.IdempotencyLevel|keyof typeof google.protobuf.MethodOptions.IdempotencyLevel);
/** MethodOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new MethodOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns MethodOptions instance
*/
public static create(properties?: google.protobuf.IMethodOptions): google.protobuf.MethodOptions;
/**
* Encodes the specified MethodOptions message. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages.
* @param message MethodOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified MethodOptions message, length delimited. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages.
* @param message MethodOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a MethodOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns MethodOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodOptions;
/**
* Decodes a MethodOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns MethodOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodOptions;
/**
* Verifies a MethodOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a MethodOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns MethodOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions;
/**
* Creates a plain object from a MethodOptions message. Also converts values to other types if specified.
* @param message MethodOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this MethodOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace MethodOptions {
/** IdempotencyLevel enum. */
enum IdempotencyLevel {
IDEMPOTENCY_UNKNOWN = 0,
NO_SIDE_EFFECTS = 1,
IDEMPOTENT = 2
}
}
/** Properties of an UninterpretedOption. */
interface IUninterpretedOption {
/** UninterpretedOption name */
name?: (google.protobuf.UninterpretedOption.INamePart[]|null);
/** UninterpretedOption identifierValue */
identifierValue?: (string|null);
/** UninterpretedOption positiveIntValue */
positiveIntValue?: (number|Long|string|null);
/** UninterpretedOption negativeIntValue */
negativeIntValue?: (number|Long|string|null);
/** UninterpretedOption doubleValue */
doubleValue?: (number|null);
/** UninterpretedOption stringValue */
stringValue?: (Uint8Array|string|null);
/** UninterpretedOption aggregateValue */
aggregateValue?: (string|null);
}
/** Represents an UninterpretedOption. */
class UninterpretedOption implements IUninterpretedOption {
/**
* Constructs a new UninterpretedOption.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IUninterpretedOption);
/** UninterpretedOption name. */
public name: google.protobuf.UninterpretedOption.INamePart[];
/** UninterpretedOption identifierValue. */
public identifierValue: string;
/** UninterpretedOption positiveIntValue. */
public positiveIntValue: (number|Long|string);
/** UninterpretedOption negativeIntValue. */
public negativeIntValue: (number|Long|string);
/** UninterpretedOption doubleValue. */
public doubleValue: number;
/** UninterpretedOption stringValue. */
public stringValue: (Uint8Array|string);
/** UninterpretedOption aggregateValue. */
public aggregateValue: string;
/**
* Creates a new UninterpretedOption instance using the specified properties.
* @param [properties] Properties to set
* @returns UninterpretedOption instance
*/
public static create(properties?: google.protobuf.IUninterpretedOption): google.protobuf.UninterpretedOption;
/**
* Encodes the specified UninterpretedOption message. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages.
* @param message UninterpretedOption message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified UninterpretedOption message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages.
* @param message UninterpretedOption message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an UninterpretedOption message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns UninterpretedOption
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption;
/**
* Decodes an UninterpretedOption message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns UninterpretedOption
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption;
/**
* Verifies an UninterpretedOption message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns UninterpretedOption
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption;
/**
* Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified.
* @param message UninterpretedOption
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this UninterpretedOption to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace UninterpretedOption {
/** Properties of a NamePart. */
interface INamePart {
/** NamePart namePart */
namePart: string;
/** NamePart isExtension */
isExtension: boolean;
}
/** Represents a NamePart. */
class NamePart implements INamePart {
/**
* Constructs a new NamePart.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.UninterpretedOption.INamePart);
/** NamePart namePart. */
public namePart: string;
/** NamePart isExtension. */
public isExtension: boolean;
/**
* Creates a new NamePart instance using the specified properties.
* @param [properties] Properties to set
* @returns NamePart instance
*/
public static create(properties?: google.protobuf.UninterpretedOption.INamePart): google.protobuf.UninterpretedOption.NamePart;
/**
* Encodes the specified NamePart message. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages.
* @param message NamePart message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified NamePart message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages.
* @param message NamePart message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a NamePart message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns NamePart
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption.NamePart;
/**
* Decodes a NamePart message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns NamePart
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption.NamePart;
/**
* Verifies a NamePart message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a NamePart message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns NamePart
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart;
/**
* Creates a plain object from a NamePart message. Also converts values to other types if specified.
* @param message NamePart
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this NamePart to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a SourceCodeInfo. */
interface ISourceCodeInfo {
/** SourceCodeInfo location */
location?: (google.protobuf.SourceCodeInfo.ILocation[]|null);
}
/** Represents a SourceCodeInfo. */
class SourceCodeInfo implements ISourceCodeInfo {
/**
* Constructs a new SourceCodeInfo.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.ISourceCodeInfo);
/** SourceCodeInfo location. */
public location: google.protobuf.SourceCodeInfo.ILocation[];
/**
* Creates a new SourceCodeInfo instance using the specified properties.
* @param [properties] Properties to set
* @returns SourceCodeInfo instance
*/
public static create(properties?: google.protobuf.ISourceCodeInfo): google.protobuf.SourceCodeInfo;
/**
* Encodes the specified SourceCodeInfo message. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages.
* @param message SourceCodeInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified SourceCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages.
* @param message SourceCodeInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a SourceCodeInfo message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns SourceCodeInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo;
/**
* Decodes a SourceCodeInfo message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns SourceCodeInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo;
/**
* Verifies a SourceCodeInfo message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns SourceCodeInfo
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo;
/**
* Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified.
* @param message SourceCodeInfo
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this SourceCodeInfo to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace SourceCodeInfo {
/** Properties of a Location. */
interface ILocation {
/** Location path */
path?: (number[]|null);
/** Location span */
span?: (number[]|null);
/** Location leadingComments */
leadingComments?: (string|null);
/** Location trailingComments */
trailingComments?: (string|null);
/** Location leadingDetachedComments */
leadingDetachedComments?: (string[]|null);
}
/** Represents a Location. */
class Location implements ILocation {
/**
* Constructs a new Location.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.SourceCodeInfo.ILocation);
/** Location path. */
public path: number[];
/** Location span. */
public span: number[];
/** Location leadingComments. */
public leadingComments: string;
/** Location trailingComments. */
public trailingComments: string;
/** Location leadingDetachedComments. */
public leadingDetachedComments: string[];
/**
* Creates a new Location instance using the specified properties.
* @param [properties] Properties to set
* @returns Location instance
*/
public static create(properties?: google.protobuf.SourceCodeInfo.ILocation): google.protobuf.SourceCodeInfo.Location;
/**
* Encodes the specified Location message. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages.
* @param message Location message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Location message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages.
* @param message Location message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Location message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Location
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo.Location;
/**
* Decodes a Location message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Location
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo.Location;
/**
* Verifies a Location message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Location message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Location
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location;
/**
* Creates a plain object from a Location message. Also converts values to other types if specified.
* @param message Location
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Location to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a GeneratedCodeInfo. */
interface IGeneratedCodeInfo {
/** GeneratedCodeInfo annotation */
annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null);
}
/** Represents a GeneratedCodeInfo. */
class GeneratedCodeInfo implements IGeneratedCodeInfo {
/**
* Constructs a new GeneratedCodeInfo.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IGeneratedCodeInfo);
/** GeneratedCodeInfo annotation. */
public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[];
/**
* Creates a new GeneratedCodeInfo instance using the specified properties.
* @param [properties] Properties to set
* @returns GeneratedCodeInfo instance
*/
public static create(properties?: google.protobuf.IGeneratedCodeInfo): google.protobuf.GeneratedCodeInfo;
/**
* Encodes the specified GeneratedCodeInfo message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages.
* @param message GeneratedCodeInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GeneratedCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages.
* @param message GeneratedCodeInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GeneratedCodeInfo message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GeneratedCodeInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo;
/**
* Decodes a GeneratedCodeInfo message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GeneratedCodeInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo;
/**
* Verifies a GeneratedCodeInfo message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GeneratedCodeInfo
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo;
/**
* Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified.
* @param message GeneratedCodeInfo
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this GeneratedCodeInfo to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace GeneratedCodeInfo {
/** Properties of an Annotation. */
interface IAnnotation {
/** Annotation path */
path?: (number[]|null);
/** Annotation sourceFile */
sourceFile?: (string|null);
/** Annotation begin */
begin?: (number|null);
/** Annotation end */
end?: (number|null);
}
/** Represents an Annotation. */
class Annotation implements IAnnotation {
/**
* Constructs a new Annotation.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation);
/** Annotation path. */
public path: number[];
/** Annotation sourceFile. */
public sourceFile: string;
/** Annotation begin. */
public begin: number;
/** Annotation end. */
public end: number;
/**
* Creates a new Annotation instance using the specified properties.
* @param [properties] Properties to set
* @returns Annotation instance
*/
public static create(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation): google.protobuf.GeneratedCodeInfo.Annotation;
/**
* Encodes the specified Annotation message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages.
* @param message Annotation message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Annotation message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages.
* @param message Annotation message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Annotation message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Annotation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo.Annotation;
/**
* Decodes an Annotation message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Annotation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo.Annotation;
/**
* Verifies an Annotation message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Annotation message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Annotation
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation;
/**
* Creates a plain object from an Annotation message. Also converts values to other types if specified.
* @param message Annotation
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Annotation to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of an Any. */
interface IAny {
/** Any type_url */
type_url?: (string|null);
/** Any value */
value?: (Uint8Array|string|null);
}
/** Represents an Any. */
class Any implements IAny {
/**
* Constructs a new Any.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IAny);
/** Any type_url. */
public type_url: string;
/** Any value. */
public value: (Uint8Array|string);
/**
* Creates a new Any instance using the specified properties.
* @param [properties] Properties to set
* @returns Any instance
*/
public static create(properties?: google.protobuf.IAny): google.protobuf.Any;
/**
* Encodes the specified Any message. Does not implicitly {@link google.protobuf.Any.verify|verify} messages.
* @param message Any message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Any message, length delimited. Does not implicitly {@link google.protobuf.Any.verify|verify} messages.
* @param message Any message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Any message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Any
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Any;
/**
* Decodes an Any message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Any
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Any;
/**
* Verifies an Any message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Any message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Any
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.Any;
/**
* Creates a plain object from an Any message. Also converts values to other types if specified.
* @param message Any
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Any to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Duration. */
interface IDuration {
/** Duration seconds */
seconds?: (number|Long|string|null);
/** Duration nanos */
nanos?: (number|null);
}
/** Represents a Duration. */
class Duration implements IDuration {
/**
* Constructs a new Duration.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IDuration);
/** Duration seconds. */
public seconds: (number|Long|string);
/** Duration nanos. */
public nanos: number;
/**
* Creates a new Duration instance using the specified properties.
* @param [properties] Properties to set
* @returns Duration instance
*/
public static create(properties?: google.protobuf.IDuration): google.protobuf.Duration;
/**
* Encodes the specified Duration message. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages.
* @param message Duration message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IDuration, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Duration message, length delimited. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages.
* @param message Duration message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IDuration, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Duration message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Duration
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Duration;
/**
* Decodes a Duration message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Duration
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Duration;
/**
* Verifies a Duration message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Duration message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Duration
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.Duration;
/**
* Creates a plain object from a Duration message. Also converts values to other types if specified.
* @param message Duration
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Duration to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an Empty. */
interface IEmpty {
}
/** Represents an Empty. */
class Empty implements IEmpty {
/**
* Constructs a new Empty.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IEmpty);
/**
* Creates a new Empty instance using the specified properties.
* @param [properties] Properties to set
* @returns Empty instance
*/
public static create(properties?: google.protobuf.IEmpty): google.protobuf.Empty;
/**
* Encodes the specified Empty message. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages.
* @param message Empty message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IEmpty, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Empty message, length delimited. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages.
* @param message Empty message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IEmpty, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Empty message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Empty
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Empty;
/**
* Decodes an Empty message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Empty
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Empty;
/**
* Verifies an Empty message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Empty message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Empty
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.Empty;
/**
* Creates a plain object from an Empty message. Also converts values to other types if specified.
* @param message Empty
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Empty to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Timestamp. */
interface ITimestamp {
/** Timestamp seconds */
seconds?: (number|Long|string|null);
/** Timestamp nanos */
nanos?: (number|null);
}
/** Represents a Timestamp. */
class Timestamp implements ITimestamp {
/**
* Constructs a new Timestamp.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.ITimestamp);
/** Timestamp seconds. */
public seconds: (number|Long|string);
/** Timestamp nanos. */
public nanos: number;
/**
* Creates a new Timestamp instance using the specified properties.
* @param [properties] Properties to set
* @returns Timestamp instance
*/
public static create(properties?: google.protobuf.ITimestamp): google.protobuf.Timestamp;
/**
* Encodes the specified Timestamp message. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages.
* @param message Timestamp message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.ITimestamp, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Timestamp message, length delimited. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages.
* @param message Timestamp message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.ITimestamp, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Timestamp message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Timestamp
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Timestamp;
/**
* Decodes a Timestamp message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Timestamp
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Timestamp;
/**
* Verifies a Timestamp message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Timestamp message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Timestamp
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp;
/**
* Creates a plain object from a Timestamp message. Also converts values to other types if specified.
* @param message Timestamp
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Timestamp to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a FieldMask. */
interface IFieldMask {
/** FieldMask paths */
paths?: (string[]|null);
}
/** Represents a FieldMask. */
class FieldMask implements IFieldMask {
/**
* Constructs a new FieldMask.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IFieldMask);
/** FieldMask paths. */
public paths: string[];
/**
* Creates a new FieldMask instance using the specified properties.
* @param [properties] Properties to set
* @returns FieldMask instance
*/
public static create(properties?: google.protobuf.IFieldMask): google.protobuf.FieldMask;
/**
* Encodes the specified FieldMask message. Does not implicitly {@link google.protobuf.FieldMask.verify|verify} messages.
* @param message FieldMask message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IFieldMask, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified FieldMask message, length delimited. Does not implicitly {@link google.protobuf.FieldMask.verify|verify} messages.
* @param message FieldMask message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IFieldMask, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a FieldMask message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns FieldMask
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldMask;
/**
* Decodes a FieldMask message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns FieldMask
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldMask;
/**
* Verifies a FieldMask message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a FieldMask message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns FieldMask
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask;
/**
* Creates a plain object from a FieldMask message. Also converts values to other types if specified.
* @param message FieldMask
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this FieldMask to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Namespace longrunning. */
namespace longrunning {
/** Represents an Operations */
class Operations extends $protobuf.rpc.Service {
/**
* Constructs a new Operations service.
* @param rpcImpl RPC implementation
* @param [requestDelimited=false] Whether requests are length-delimited
* @param [responseDelimited=false] Whether responses are length-delimited
*/
constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean);
/**
* Creates new Operations service using the specified rpc implementation.
* @param rpcImpl RPC implementation
* @param [requestDelimited=false] Whether requests are length-delimited
* @param [responseDelimited=false] Whether responses are length-delimited
* @returns RPC service. Useful where requests and/or responses are streamed.
*/
public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Operations;
/**
* Calls ListOperations.
* @param request ListOperationsRequest message or plain object
* @param callback Node-style callback called with the error, if any, and ListOperationsResponse
*/
public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void;
/**
* Calls ListOperations.
* @param request ListOperationsRequest message or plain object
* @returns Promise
*/
public listOperations(request: google.longrunning.IListOperationsRequest): Promise<google.longrunning.ListOperationsResponse>;
/**
* Calls GetOperation.
* @param request GetOperationRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Operation
*/
public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void;
/**
* Calls GetOperation.
* @param request GetOperationRequest message or plain object
* @returns Promise
*/
public getOperation(request: google.longrunning.IGetOperationRequest): Promise<google.longrunning.Operation>;
/**
* Calls DeleteOperation.
* @param request DeleteOperationRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Empty
*/
public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void;
/**
* Calls DeleteOperation.
* @param request DeleteOperationRequest message or plain object
* @returns Promise
*/
public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise<google.protobuf.Empty>;
/**
* Calls CancelOperation.
* @param request CancelOperationRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Empty
*/
public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void;
/**
* Calls CancelOperation.
* @param request CancelOperationRequest message or plain object
* @returns Promise
*/
public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise<google.protobuf.Empty>;
/**
* Calls WaitOperation.
* @param request WaitOperationRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Operation
*/
public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void;
/**
* Calls WaitOperation.
* @param request WaitOperationRequest message or plain object
* @returns Promise
*/
public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise<google.longrunning.Operation>;
}
namespace Operations {
/**
* Callback as used by {@link google.longrunning.Operations#listOperations}.
* @param error Error, if any
* @param [response] ListOperationsResponse
*/
type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void;
/**
* Callback as used by {@link google.longrunning.Operations#getOperation}.
* @param error Error, if any
* @param [response] Operation
*/
type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void;
/**
* Callback as used by {@link google.longrunning.Operations#deleteOperation}.
* @param error Error, if any
* @param [response] Empty
*/
type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void;
/**
* Callback as used by {@link google.longrunning.Operations#cancelOperation}.
* @param error Error, if any
* @param [response] Empty
*/
type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void;
/**
* Callback as used by {@link google.longrunning.Operations#waitOperation}.
* @param error Error, if any
* @param [response] Operation
*/
type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void;
}
/** Properties of an Operation. */
interface IOperation {
/** Operation name */
name?: (string|null);
/** Operation metadata */
metadata?: (google.protobuf.IAny|null);
/** Operation done */
done?: (boolean|null);
/** Operation error */
error?: (google.rpc.IStatus|null);
/** Operation response */
response?: (google.protobuf.IAny|null);
}
/** Represents an Operation. */
class Operation implements IOperation {
/**
* Constructs a new Operation.
* @param [properties] Properties to set
*/
constructor(properties?: google.longrunning.IOperation);
/** Operation name. */
public name: string;
/** Operation metadata. */
public metadata?: (google.protobuf.IAny|null);
/** Operation done. */
public done: boolean;
/** Operation error. */
public error?: (google.rpc.IStatus|null);
/** Operation response. */
public response?: (google.protobuf.IAny|null);
/** Operation result. */
public result?: ("error"|"response");
/**
* Creates a new Operation instance using the specified properties.
* @param [properties] Properties to set
* @returns Operation instance
*/
public static create(properties?: google.longrunning.IOperation): google.longrunning.Operation;
/**
* Encodes the specified Operation message. Does not implicitly {@link google.longrunning.Operation.verify|verify} messages.
* @param message Operation message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.longrunning.IOperation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Operation message, length delimited. Does not implicitly {@link google.longrunning.Operation.verify|verify} messages.
* @param message Operation message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.longrunning.IOperation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Operation message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Operation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.Operation;
/**
* Decodes an Operation message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Operation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.Operation;
/**
* Verifies an Operation message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Operation message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Operation
*/
public static fromObject(object: { [k: string]: any }): google.longrunning.Operation;
/**
* Creates a plain object from an Operation message. Also converts values to other types if specified.
* @param message Operation
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Operation to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a GetOperationRequest. */
interface IGetOperationRequest {
/** GetOperationRequest name */
name?: (string|null);
}
/** Represents a GetOperationRequest. */
class GetOperationRequest implements IGetOperationRequest {
/**
* Constructs a new GetOperationRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.longrunning.IGetOperationRequest);
/** GetOperationRequest name. */
public name: string;
/**
* Creates a new GetOperationRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns GetOperationRequest instance
*/
public static create(properties?: google.longrunning.IGetOperationRequest): google.longrunning.GetOperationRequest;
/**
* Encodes the specified GetOperationRequest message. Does not implicitly {@link google.longrunning.GetOperationRequest.verify|verify} messages.
* @param message GetOperationRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.longrunning.IGetOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GetOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.GetOperationRequest.verify|verify} messages.
* @param message GetOperationRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.longrunning.IGetOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GetOperationRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GetOperationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.GetOperationRequest;
/**
* Decodes a GetOperationRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GetOperationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.GetOperationRequest;
/**
* Verifies a GetOperationRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GetOperationRequest
*/
public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest;
/**
* Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified.
* @param message GetOperationRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this GetOperationRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ListOperationsRequest. */
interface IListOperationsRequest {
/** ListOperationsRequest name */
name?: (string|null);
/** ListOperationsRequest filter */
filter?: (string|null);
/** ListOperationsRequest pageSize */
pageSize?: (number|null);
/** ListOperationsRequest pageToken */
pageToken?: (string|null);
}
/** Represents a ListOperationsRequest. */
class ListOperationsRequest implements IListOperationsRequest {
/**
* Constructs a new ListOperationsRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.longrunning.IListOperationsRequest);
/** ListOperationsRequest name. */
public name: string;
/** ListOperationsRequest filter. */
public filter: string;
/** ListOperationsRequest pageSize. */
public pageSize: number;
/** ListOperationsRequest pageToken. */
public pageToken: string;
/**
* Creates a new ListOperationsRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ListOperationsRequest instance
*/
public static create(properties?: google.longrunning.IListOperationsRequest): google.longrunning.ListOperationsRequest;
/**
* Encodes the specified ListOperationsRequest message. Does not implicitly {@link google.longrunning.ListOperationsRequest.verify|verify} messages.
* @param message ListOperationsRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.longrunning.IListOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ListOperationsRequest message, length delimited. Does not implicitly {@link google.longrunning.ListOperationsRequest.verify|verify} messages.
* @param message ListOperationsRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.longrunning.IListOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ListOperationsRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ListOperationsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.ListOperationsRequest;
/**
* Decodes a ListOperationsRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ListOperationsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.ListOperationsRequest;
/**
* Verifies a ListOperationsRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ListOperationsRequest
*/
public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest;
/**
* Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified.
* @param message ListOperationsRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ListOperationsRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ListOperationsResponse. */
interface IListOperationsResponse {
/** ListOperationsResponse operations */
operations?: (google.longrunning.IOperation[]|null);
/** ListOperationsResponse nextPageToken */
nextPageToken?: (string|null);
}
/** Represents a ListOperationsResponse. */
class ListOperationsResponse implements IListOperationsResponse {
/**
* Constructs a new ListOperationsResponse.
* @param [properties] Properties to set
*/
constructor(properties?: google.longrunning.IListOperationsResponse);
/** ListOperationsResponse operations. */
public operations: google.longrunning.IOperation[];
/** ListOperationsResponse nextPageToken. */
public nextPageToken: string;
/**
* Creates a new ListOperationsResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ListOperationsResponse instance
*/
public static create(properties?: google.longrunning.IListOperationsResponse): google.longrunning.ListOperationsResponse;
/**
* Encodes the specified ListOperationsResponse message. Does not implicitly {@link google.longrunning.ListOperationsResponse.verify|verify} messages.
* @param message ListOperationsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.longrunning.IListOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ListOperationsResponse message, length delimited. Does not implicitly {@link google.longrunning.ListOperationsResponse.verify|verify} messages.
* @param message ListOperationsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.longrunning.IListOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ListOperationsResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ListOperationsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.ListOperationsResponse;
/**
* Decodes a ListOperationsResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ListOperationsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.ListOperationsResponse;
/**
* Verifies a ListOperationsResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ListOperationsResponse
*/
public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse;
/**
* Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified.
* @param message ListOperationsResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ListOperationsResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a CancelOperationRequest. */
interface ICancelOperationRequest {
/** CancelOperationRequest name */
name?: (string|null);
}
/** Represents a CancelOperationRequest. */
class CancelOperationRequest implements ICancelOperationRequest {
/**
* Constructs a new CancelOperationRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.longrunning.ICancelOperationRequest);
/** CancelOperationRequest name. */
public name: string;
/**
* Creates a new CancelOperationRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns CancelOperationRequest instance
*/
public static create(properties?: google.longrunning.ICancelOperationRequest): google.longrunning.CancelOperationRequest;
/**
* Encodes the specified CancelOperationRequest message. Does not implicitly {@link google.longrunning.CancelOperationRequest.verify|verify} messages.
* @param message CancelOperationRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.longrunning.ICancelOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified CancelOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.CancelOperationRequest.verify|verify} messages.
* @param message CancelOperationRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.longrunning.ICancelOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a CancelOperationRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns CancelOperationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.CancelOperationRequest;
/**
* Decodes a CancelOperationRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns CancelOperationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.CancelOperationRequest;
/**
* Verifies a CancelOperationRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns CancelOperationRequest
*/
public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest;
/**
* Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified.
* @param message CancelOperationRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this CancelOperationRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a DeleteOperationRequest. */
interface IDeleteOperationRequest {
/** DeleteOperationRequest name */
name?: (string|null);
}
/** Represents a DeleteOperationRequest. */
class DeleteOperationRequest implements IDeleteOperationRequest {
/**
* Constructs a new DeleteOperationRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.longrunning.IDeleteOperationRequest);
/** DeleteOperationRequest name. */
public name: string;
/**
* Creates a new DeleteOperationRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns DeleteOperationRequest instance
*/
public static create(properties?: google.longrunning.IDeleteOperationRequest): google.longrunning.DeleteOperationRequest;
/**
* Encodes the specified DeleteOperationRequest message. Does not implicitly {@link google.longrunning.DeleteOperationRequest.verify|verify} messages.
* @param message DeleteOperationRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.longrunning.IDeleteOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified DeleteOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.DeleteOperationRequest.verify|verify} messages.
* @param message DeleteOperationRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.longrunning.IDeleteOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a DeleteOperationRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns DeleteOperationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.DeleteOperationRequest;
/**
* Decodes a DeleteOperationRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns DeleteOperationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.DeleteOperationRequest;
/**
* Verifies a DeleteOperationRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns DeleteOperationRequest
*/
public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest;
/**
* Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified.
* @param message DeleteOperationRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this DeleteOperationRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a WaitOperationRequest. */
interface IWaitOperationRequest {
/** WaitOperationRequest name */
name?: (string|null);
/** WaitOperationRequest timeout */
timeout?: (google.protobuf.IDuration|null);
}
/** Represents a WaitOperationRequest. */
class WaitOperationRequest implements IWaitOperationRequest {
/**
* Constructs a new WaitOperationRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.longrunning.IWaitOperationRequest);
/** WaitOperationRequest name. */
public name: string;
/** WaitOperationRequest timeout. */
public timeout?: (google.protobuf.IDuration|null);
/**
* Creates a new WaitOperationRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns WaitOperationRequest instance
*/
public static create(properties?: google.longrunning.IWaitOperationRequest): google.longrunning.WaitOperationRequest;
/**
* Encodes the specified WaitOperationRequest message. Does not implicitly {@link google.longrunning.WaitOperationRequest.verify|verify} messages.
* @param message WaitOperationRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.longrunning.IWaitOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified WaitOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.WaitOperationRequest.verify|verify} messages.
* @param message WaitOperationRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.longrunning.IWaitOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a WaitOperationRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns WaitOperationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.WaitOperationRequest;
/**
* Decodes a WaitOperationRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns WaitOperationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.WaitOperationRequest;
/**
* Verifies a WaitOperationRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns WaitOperationRequest
*/
public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest;
/**
* Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified.
* @param message WaitOperationRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this WaitOperationRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an OperationInfo. */
interface IOperationInfo {
/** OperationInfo responseType */
responseType?: (string|null);
/** OperationInfo metadataType */
metadataType?: (string|null);
}
/** Represents an OperationInfo. */
class OperationInfo implements IOperationInfo {
/**
* Constructs a new OperationInfo.
* @param [properties] Properties to set
*/
constructor(properties?: google.longrunning.IOperationInfo);
/** OperationInfo responseType. */
public responseType: string;
/** OperationInfo metadataType. */
public metadataType: string;
/**
* Creates a new OperationInfo instance using the specified properties.
* @param [properties] Properties to set
* @returns OperationInfo instance
*/
public static create(properties?: google.longrunning.IOperationInfo): google.longrunning.OperationInfo;
/**
* Encodes the specified OperationInfo message. Does not implicitly {@link google.longrunning.OperationInfo.verify|verify} messages.
* @param message OperationInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.longrunning.IOperationInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OperationInfo message, length delimited. Does not implicitly {@link google.longrunning.OperationInfo.verify|verify} messages.
* @param message OperationInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.longrunning.IOperationInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OperationInfo message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OperationInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.OperationInfo;
/**
* Decodes an OperationInfo message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OperationInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.OperationInfo;
/**
* Verifies an OperationInfo message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OperationInfo message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OperationInfo
*/
public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo;
/**
* Creates a plain object from an OperationInfo message. Also converts values to other types if specified.
* @param message OperationInfo
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OperationInfo to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Namespace rpc. */
namespace rpc {
/** Properties of a Status. */
interface IStatus {
/** Status code */
code?: (number|null);
/** Status message */
message?: (string|null);
/** Status details */
details?: (google.protobuf.IAny[]|null);
}
/** Represents a Status. */
class Status implements IStatus {
/**
* Constructs a new Status.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.IStatus);
/** Status code. */
public code: number;
/** Status message. */
public message: string;
/** Status details. */
public details: google.protobuf.IAny[];
/**
* Creates a new Status instance using the specified properties.
* @param [properties] Properties to set
* @returns Status instance
*/
public static create(properties?: google.rpc.IStatus): google.rpc.Status;
/**
* Encodes the specified Status message. Does not implicitly {@link google.rpc.Status.verify|verify} messages.
* @param message Status message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.IStatus, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Status message, length delimited. Does not implicitly {@link google.rpc.Status.verify|verify} messages.
* @param message Status message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.IStatus, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Status message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Status
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.Status;
/**
* Decodes a Status message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Status
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.Status;
/**
* Verifies a Status message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Status message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Status
*/
public static fromObject(object: { [k: string]: any }): google.rpc.Status;
/**
* Creates a plain object from a Status message. Also converts values to other types if specified.
* @param message Status
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Status to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a RetryInfo. */
interface IRetryInfo {
/** RetryInfo retryDelay */
retryDelay?: (google.protobuf.IDuration|null);
}
/** Represents a RetryInfo. */
class RetryInfo implements IRetryInfo {
/**
* Constructs a new RetryInfo.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.IRetryInfo);
/** RetryInfo retryDelay. */
public retryDelay?: (google.protobuf.IDuration|null);
/**
* Creates a new RetryInfo instance using the specified properties.
* @param [properties] Properties to set
* @returns RetryInfo instance
*/
public static create(properties?: google.rpc.IRetryInfo): google.rpc.RetryInfo;
/**
* Encodes the specified RetryInfo message. Does not implicitly {@link google.rpc.RetryInfo.verify|verify} messages.
* @param message RetryInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.IRetryInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified RetryInfo message, length delimited. Does not implicitly {@link google.rpc.RetryInfo.verify|verify} messages.
* @param message RetryInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.IRetryInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a RetryInfo message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns RetryInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.RetryInfo;
/**
* Decodes a RetryInfo message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns RetryInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.RetryInfo;
/**
* Verifies a RetryInfo message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a RetryInfo message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns RetryInfo
*/
public static fromObject(object: { [k: string]: any }): google.rpc.RetryInfo;
/**
* Creates a plain object from a RetryInfo message. Also converts values to other types if specified.
* @param message RetryInfo
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.RetryInfo, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this RetryInfo to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a DebugInfo. */
interface IDebugInfo {
/** DebugInfo stackEntries */
stackEntries?: (string[]|null);
/** DebugInfo detail */
detail?: (string|null);
}
/** Represents a DebugInfo. */
class DebugInfo implements IDebugInfo {
/**
* Constructs a new DebugInfo.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.IDebugInfo);
/** DebugInfo stackEntries. */
public stackEntries: string[];
/** DebugInfo detail. */
public detail: string;
/**
* Creates a new DebugInfo instance using the specified properties.
* @param [properties] Properties to set
* @returns DebugInfo instance
*/
public static create(properties?: google.rpc.IDebugInfo): google.rpc.DebugInfo;
/**
* Encodes the specified DebugInfo message. Does not implicitly {@link google.rpc.DebugInfo.verify|verify} messages.
* @param message DebugInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.IDebugInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified DebugInfo message, length delimited. Does not implicitly {@link google.rpc.DebugInfo.verify|verify} messages.
* @param message DebugInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.IDebugInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a DebugInfo message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns DebugInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.DebugInfo;
/**
* Decodes a DebugInfo message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns DebugInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.DebugInfo;
/**
* Verifies a DebugInfo message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a DebugInfo message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns DebugInfo
*/
public static fromObject(object: { [k: string]: any }): google.rpc.DebugInfo;
/**
* Creates a plain object from a DebugInfo message. Also converts values to other types if specified.
* @param message DebugInfo
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.DebugInfo, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this DebugInfo to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a QuotaFailure. */
interface IQuotaFailure {
/** QuotaFailure violations */
violations?: (google.rpc.QuotaFailure.IViolation[]|null);
}
/** Represents a QuotaFailure. */
class QuotaFailure implements IQuotaFailure {
/**
* Constructs a new QuotaFailure.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.IQuotaFailure);
/** QuotaFailure violations. */
public violations: google.rpc.QuotaFailure.IViolation[];
/**
* Creates a new QuotaFailure instance using the specified properties.
* @param [properties] Properties to set
* @returns QuotaFailure instance
*/
public static create(properties?: google.rpc.IQuotaFailure): google.rpc.QuotaFailure;
/**
* Encodes the specified QuotaFailure message. Does not implicitly {@link google.rpc.QuotaFailure.verify|verify} messages.
* @param message QuotaFailure message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.IQuotaFailure, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified QuotaFailure message, length delimited. Does not implicitly {@link google.rpc.QuotaFailure.verify|verify} messages.
* @param message QuotaFailure message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.IQuotaFailure, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a QuotaFailure message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns QuotaFailure
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.QuotaFailure;
/**
* Decodes a QuotaFailure message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns QuotaFailure
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.QuotaFailure;
/**
* Verifies a QuotaFailure message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a QuotaFailure message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns QuotaFailure
*/
public static fromObject(object: { [k: string]: any }): google.rpc.QuotaFailure;
/**
* Creates a plain object from a QuotaFailure message. Also converts values to other types if specified.
* @param message QuotaFailure
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.QuotaFailure, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this QuotaFailure to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace QuotaFailure {
/** Properties of a Violation. */
interface IViolation {
/** Violation subject */
subject?: (string|null);
/** Violation description */
description?: (string|null);
}
/** Represents a Violation. */
class Violation implements IViolation {
/**
* Constructs a new Violation.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.QuotaFailure.IViolation);
/** Violation subject. */
public subject: string;
/** Violation description. */
public description: string;
/**
* Creates a new Violation instance using the specified properties.
* @param [properties] Properties to set
* @returns Violation instance
*/
public static create(properties?: google.rpc.QuotaFailure.IViolation): google.rpc.QuotaFailure.Violation;
/**
* Encodes the specified Violation message. Does not implicitly {@link google.rpc.QuotaFailure.Violation.verify|verify} messages.
* @param message Violation message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.QuotaFailure.IViolation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Violation message, length delimited. Does not implicitly {@link google.rpc.QuotaFailure.Violation.verify|verify} messages.
* @param message Violation message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.QuotaFailure.IViolation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Violation message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Violation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.QuotaFailure.Violation;
/**
* Decodes a Violation message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Violation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.QuotaFailure.Violation;
/**
* Verifies a Violation message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Violation message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Violation
*/
public static fromObject(object: { [k: string]: any }): google.rpc.QuotaFailure.Violation;
/**
* Creates a plain object from a Violation message. Also converts values to other types if specified.
* @param message Violation
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.QuotaFailure.Violation, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Violation to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of an ErrorInfo. */
interface IErrorInfo {
/** ErrorInfo reason */
reason?: (string|null);
/** ErrorInfo domain */
domain?: (string|null);
/** ErrorInfo metadata */
metadata?: ({ [k: string]: string }|null);
}
/** Represents an ErrorInfo. */
class ErrorInfo implements IErrorInfo {
/**
* Constructs a new ErrorInfo.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.IErrorInfo);
/** ErrorInfo reason. */
public reason: string;
/** ErrorInfo domain. */
public domain: string;
/** ErrorInfo metadata. */
public metadata: { [k: string]: string };
/**
* Creates a new ErrorInfo instance using the specified properties.
* @param [properties] Properties to set
* @returns ErrorInfo instance
*/
public static create(properties?: google.rpc.IErrorInfo): google.rpc.ErrorInfo;
/**
* Encodes the specified ErrorInfo message. Does not implicitly {@link google.rpc.ErrorInfo.verify|verify} messages.
* @param message ErrorInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.IErrorInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ErrorInfo message, length delimited. Does not implicitly {@link google.rpc.ErrorInfo.verify|verify} messages.
* @param message ErrorInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.IErrorInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ErrorInfo message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ErrorInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.ErrorInfo;
/**
* Decodes an ErrorInfo message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ErrorInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.ErrorInfo;
/**
* Verifies an ErrorInfo message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ErrorInfo message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ErrorInfo
*/
public static fromObject(object: { [k: string]: any }): google.rpc.ErrorInfo;
/**
* Creates a plain object from an ErrorInfo message. Also converts values to other types if specified.
* @param message ErrorInfo
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.ErrorInfo, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ErrorInfo to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PreconditionFailure. */
interface IPreconditionFailure {
/** PreconditionFailure violations */
violations?: (google.rpc.PreconditionFailure.IViolation[]|null);
}
/** Represents a PreconditionFailure. */
class PreconditionFailure implements IPreconditionFailure {
/**
* Constructs a new PreconditionFailure.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.IPreconditionFailure);
/** PreconditionFailure violations. */
public violations: google.rpc.PreconditionFailure.IViolation[];
/**
* Creates a new PreconditionFailure instance using the specified properties.
* @param [properties] Properties to set
* @returns PreconditionFailure instance
*/
public static create(properties?: google.rpc.IPreconditionFailure): google.rpc.PreconditionFailure;
/**
* Encodes the specified PreconditionFailure message. Does not implicitly {@link google.rpc.PreconditionFailure.verify|verify} messages.
* @param message PreconditionFailure message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.IPreconditionFailure, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PreconditionFailure message, length delimited. Does not implicitly {@link google.rpc.PreconditionFailure.verify|verify} messages.
* @param message PreconditionFailure message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.IPreconditionFailure, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PreconditionFailure message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PreconditionFailure
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.PreconditionFailure;
/**
* Decodes a PreconditionFailure message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PreconditionFailure
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.PreconditionFailure;
/**
* Verifies a PreconditionFailure message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PreconditionFailure message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PreconditionFailure
*/
public static fromObject(object: { [k: string]: any }): google.rpc.PreconditionFailure;
/**
* Creates a plain object from a PreconditionFailure message. Also converts values to other types if specified.
* @param message PreconditionFailure
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.PreconditionFailure, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PreconditionFailure to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace PreconditionFailure {
/** Properties of a Violation. */
interface IViolation {
/** Violation type */
type?: (string|null);
/** Violation subject */
subject?: (string|null);
/** Violation description */
description?: (string|null);
}
/** Represents a Violation. */
class Violation implements IViolation {
/**
* Constructs a new Violation.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.PreconditionFailure.IViolation);
/** Violation type. */
public type: string;
/** Violation subject. */
public subject: string;
/** Violation description. */
public description: string;
/**
* Creates a new Violation instance using the specified properties.
* @param [properties] Properties to set
* @returns Violation instance
*/
public static create(properties?: google.rpc.PreconditionFailure.IViolation): google.rpc.PreconditionFailure.Violation;
/**
* Encodes the specified Violation message. Does not implicitly {@link google.rpc.PreconditionFailure.Violation.verify|verify} messages.
* @param message Violation message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.PreconditionFailure.IViolation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Violation message, length delimited. Does not implicitly {@link google.rpc.PreconditionFailure.Violation.verify|verify} messages.
* @param message Violation message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.PreconditionFailure.IViolation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Violation message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Violation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.PreconditionFailure.Violation;
/**
* Decodes a Violation message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Violation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.PreconditionFailure.Violation;
/**
* Verifies a Violation message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Violation message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Violation
*/
public static fromObject(object: { [k: string]: any }): google.rpc.PreconditionFailure.Violation;
/**
* Creates a plain object from a Violation message. Also converts values to other types if specified.
* @param message Violation
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.PreconditionFailure.Violation, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Violation to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a BadRequest. */
interface IBadRequest {
/** BadRequest fieldViolations */
fieldViolations?: (google.rpc.BadRequest.IFieldViolation[]|null);
}
/** Represents a BadRequest. */
class BadRequest implements IBadRequest {
/**
* Constructs a new BadRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.IBadRequest);
/** BadRequest fieldViolations. */
public fieldViolations: google.rpc.BadRequest.IFieldViolation[];
/**
* Creates a new BadRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns BadRequest instance
*/
public static create(properties?: google.rpc.IBadRequest): google.rpc.BadRequest;
/**
* Encodes the specified BadRequest message. Does not implicitly {@link google.rpc.BadRequest.verify|verify} messages.
* @param message BadRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.IBadRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified BadRequest message, length delimited. Does not implicitly {@link google.rpc.BadRequest.verify|verify} messages.
* @param message BadRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.IBadRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a BadRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns BadRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.BadRequest;
/**
* Decodes a BadRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns BadRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.BadRequest;
/**
* Verifies a BadRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a BadRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns BadRequest
*/
public static fromObject(object: { [k: string]: any }): google.rpc.BadRequest;
/**
* Creates a plain object from a BadRequest message. Also converts values to other types if specified.
* @param message BadRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.BadRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this BadRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace BadRequest {
/** Properties of a FieldViolation. */
interface IFieldViolation {
/** FieldViolation field */
field?: (string|null);
/** FieldViolation description */
description?: (string|null);
}
/** Represents a FieldViolation. */
class FieldViolation implements IFieldViolation {
/**
* Constructs a new FieldViolation.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.BadRequest.IFieldViolation);
/** FieldViolation field. */
public field: string;
/** FieldViolation description. */
public description: string;
/**
* Creates a new FieldViolation instance using the specified properties.
* @param [properties] Properties to set
* @returns FieldViolation instance
*/
public static create(properties?: google.rpc.BadRequest.IFieldViolation): google.rpc.BadRequest.FieldViolation;
/**
* Encodes the specified FieldViolation message. Does not implicitly {@link google.rpc.BadRequest.FieldViolation.verify|verify} messages.
* @param message FieldViolation message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.BadRequest.IFieldViolation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified FieldViolation message, length delimited. Does not implicitly {@link google.rpc.BadRequest.FieldViolation.verify|verify} messages.
* @param message FieldViolation message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.BadRequest.IFieldViolation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a FieldViolation message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns FieldViolation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.BadRequest.FieldViolation;
/**
* Decodes a FieldViolation message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns FieldViolation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.BadRequest.FieldViolation;
/**
* Verifies a FieldViolation message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a FieldViolation message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns FieldViolation
*/
public static fromObject(object: { [k: string]: any }): google.rpc.BadRequest.FieldViolation;
/**
* Creates a plain object from a FieldViolation message. Also converts values to other types if specified.
* @param message FieldViolation
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.BadRequest.FieldViolation, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this FieldViolation to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a RequestInfo. */
interface IRequestInfo {
/** RequestInfo requestId */
requestId?: (string|null);
/** RequestInfo servingData */
servingData?: (string|null);
}
/** Represents a RequestInfo. */
class RequestInfo implements IRequestInfo {
/**
* Constructs a new RequestInfo.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.IRequestInfo);
/** RequestInfo requestId. */
public requestId: string;
/** RequestInfo servingData. */
public servingData: string;
/**
* Creates a new RequestInfo instance using the specified properties.
* @param [properties] Properties to set
* @returns RequestInfo instance
*/
public static create(properties?: google.rpc.IRequestInfo): google.rpc.RequestInfo;
/**
* Encodes the specified RequestInfo message. Does not implicitly {@link google.rpc.RequestInfo.verify|verify} messages.
* @param message RequestInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.IRequestInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified RequestInfo message, length delimited. Does not implicitly {@link google.rpc.RequestInfo.verify|verify} messages.
* @param message RequestInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.IRequestInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a RequestInfo message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns RequestInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.RequestInfo;
/**
* Decodes a RequestInfo message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns RequestInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.RequestInfo;
/**
* Verifies a RequestInfo message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a RequestInfo message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns RequestInfo
*/
public static fromObject(object: { [k: string]: any }): google.rpc.RequestInfo;
/**
* Creates a plain object from a RequestInfo message. Also converts values to other types if specified.
* @param message RequestInfo
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.RequestInfo, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this RequestInfo to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ResourceInfo. */
interface IResourceInfo {
/** ResourceInfo resourceType */
resourceType?: (string|null);
/** ResourceInfo resourceName */
resourceName?: (string|null);
/** ResourceInfo owner */
owner?: (string|null);
/** ResourceInfo description */
description?: (string|null);
}
/** Represents a ResourceInfo. */
class ResourceInfo implements IResourceInfo {
/**
* Constructs a new ResourceInfo.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.IResourceInfo);
/** ResourceInfo resourceType. */
public resourceType: string;
/** ResourceInfo resourceName. */
public resourceName: string;
/** ResourceInfo owner. */
public owner: string;
/** ResourceInfo description. */
public description: string;
/**
* Creates a new ResourceInfo instance using the specified properties.
* @param [properties] Properties to set
* @returns ResourceInfo instance
*/
public static create(properties?: google.rpc.IResourceInfo): google.rpc.ResourceInfo;
/**
* Encodes the specified ResourceInfo message. Does not implicitly {@link google.rpc.ResourceInfo.verify|verify} messages.
* @param message ResourceInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.IResourceInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ResourceInfo message, length delimited. Does not implicitly {@link google.rpc.ResourceInfo.verify|verify} messages.
* @param message ResourceInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.IResourceInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ResourceInfo message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ResourceInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.ResourceInfo;
/**
* Decodes a ResourceInfo message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ResourceInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.ResourceInfo;
/**
* Verifies a ResourceInfo message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ResourceInfo message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ResourceInfo
*/
public static fromObject(object: { [k: string]: any }): google.rpc.ResourceInfo;
/**
* Creates a plain object from a ResourceInfo message. Also converts values to other types if specified.
* @param message ResourceInfo
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.ResourceInfo, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ResourceInfo to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Help. */
interface IHelp {
/** Help links */
links?: (google.rpc.Help.ILink[]|null);
}
/** Represents a Help. */
class Help implements IHelp {
/**
* Constructs a new Help.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.IHelp);
/** Help links. */
public links: google.rpc.Help.ILink[];
/**
* Creates a new Help instance using the specified properties.
* @param [properties] Properties to set
* @returns Help instance
*/
public static create(properties?: google.rpc.IHelp): google.rpc.Help;
/**
* Encodes the specified Help message. Does not implicitly {@link google.rpc.Help.verify|verify} messages.
* @param message Help message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.IHelp, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Help message, length delimited. Does not implicitly {@link google.rpc.Help.verify|verify} messages.
* @param message Help message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.IHelp, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Help message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Help
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.Help;
/**
* Decodes a Help message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Help
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.Help;
/**
* Verifies a Help message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Help message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Help
*/
public static fromObject(object: { [k: string]: any }): google.rpc.Help;
/**
* Creates a plain object from a Help message. Also converts values to other types if specified.
* @param message Help
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.Help, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Help to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace Help {
/** Properties of a Link. */
interface ILink {
/** Link description */
description?: (string|null);
/** Link url */
url?: (string|null);
}
/** Represents a Link. */
class Link implements ILink {
/**
* Constructs a new Link.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.Help.ILink);
/** Link description. */
public description: string;
/** Link url. */
public url: string;
/**
* Creates a new Link instance using the specified properties.
* @param [properties] Properties to set
* @returns Link instance
*/
public static create(properties?: google.rpc.Help.ILink): google.rpc.Help.Link;
/**
* Encodes the specified Link message. Does not implicitly {@link google.rpc.Help.Link.verify|verify} messages.
* @param message Link message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.Help.ILink, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Link message, length delimited. Does not implicitly {@link google.rpc.Help.Link.verify|verify} messages.
* @param message Link message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.Help.ILink, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Link message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Link
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.Help.Link;
/**
* Decodes a Link message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Link
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.Help.Link;
/**
* Verifies a Link message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Link message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Link
*/
public static fromObject(object: { [k: string]: any }): google.rpc.Help.Link;
/**
* Creates a plain object from a Link message. Also converts values to other types if specified.
* @param message Link
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.Help.Link, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Link to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a LocalizedMessage. */
interface ILocalizedMessage {
/** LocalizedMessage locale */
locale?: (string|null);
/** LocalizedMessage message */
message?: (string|null);
}
/** Represents a LocalizedMessage. */
class LocalizedMessage implements ILocalizedMessage {
/**
* Constructs a new LocalizedMessage.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.ILocalizedMessage);
/** LocalizedMessage locale. */
public locale: string;
/** LocalizedMessage message. */
public message: string;
/**
* Creates a new LocalizedMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns LocalizedMessage instance
*/
public static create(properties?: google.rpc.ILocalizedMessage): google.rpc.LocalizedMessage;
/**
* Encodes the specified LocalizedMessage message. Does not implicitly {@link google.rpc.LocalizedMessage.verify|verify} messages.
* @param message LocalizedMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.ILocalizedMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified LocalizedMessage message, length delimited. Does not implicitly {@link google.rpc.LocalizedMessage.verify|verify} messages.
* @param message LocalizedMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.ILocalizedMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a LocalizedMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns LocalizedMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.LocalizedMessage;
/**
* Decodes a LocalizedMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns LocalizedMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.LocalizedMessage;
/**
* Verifies a LocalizedMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a LocalizedMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns LocalizedMessage
*/
public static fromObject(object: { [k: string]: any }): google.rpc.LocalizedMessage;
/**
* Creates a plain object from a LocalizedMessage message. Also converts values to other types if specified.
* @param message LocalizedMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.LocalizedMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this LocalizedMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
} | the_stack |
import ResultPoint from '../../ResultPoint';
import AztecDetectorResult from '../AztecDetectorResult';
import BitMatrix from '../../common/BitMatrix';
import CornerDetector from '../../common/detector/CornerDetector';
import MathUtils from '../../common/detector/MathUtils';
import WhiteRectangleDetector from '../../common/detector/WhiteRectangleDetector';
import GenericGF from '../../common/reedsolomon/GenericGF';
import ReedSolomonDecoder from '../../common/reedsolomon/ReedSolomonDecoder';
import NotFoundException from '../../NotFoundException';
import GridSamplerInstance from '../../common/GridSamplerInstance';
import Integer from '../../util/Integer';
export class Point {
private x: number;
private y: number;
public toResultPoint(): ResultPoint {
return new ResultPoint(this.getX(), this.getY());
}
public constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
public getX(): number {
return this.x;
}
public getY(): number {
return this.y;
}
// @Override
// public String toString() {
// return "<" + x + ' ' + y + '>';
// }
}
/**
* Encapsulates logic that can detect an Aztec Code in an image, even if the Aztec Code
* is rotated or skewed, or partially obscured.
*
* @author David Olivier
* @author Frank Yellin
*/
export default class Detector {
private EXPECTED_CORNER_BITS = new Int32Array([
0xee0, // 07340 XXX .XX X.. ...
0x1dc, // 00734 ... XXX .XX X..
0x83b, // 04073 X.. ... XXX .XX
0x707, // 03407 .XX X.. ... XXX
]);
private image: BitMatrix;
private compact: boolean;
private nbLayers: number;
private nbDataBlocks: number;
private nbCenterLayers: number;
private shift: number;
public constructor(image: BitMatrix) {
this.image = image;
}
public detect(): AztecDetectorResult {
return this.detectMirror(false);
}
/**
* Detects an Aztec Code in an image.
*
* @param isMirror if true, image is a mirror-image of original
* @return {@link AztecDetectorResult} encapsulating results of detecting an Aztec Code
* @throws NotFoundException if no Aztec Code can be found
*/
public detectMirror(isMirror: boolean): AztecDetectorResult {
// 1. Get the center of the aztec matrix
let pCenter = this.getMatrixCenter();
// 2. Get the center points of the four diagonal points just outside the bull's eye
// [topRight, bottomRight, bottomLeft, topLeft]
let bullsEyeCorners = this.getBullsEyeCorners(pCenter);
if (isMirror) {
let temp = bullsEyeCorners[0];
bullsEyeCorners[0] = bullsEyeCorners[2];
bullsEyeCorners[2] = temp;
}
// 3. Get the size of the matrix and other parameters from the bull's eye
this.extractParameters(bullsEyeCorners);
// 4. Sample the grid
let bits: BitMatrix = this.sampleGrid(this.image,
bullsEyeCorners[this.shift % 4],
bullsEyeCorners[(this.shift + 1) % 4],
bullsEyeCorners[(this.shift + 2) % 4],
bullsEyeCorners[(this.shift + 3) % 4]
);
// 5. Get the corners of the matrix.
let corners: ResultPoint[] = this.getMatrixCornerPoints(bullsEyeCorners);
return new AztecDetectorResult(bits, corners, this.compact, this.nbDataBlocks, this.nbLayers);
}
/**
* Extracts the number of data layers and data blocks from the layer around the bull's eye.
*
* @param bullsEyeCorners the array of bull's eye corners
* @throws NotFoundException in case of too many errors or invalid parameters
*/
private extractParameters(bullsEyeCorners: ResultPoint[]): void {
if (!this.isValidPoint(bullsEyeCorners[0]) || !this.isValidPoint(bullsEyeCorners[1]) ||
!this.isValidPoint(bullsEyeCorners[2]) || !this.isValidPoint(bullsEyeCorners[3])) {
throw new NotFoundException();
}
let length = 2 * this.nbCenterLayers;
// Get the bits around the bull's eye
let sides = new Int32Array([
this.sampleLine(bullsEyeCorners[0], bullsEyeCorners[1], length), // Right side
this.sampleLine(bullsEyeCorners[1], bullsEyeCorners[2], length), // Bottom
this.sampleLine(bullsEyeCorners[2], bullsEyeCorners[3], length), // Left side
this.sampleLine(bullsEyeCorners[3], bullsEyeCorners[0], length) // Top
]);
// bullsEyeCorners[shift] is the corner of the bulls'eye that has three
// orientation marks.
// sides[shift] is the row/column that goes from the corner with three
// orientation marks to the corner with two.
this.shift = this.getRotation(sides, length);
// Flatten the parameter bits into a single 28- or 40-bit long
let parameterData = 0;
for (let i = 0; i < 4; i++) {
let side = sides[(this.shift + i) % 4];
if (this.compact) {
// Each side of the form ..XXXXXXX. where Xs are parameter data
parameterData <<= 7;
parameterData += (side >> 1) & 0x7F;
} else {
// Each side of the form ..XXXXX.XXXXX. where Xs are parameter data
parameterData <<= 10;
parameterData += ((side >> 2) & (0x1f << 5)) + ((side >> 1) & 0x1F);
}
}
// Corrects parameter data using RS. Returns just the data portion
// without the error correction.
let correctedData = this.getCorrectedParameterData(parameterData, this.compact);
if (this.compact) {
// 8 bits: 2 bits layers and 6 bits data blocks
this.nbLayers = (correctedData >> 6) + 1;
this.nbDataBlocks = (correctedData & 0x3F) + 1;
} else {
// 16 bits: 5 bits layers and 11 bits data blocks
this.nbLayers = (correctedData >> 11) + 1;
this.nbDataBlocks = (correctedData & 0x7FF) + 1;
}
}
private getRotation(sides: Int32Array, length: number): number {
// In a normal pattern, we expect to See
// ** .* D A
// * *
//
// . *
// .. .. C B
//
// Grab the 3 bits from each of the sides the form the locator pattern and concatenate
// into a 12-bit integer. Start with the bit at A
let cornerBits = 0;
sides.forEach((side, idx, arr) => {
// XX......X where X's are orientation marks
let t = ((side >> (length - 2)) << 1) + (side & 1);
cornerBits = (cornerBits << 3) + t;
});
// for (var side in sides) {
// // XX......X where X's are orientation marks
// var t = ((side >> (length - 2)) << 1) + (side & 1);
// cornerBits = (cornerBits << 3) + t;
// }
// Mov the bottom bit to the top, so that the three bits of the locator pattern at A are
// together. cornerBits is now:
// 3 orientation bits at A || 3 orientation bits at B || ... || 3 orientation bits at D
cornerBits = ((cornerBits & 1) << 11) + (cornerBits >> 1);
// The result shift indicates which element of BullsEyeCorners[] goes into the top-left
// corner. Since the four rotation values have a Hamming distance of 8, we
// can easily tolerate two errors.
for (let shift = 0; shift < 4; shift++) {
if (Integer.bitCount(cornerBits ^ this.EXPECTED_CORNER_BITS[shift]) <= 2) {
return shift;
}
}
throw new NotFoundException();
}
/**
* Corrects the parameter bits using Reed-Solomon algorithm.
*
* @param parameterData parameter bits
* @param compact true if this is a compact Aztec code
* @throws NotFoundException if the array contains too many errors
*/
private getCorrectedParameterData(parameterData: number, compact: boolean): number {
let numCodewords;
let numDataCodewords;
if (compact) {
numCodewords = 7;
numDataCodewords = 2;
} else {
numCodewords = 10;
numDataCodewords = 4;
}
let numECCodewords = numCodewords - numDataCodewords;
let parameterWords: Int32Array = new Int32Array(numCodewords);
for (let i = numCodewords - 1; i >= 0; --i) {
parameterWords[i] = parameterData & 0xF;
parameterData >>= 4;
}
try {
let rsDecoder = new ReedSolomonDecoder(GenericGF.AZTEC_PARAM);
rsDecoder.decode(parameterWords, numECCodewords);
} catch (ignored) {
throw new NotFoundException();
}
// Toss the error correction. Just return the data as an integer
let result = 0;
for (let i = 0; i < numDataCodewords; i++) {
result = (result << 4) + parameterWords[i];
}
return result;
}
/**
* Finds the corners of a bull-eye centered on the passed point.
* This returns the centers of the diagonal points just outside the bull's eye
* Returns [topRight, bottomRight, bottomLeft, topLeft]
*
* @param pCenter Center point
* @return The corners of the bull-eye
* @throws NotFoundException If no valid bull-eye can be found
*/
private getBullsEyeCorners(pCenter: Point): ResultPoint[] {
let pina = pCenter;
let pinb = pCenter;
let pinc = pCenter;
let pind = pCenter;
let color = true;
for (this.nbCenterLayers = 1; this.nbCenterLayers < 9; this.nbCenterLayers++) {
let pouta = this.getFirstDifferent(pina, color, 1, -1);
let poutb = this.getFirstDifferent(pinb, color, 1, 1);
let poutc = this.getFirstDifferent(pinc, color, -1, 1);
let poutd = this.getFirstDifferent(pind, color, -1, -1);
// d a
//
// c b
if (this.nbCenterLayers > 2) {
let q = (this.distancePoint(poutd, pouta) * this.nbCenterLayers) / (this.distancePoint(pind, pina) * (this.nbCenterLayers + 2));
if (q < 0.75 || q > 1.25 || !this.isWhiteOrBlackRectangle(pouta, poutb, poutc, poutd)) {
break;
}
}
pina = pouta;
pinb = poutb;
pinc = poutc;
pind = poutd;
color = !color;
}
if (this.nbCenterLayers !== 5 && this.nbCenterLayers !== 7) {
throw new NotFoundException();
}
this.compact = this.nbCenterLayers === 5;
// Expand the square by .5 pixel in each direction so that we're on the border
// between the white square and the black square
let pinax = new ResultPoint(pina.getX() + 0.5, pina.getY() - 0.5);
let pinbx = new ResultPoint(pinb.getX() + 0.5, pinb.getY() + 0.5);
let pincx = new ResultPoint(pinc.getX() - 0.5, pinc.getY() + 0.5);
let pindx = new ResultPoint(pind.getX() - 0.5, pind.getY() - 0.5);
// Expand the square so that its corners are the centers of the points
// just outside the bull's eye.
return this.expandSquare([pinax, pinbx, pincx, pindx],
2 * this.nbCenterLayers - 3,
2 * this.nbCenterLayers);
}
/**
* Finds a candidate center point of an Aztec code from an image
*
* @return the center point
*/
private getMatrixCenter(): Point {
let pointA: ResultPoint;
let pointB: ResultPoint;
let pointC: ResultPoint;
let pointD: ResultPoint;
// Get a white rectangle that can be the border of the matrix in center bull's eye or
try {
let cornerPoints = new WhiteRectangleDetector(this.image).detect();
pointA = cornerPoints[0];
pointB = cornerPoints[1];
pointC = cornerPoints[2];
pointD = cornerPoints[3];
} catch (e) {
// This exception can be in case the initial rectangle is white
// In that case, surely in the bull's eye, we try to expand the rectangle.
let cx = this.image.getWidth() / 2;
let cy = this.image.getHeight() / 2;
pointA = this.getFirstDifferent(new Point(cx + 7, cy - 7), false, 1, -1).toResultPoint();
pointB = this.getFirstDifferent(new Point(cx + 7, cy + 7), false, 1, 1).toResultPoint();
pointC = this.getFirstDifferent(new Point(cx - 7, cy + 7), false, -1, 1).toResultPoint();
pointD = this.getFirstDifferent(new Point(cx - 7, cy - 7), false, -1, -1).toResultPoint();
}
// Compute the center of the rectangle
let cx = MathUtils.round((pointA.getX() + pointD.getX() + pointB.getX() + pointC.getX()) / 4.0);
let cy = MathUtils.round((pointA.getY() + pointD.getY() + pointB.getY() + pointC.getY()) / 4.0);
// Redetermine the white rectangle starting from previously computed center.
// This will ensure that we end up with a white rectangle in center bull's eye
// in order to compute a more accurate center.
try {
let cornerPoints = new WhiteRectangleDetector(this.image, 15, cx, cy).detect();
pointA = cornerPoints[0];
pointB = cornerPoints[1];
pointC = cornerPoints[2];
pointD = cornerPoints[3];
} catch (e) {
// This exception can be in case the initial rectangle is white
// In that case we try to expand the rectangle.
pointA = this.getFirstDifferent(new Point(cx + 7, cy - 7), false, 1, -1).toResultPoint();
pointB = this.getFirstDifferent(new Point(cx + 7, cy + 7), false, 1, 1).toResultPoint();
pointC = this.getFirstDifferent(new Point(cx - 7, cy + 7), false, -1, 1).toResultPoint();
pointD = this.getFirstDifferent(new Point(cx - 7, cy - 7), false, -1, -1).toResultPoint();
}
// Recompute the center of the rectangle
cx = MathUtils.round((pointA.getX() + pointD.getX() + pointB.getX() + pointC.getX()) / 4.0);
cy = MathUtils.round((pointA.getY() + pointD.getY() + pointB.getY() + pointC.getY()) / 4.0);
return new Point(cx, cy);
}
/**
* Gets the Aztec code corners from the bull's eye corners and the parameters.
*
* @param bullsEyeCorners the array of bull's eye corners
* @return the array of aztec code corners
*/
private getMatrixCornerPoints(bullsEyeCorners: ResultPoint[]): ResultPoint[] {
return this.expandSquare(bullsEyeCorners, 2 * this.nbCenterLayers, this.getDimension());
}
/**
* Creates a BitMatrix by sampling the provided image.
* topLeft, topRight, bottomRight, and bottomLeft are the centers of the squares on the
* diagonal just outside the bull's eye.
*/
private sampleGrid(image: BitMatrix,
topLeft: ResultPoint,
topRight: ResultPoint,
bottomRight: ResultPoint,
bottomLeft: ResultPoint): BitMatrix {
let sampler = GridSamplerInstance.getInstance();
let dimension = this.getDimension();
let low = dimension / 2 - this.nbCenterLayers;
let high = dimension / 2 + this.nbCenterLayers;
return sampler.sampleGrid(image,
dimension,
dimension,
low, low, // topleft
high, low, // topright
high, high, // bottomright
low, high, // bottomleft
topLeft.getX(), topLeft.getY(),
topRight.getX(), topRight.getY(),
bottomRight.getX(), bottomRight.getY(),
bottomLeft.getX(), bottomLeft.getY());
}
/**
* Samples a line.
*
* @param p1 start point (inclusive)
* @param p2 end point (exclusive)
* @param size number of bits
* @return the array of bits as an int (first bit is high-order bit of result)
*/
private sampleLine(p1: ResultPoint, p2: ResultPoint, size: number): number {
let result = 0;
let d = this.distanceResultPoint(p1, p2);
let moduleSize = d / size;
let px = p1.getX();
let py = p1.getY();
let dx = moduleSize * (p2.getX() - p1.getX()) / d;
let dy = moduleSize * (p2.getY() - p1.getY()) / d;
for (let i = 0; i < size; i++) {
if (this.image.get(MathUtils.round(px + i * dx), MathUtils.round(py + i * dy))) {
result |= 1 << (size - i - 1);
}
}
return result;
}
/**
* @return true if the border of the rectangle passed in parameter is compound of white points only
* or black points only
*/
private isWhiteOrBlackRectangle(p1: Point,
p2: Point,
p3: Point,
p4: Point): boolean {
let corr = 3;
p1 = new Point(p1.getX() - corr, p1.getY() + corr);
p2 = new Point(p2.getX() - corr, p2.getY() - corr);
p3 = new Point(p3.getX() + corr, p3.getY() - corr);
p4 = new Point(p4.getX() + corr, p4.getY() + corr);
let cInit = this.getColor(p4, p1);
if (cInit === 0) {
return false;
}
let c = this.getColor(p1, p2);
if (c !== cInit) {
return false;
}
c = this.getColor(p2, p3);
if (c !== cInit) {
return false;
}
c = this.getColor(p3, p4);
return c === cInit;
}
/**
* Gets the color of a segment
*
* @return 1 if segment more than 90% black, -1 if segment is more than 90% white, 0 else
*/
private getColor(p1: Point, p2: Point): number {
let d = this.distancePoint(p1, p2);
let dx = (p2.getX() - p1.getX()) / d;
let dy = (p2.getY() - p1.getY()) / d;
let error = 0;
let px = p1.getX();
let py = p1.getY();
let colorModel = this.image.get(p1.getX(), p1.getY());
let iMax = Math.ceil(d);
for (let i = 0; i < iMax; i++) {
px += dx;
py += dy;
if (this.image.get(MathUtils.round(px), MathUtils.round(py)) !== colorModel) {
error++;
}
}
let errRatio = error / d;
if (errRatio > 0.1 && errRatio < 0.9) {
return 0;
}
return (errRatio <= 0.1) === colorModel ? 1 : -1;
}
/**
* Gets the coordinate of the first point with a different color in the given direction
*/
private getFirstDifferent(init: Point, color: boolean, dx: number, dy: number): Point {
let x = init.getX() + dx;
let y = init.getY() + dy;
while (this.isValid(x, y) && this.image.get(x, y) === color) {
x += dx;
y += dy;
}
x -= dx;
y -= dy;
while (this.isValid(x, y) && this.image.get(x, y) === color) {
x += dx;
}
x -= dx;
while (this.isValid(x, y) && this.image.get(x, y) === color) {
y += dy;
}
y -= dy;
return new Point(x, y);
}
/**
* Expand the square represented by the corner points by pushing out equally in all directions
*
* @param cornerPoints the corners of the square, which has the bull's eye at its center
* @param oldSide the original length of the side of the square in the target bit matrix
* @param newSide the new length of the size of the square in the target bit matrix
* @return the corners of the expanded square
*/
private expandSquare(cornerPoints: ResultPoint[], oldSide: number, newSide: number): ResultPoint[] {
let ratio = newSide / (2.0 * oldSide);
let dx = cornerPoints[0].getX() - cornerPoints[2].getX();
let dy = cornerPoints[0].getY() - cornerPoints[2].getY();
let centerx = (cornerPoints[0].getX() + cornerPoints[2].getX()) / 2.0;
let centery = (cornerPoints[0].getY() + cornerPoints[2].getY()) / 2.0;
let result0 = new ResultPoint(centerx + ratio * dx, centery + ratio * dy);
let result2 = new ResultPoint(centerx - ratio * dx, centery - ratio * dy);
dx = cornerPoints[1].getX() - cornerPoints[3].getX();
dy = cornerPoints[1].getY() - cornerPoints[3].getY();
centerx = (cornerPoints[1].getX() + cornerPoints[3].getX()) / 2.0;
centery = (cornerPoints[1].getY() + cornerPoints[3].getY()) / 2.0;
let result1 = new ResultPoint(centerx + ratio * dx, centery + ratio * dy);
let result3 = new ResultPoint(centerx - ratio * dx, centery - ratio * dy);
let results: ResultPoint[] = [result0, result1, result2, result3];
return results;
}
private isValid(x: number, y: number): boolean {
return x >= 0 && x < this.image.getWidth() && y > 0 && y < this.image.getHeight();
}
private isValidPoint(point: ResultPoint): boolean {
let x = MathUtils.round(point.getX());
let y = MathUtils.round(point.getY());
return this.isValid(x, y);
}
private distancePoint(a: Point, b: Point): number {
return MathUtils.distance(a.getX(), a.getY(), b.getX(), b.getY());
}
private distanceResultPoint(a: ResultPoint, b: ResultPoint): number {
return MathUtils.distance(a.getX(), a.getY(), b.getX(), b.getY());
}
private getDimension(): number {
if (this.compact) {
return 4 * this.nbLayers + 11;
}
if (this.nbLayers <= 4) {
return 4 * this.nbLayers + 15;
}
return 4 * this.nbLayers + 2 * (Integer.truncDivision((this.nbLayers - 4), 8) + 1) + 15;
}
} | the_stack |
import React, { Fragment } from "react"
import { RouteComponentProps, withRouter } from "react-router-dom"
import { v4 as uuidv4 } from "uuid"
import JobDetailsModal, { JobDetailsModalContext, toggleExpanded } from "../components/job-details/JobDetailsModal"
import CancelJobsModal, { CancelJobsModalContext, CancelJobsModalState } from "../components/jobs/CancelJobsModal"
import Jobs from "../components/jobs/Jobs"
import ReprioritizeJobsDialog, {
ReprioritizeJobsDialogContext,
ReprioritizeJobsDialogState,
} from "../components/jobs/ReprioritizeJobsDialog"
import IntervalService from "../services/IntervalService"
import JobService, { GetJobsRequest, Job } from "../services/JobService"
import JobTableService from "../services/JobTableService"
import JobsLocalStorageService from "../services/JobsLocalStorageService"
import JobsQueryParamsService from "../services/JobsQueryParamsService"
import LogService from "../services/LogService"
import TimerService from "../services/TimerService"
import { RequestStatus, selectItem, setStateAsync } from "../utils"
type JobsContainerProps = {
jobService: JobService
logService: LogService
jobsAutoRefreshMs: number
} & RouteComponentProps
export type JobsContainerState = {
jobs: Job[]
selectedJobs: Map<string, Job>
lastSelectedIndex: number
autoRefresh: boolean
defaultColumns: ColumnSpec<string | boolean | string[]>[]
annotationColumns: ColumnSpec<string>[]
cancelJobsModalContext: CancelJobsModalContext
reprioritizeJobsDialogContext: ReprioritizeJobsDialogContext
jobDetailsModalContext: JobDetailsModalContext
getJobsRequestStatus: RequestStatus
}
export type ColumnSpec<T> = {
id: string
name: string
accessor: string
isDisabled: boolean
filter: T
defaultFilter: T
width: number // Relative weight of column w.r.t. other columns, default is 1
}
export function isColumnSpec<T>(obj: any): obj is ColumnSpec<T> {
if (obj == undefined || typeof obj != "object") {
return false
}
const columnSpec = obj as Record<string, unknown>
return (
columnSpec.id != undefined &&
typeof columnSpec.id == "string" &&
columnSpec.name != undefined &&
typeof columnSpec.name == "string" &&
columnSpec.accessor != undefined &&
typeof columnSpec.accessor == "string" &&
columnSpec.isDisabled != undefined &&
typeof columnSpec.isDisabled == "boolean" &&
columnSpec.filter != undefined &&
columnSpec.defaultFilter != undefined &&
columnSpec.width != undefined &&
typeof columnSpec.width == "number"
)
}
const newPriorityRegex = new RegExp("^([0-9]+)$")
const BATCH_SIZE = 100
const CANCELLABLE_JOB_STATES = ["Queued", "Pending", "Running"]
const REPRIORITIZEABLE_JOB_STATES = ["Queued", "Pending", "Running"]
class JobsContainer extends React.Component<JobsContainerProps, JobsContainerState> {
jobTableService: JobTableService
autoRefreshService: IntervalService
resetCacheService: TimerService
localStorageService: JobsLocalStorageService
queryParamsService: JobsQueryParamsService
constructor(props: JobsContainerProps) {
super(props)
this.jobTableService = new JobTableService(this.props.jobService, BATCH_SIZE)
this.autoRefreshService = new IntervalService(props.jobsAutoRefreshMs)
this.resetCacheService = new TimerService(100)
this.localStorageService = new JobsLocalStorageService()
this.queryParamsService = new JobsQueryParamsService(this.props)
this.state = {
jobs: [],
getJobsRequestStatus: "Idle",
selectedJobs: new Map<string, Job>(),
lastSelectedIndex: 0,
autoRefresh: true,
defaultColumns: [
{
id: "jobState",
name: "State",
accessor: "jobState",
isDisabled: false,
filter: [],
defaultFilter: [],
width: 0.5,
},
{
id: "queue",
name: "Queue",
accessor: "queue",
isDisabled: false,
filter: "",
defaultFilter: "",
width: 1,
},
{
id: "jobId",
name: "Job Id",
accessor: "jobId",
isDisabled: false,
filter: "",
defaultFilter: "",
width: 1,
},
{
id: "owner",
name: "Owner",
accessor: "owner",
isDisabled: false,
filter: "",
defaultFilter: "",
width: 1,
},
{
id: "jobSet",
name: "Job Set",
accessor: "jobSet",
isDisabled: false,
filter: "",
defaultFilter: "",
width: 1,
},
{
id: "submissionTime",
name: "Submission Time",
accessor: "submissionTime",
isDisabled: false,
filter: true,
defaultFilter: true,
width: 1,
},
],
annotationColumns: [],
cancelJobsModalContext: {
modalState: "None",
jobsToCancel: [],
cancelJobsResult: { cancelledJobs: [], failedJobCancellations: [] },
cancelJobsRequestStatus: "Idle",
},
reprioritizeJobsDialogContext: {
modalState: "None",
jobsToReprioritize: [],
newPriority: 0,
isValid: false,
reprioritizeJobsResult: { reprioritizedJobs: [], failedJobReprioritizations: [] },
reprioritizeJobsRequestStatus: "Idle",
},
jobDetailsModalContext: {
open: false,
job: undefined,
expandedItems: new Set(),
},
}
this.serveJobs = this.serveJobs.bind(this)
this.jobIsLoaded = this.jobIsLoaded.bind(this)
this.changeColumnFilter = this.changeColumnFilter.bind(this)
this.disableColumn = this.disableColumn.bind(this)
this.refresh = this.refresh.bind(this)
this.toggleAutoRefresh = this.toggleAutoRefresh.bind(this)
this.resetAutoRefresh = this.resetAutoRefresh.bind(this)
this.selectJob = this.selectJob.bind(this)
this.shiftSelectJob = this.shiftSelectJob.bind(this)
this.deselectAll = this.deselectAll.bind(this)
this.setCancelJobsModalState = this.setCancelJobsModalState.bind(this)
this.cancelJobs = this.cancelJobs.bind(this)
this.setReprioritizeJobsDialogState = this.setReprioritizeJobsDialogState.bind(this)
this.reprioritizeJobs = this.reprioritizeJobs.bind(this)
this.openJobDetailsModal = this.openJobDetailsModal.bind(this)
this.toggleExpanded = this.toggleExpanded.bind(this)
this.closeJobDetailsModal = this.closeJobDetailsModal.bind(this)
this.addAnnotationColumn = this.addAnnotationColumn.bind(this)
this.deleteAnnotationColumn = this.deleteAnnotationColumn.bind(this)
this.changeAnnotationColumnKey = this.changeAnnotationColumnKey.bind(this)
this.handlePriorityChange = this.handlePriorityChange.bind(this)
this.registerResetCache = this.registerResetCache.bind(this)
this.clearFilters = this.clearFilters.bind(this)
}
async componentDidMount() {
const newState = { ...this.state }
this.localStorageService.updateState(newState)
this.queryParamsService.updateState(newState)
this.localStorageService.saveState(newState)
this.queryParamsService.saveState(newState)
await setStateAsync(this, {
...newState,
jobs: this.jobTableService.getJobs(), // Can start loading
})
this.autoRefreshService.registerCallback(this.refresh)
this.tryStartAutoRefreshService()
}
componentWillUnmount() {
this.resetCacheService.stop()
this.autoRefreshService.stop()
}
async serveJobs(start: number, stop: number): Promise<Job[]> {
if (this.state.getJobsRequestStatus === "Loading") {
return Promise.resolve([])
}
await setStateAsync(this, {
...this.state,
getJobsRequestStatus: "Loading",
})
let shouldLoad = false
for (let i = start; i <= stop; i++) {
if (!this.jobTableService.jobIsLoaded(i)) {
shouldLoad = true
break
}
}
if (shouldLoad) {
const request = this.createGetJobsRequest()
await this.jobTableService.loadJobs(request, start, stop)
await setStateAsync(this, {
...this.state,
jobs: this.jobTableService.getJobs(),
getJobsRequestStatus: "Idle",
})
}
return Promise.resolve(this.state.jobs.slice(start, stop))
}
jobIsLoaded(index: number) {
return this.state.getJobsRequestStatus === "Loading" || this.jobTableService.jobIsLoaded(index)
}
changeColumnFilter(columnId: string, newValue: string | boolean | string[]) {
const newState = { ...this.state }
for (const col of newState.defaultColumns) {
if (col.id === columnId) {
col.filter = newValue
}
}
for (const col of newState.annotationColumns) {
if (col.id === columnId) {
col.filter = newValue as string
}
}
this.setFilters(newState)
}
disableColumn(columnId: string, isDisabled: boolean) {
const newState = { ...this.state }
for (const col of newState.defaultColumns) {
if (col.id === columnId) {
col.isDisabled = isDisabled
col.filter = col.defaultFilter
}
}
for (const col of newState.annotationColumns) {
if (col.id === columnId) {
col.isDisabled = isDisabled
col.filter = col.defaultFilter
}
}
this.setFilters(newState)
}
addAnnotationColumn() {
const newState = { ...this.state }
const newCol: ColumnSpec<string> = {
id: uuidv4(),
name: "",
accessor: "",
isDisabled: false,
filter: "",
defaultFilter: "",
width: 1,
}
newState.annotationColumns.push(newCol)
this.setFilters(newState)
}
deleteAnnotationColumn(columnId: string) {
const newState = { ...this.state }
let toRemove = -1
for (let i = 0; i < newState.annotationColumns.length; i++) {
if (newState.annotationColumns[i].id === columnId) {
toRemove = i
}
}
newState.annotationColumns.splice(toRemove, 1)
this.setFilters(newState)
}
changeAnnotationColumnKey(columnId: string, newKey: string) {
const newState = { ...this.state }
for (const col of newState.annotationColumns) {
if (col.id === columnId) {
col.name = newKey
col.accessor = newKey
}
}
this.setFilters(newState)
}
clearFilters() {
const newState = { ...this.state }
for (const col of newState.defaultColumns) {
switch (col.id) {
case "queue":
case "jobId":
case "owner":
case "jobSet": {
col.filter = ""
break
}
case "submissionTime": {
col.filter = true
break
}
case "jobState": {
col.filter = []
break
}
}
}
for (const col of newState.annotationColumns) {
col.filter = ""
}
this.setFilters(newState)
}
refresh() {
this.setFilters(this.state)
}
resetAutoRefresh() {
this.autoRefreshService.start()
}
selectJob(index: number, selected: boolean) {
if (index < 0 || index >= this.state.jobs.length) {
return
}
const job = this.state.jobs[index]
const selectedJobs = new Map<string, Job>(this.state.selectedJobs)
selectItem(job.jobId, job, selectedJobs, selected)
const cancellableJobs = this.getCancellableSelectedJobs(selectedJobs)
const reprioritizeableJobs = this.getReprioritizeableSelectedJobs(selectedJobs)
this.setState({
...this.state,
selectedJobs: selectedJobs,
lastSelectedIndex: index,
cancelJobsModalContext: {
...this.state.cancelJobsModalContext,
jobsToCancel: cancellableJobs,
},
reprioritizeJobsDialogContext: {
...this.state.reprioritizeJobsDialogContext,
jobsToReprioritize: reprioritizeableJobs,
},
})
}
shiftSelectJob(index: number, selected: boolean) {
if (index >= this.state.jobs.length || index < 0) {
return
}
const [start, end] = [this.state.lastSelectedIndex, index].sort((a, b) => a - b)
const selectedJobs = new Map<string, Job>(this.state.selectedJobs)
for (let i = start; i <= end; i++) {
const job = this.state.jobs[i]
selectItem(job.jobId, job, selectedJobs, selected)
}
const cancellableJobs = this.getCancellableSelectedJobs(selectedJobs)
const reprioritizeableJobs = this.getReprioritizeableSelectedJobs(selectedJobs)
this.setState({
...this.state,
selectedJobs: selectedJobs,
lastSelectedIndex: index,
cancelJobsModalContext: {
...this.state.cancelJobsModalContext,
jobsToCancel: cancellableJobs,
},
reprioritizeJobsDialogContext: {
...this.state.reprioritizeJobsDialogContext,
jobsToReprioritize: reprioritizeableJobs,
},
})
}
deselectAll() {
this.setState({
...this.state,
selectedJobs: new Map<string, Job>(),
lastSelectedIndex: 0,
cancelJobsModalContext: {
...this.state.cancelJobsModalContext,
jobsToCancel: [],
},
reprioritizeJobsDialogContext: {
...this.state.reprioritizeJobsDialogContext,
jobsToReprioritize: [],
},
})
}
setReprioritizeJobsDialogState(modalState: ReprioritizeJobsDialogState) {
this.setState({
...this.state,
reprioritizeJobsDialogContext: {
...this.state.reprioritizeJobsDialogContext,
modalState: modalState,
},
})
}
setCancelJobsModalState(modalState: CancelJobsModalState) {
this.setState({
...this.state,
cancelJobsModalContext: {
...this.state.cancelJobsModalContext,
modalState: modalState,
},
})
}
async cancelJobs() {
if (this.state.cancelJobsModalContext.cancelJobsRequestStatus === "Loading") {
return
}
this.setState({
...this.state,
cancelJobsModalContext: {
...this.state.cancelJobsModalContext,
cancelJobsRequestStatus: "Loading",
},
})
const cancelJobsResult = await this.props.jobService.cancelJobs(this.state.cancelJobsModalContext.jobsToCancel)
if (cancelJobsResult.failedJobCancellations.length === 0) {
// All succeeded
this.setState({
...this.state,
jobs: [],
selectedJobs: new Map<string, Job>(),
cancelJobsModalContext: {
jobsToCancel: [],
cancelJobsResult: cancelJobsResult,
modalState: "CancelJobsResult",
cancelJobsRequestStatus: "Idle",
},
})
} else if (cancelJobsResult.cancelledJobs.length === 0) {
// All failed
this.setState({
...this.state,
cancelJobsModalContext: {
...this.state.cancelJobsModalContext,
cancelJobsResult: cancelJobsResult,
modalState: "CancelJobsResult",
cancelJobsRequestStatus: "Idle",
},
})
} else {
// Some succeeded, some failed
this.setState({
...this.state,
jobs: [],
selectedJobs: new Map<string, Job>(),
cancelJobsModalContext: {
...this.state.cancelJobsModalContext,
jobsToCancel: cancelJobsResult.failedJobCancellations.map((failed) => failed.job),
cancelJobsResult: cancelJobsResult,
modalState: "CancelJobsResult",
cancelJobsRequestStatus: "Idle",
},
})
}
}
async reprioritizeJobs() {
if (this.state.reprioritizeJobsDialogContext.reprioritizeJobsRequestStatus === "Loading") {
return
}
this.setState({
...this.state,
reprioritizeJobsDialogContext: {
...this.state.reprioritizeJobsDialogContext,
reprioritizeJobsRequestStatus: "Loading",
},
})
const reprioritizeJobsResult = await this.props.jobService.reprioritizeJobs(
this.state.reprioritizeJobsDialogContext.jobsToReprioritize,
this.state.reprioritizeJobsDialogContext.newPriority,
)
if (reprioritizeJobsResult.failedJobReprioritizations.length === 0) {
// Succeeded
this.setState({
...this.state,
jobs: [],
selectedJobs: new Map<string, Job>(),
reprioritizeJobsDialogContext: {
jobsToReprioritize: [],
isValid: false,
newPriority: 0,
reprioritizeJobsResult: reprioritizeJobsResult,
modalState: "ReprioritizeJobsResult",
reprioritizeJobsRequestStatus: "Idle",
},
})
} else if (reprioritizeJobsResult.reprioritizedJobs.length === 0) {
// Failure
this.setState({
...this.state,
reprioritizeJobsDialogContext: {
...this.state.reprioritizeJobsDialogContext,
reprioritizeJobsResult: reprioritizeJobsResult,
modalState: "ReprioritizeJobsResult",
reprioritizeJobsRequestStatus: "Idle",
},
})
} else {
// Some succeeded, some failed
this.setState({
...this.state,
jobs: [],
selectedJobs: new Map<string, Job>(),
reprioritizeJobsDialogContext: {
...this.state.reprioritizeJobsDialogContext,
jobsToReprioritize: reprioritizeJobsResult.failedJobReprioritizations.map((failed) => failed.job),
reprioritizeJobsResult: reprioritizeJobsResult,
modalState: "ReprioritizeJobsResult",
reprioritizeJobsRequestStatus: "Idle",
},
})
}
}
openJobDetailsModal(jobIndex: number) {
if (jobIndex < 0 || jobIndex >= this.state.jobs.length) {
return
}
const job = this.state.jobs[jobIndex]
this.setState({
...this.state,
jobDetailsModalContext: {
open: true,
job: job,
expandedItems: new Set(),
},
})
}
// Toggle expanded items in scheduling history in Job detail modal
toggleExpanded(item: string, isExpanded: boolean) {
const newExpanded = toggleExpanded(item, isExpanded, this.state.jobDetailsModalContext.expandedItems)
this.setState({
...this.state,
jobDetailsModalContext: {
...this.state.jobDetailsModalContext,
expandedItems: newExpanded,
},
})
}
closeJobDetailsModal() {
this.setState({
...this.state,
jobDetailsModalContext: {
...this.state.jobDetailsModalContext,
open: false,
},
})
}
async toggleAutoRefresh(autoRefresh: boolean) {
await setStateAsync(this, {
...this.state,
autoRefresh: autoRefresh,
})
this.tryStartAutoRefreshService()
}
tryStartAutoRefreshService() {
if (this.state.autoRefresh) {
this.autoRefreshService.start()
} else {
this.autoRefreshService.stop()
}
}
handlePriorityChange(newValue: string) {
const valid = newPriorityRegex.test(newValue) && newValue.length > 0
this.setState({
...this.state,
reprioritizeJobsDialogContext: {
...this.state.reprioritizeJobsDialogContext,
isValid: valid,
newPriority: Number(newValue),
},
})
}
registerResetCache(resetCache: () => void) {
this.resetCacheService.registerCallback(resetCache)
}
private createGetJobsRequest(): GetJobsRequest {
const request: GetJobsRequest = {
queue: "",
jobId: "",
owner: "",
jobSets: [],
newestFirst: true,
jobStates: [],
take: BATCH_SIZE,
skip: 0,
annotations: {},
}
for (const col of this.state.defaultColumns) {
switch (col.id) {
case "queue": {
request.queue = col.filter as string
break
}
case "jobId": {
request.jobId = col.filter as string
break
}
case "owner": {
request.owner = col.filter as string
break
}
case "jobSet": {
request.jobSets = [col.filter as string]
break
}
case "submissionTime": {
request.newestFirst = col.filter as boolean
break
}
case "jobState": {
request.jobStates = col.filter as string[]
break
}
}
}
for (const col of this.state.annotationColumns) {
if (col.filter) {
request.annotations[col.accessor] = col.filter as string
}
}
return request
}
private async setFilters(updatedState: JobsContainerState) {
this.localStorageService.saveState(updatedState)
this.queryParamsService.saveState(updatedState)
this.jobTableService.refresh()
await setStateAsync(this, {
...updatedState,
jobs: this.jobTableService.getJobs(),
})
this.resetCacheService.start()
}
private selectedJobsAreCancellable(): boolean {
return Array.from(this.state.selectedJobs.values())
.map((job) => job.jobState)
.some((jobState) => CANCELLABLE_JOB_STATES.includes(jobState))
}
private getCancellableSelectedJobs(selectedJobs: Map<string, Job>): Job[] {
return Array.from(selectedJobs.values()).filter((job) => CANCELLABLE_JOB_STATES.includes(job.jobState))
}
private selectedJobsAreReprioritizeable(): boolean {
return Array.from(this.state.selectedJobs.values())
.map((job) => job.jobState)
.some((jobState) => REPRIORITIZEABLE_JOB_STATES.includes(jobState))
}
private getReprioritizeableSelectedJobs(selectedJobs: Map<string, Job>): Job[] {
return Array.from(selectedJobs.values()).filter((job) => REPRIORITIZEABLE_JOB_STATES.includes(job.jobState))
}
render() {
return (
<Fragment>
<CancelJobsModal
modalState={this.state.cancelJobsModalContext.modalState}
jobsToCancel={this.state.cancelJobsModalContext.jobsToCancel}
cancelJobsResult={this.state.cancelJobsModalContext.cancelJobsResult}
cancelJobsRequestStatus={this.state.cancelJobsModalContext.cancelJobsRequestStatus}
onCancelJobs={this.cancelJobs}
onClose={() => this.setCancelJobsModalState("None")}
/>
<ReprioritizeJobsDialog
modalState={this.state.reprioritizeJobsDialogContext.modalState}
jobsToReprioritize={this.state.reprioritizeJobsDialogContext.jobsToReprioritize}
reprioritizeJobsResult={this.state.reprioritizeJobsDialogContext.reprioritizeJobsResult}
reprioritizeJobsRequestStatus={this.state.reprioritizeJobsDialogContext.reprioritizeJobsRequestStatus}
isValid={this.state.reprioritizeJobsDialogContext.isValid}
newPriority={this.state.reprioritizeJobsDialogContext.newPriority}
onReprioritizeJobs={this.reprioritizeJobs}
onPriorityChange={this.handlePriorityChange}
onClose={() => this.setReprioritizeJobsDialogState("None")}
/>
<JobDetailsModal
{...this.state.jobDetailsModalContext}
logService={this.props.logService}
onToggleExpanded={this.toggleExpanded}
onClose={this.closeJobDetailsModal}
/>
<Jobs
jobs={this.state.jobs}
defaultColumns={this.state.defaultColumns}
annotationColumns={this.state.annotationColumns}
selectedJobs={this.state.selectedJobs}
autoRefresh={this.state.autoRefresh}
getJobsRequestStatus={this.state.getJobsRequestStatus}
cancelJobsButtonIsEnabled={this.selectedJobsAreCancellable()}
reprioritizeButtonIsEnabled={this.selectedJobsAreReprioritizeable()}
fetchJobs={this.serveJobs}
isLoaded={this.jobIsLoaded}
onChangeColumnValue={this.changeColumnFilter}
onDisableColumn={this.disableColumn}
onDeleteColumn={this.deleteAnnotationColumn}
onAddColumn={this.addAnnotationColumn}
onChangeAnnotationColumnKey={this.changeAnnotationColumnKey}
onRefresh={this.refresh}
onSelectJob={this.selectJob}
onShiftSelect={this.shiftSelectJob}
onDeselectAllClick={this.deselectAll}
onCancelJobsClick={() => this.setCancelJobsModalState("CancelJobs")}
onReprioritizeJobsClick={() => this.setReprioritizeJobsDialogState("ReprioritizeJobs")}
onJobIdClick={this.openJobDetailsModal}
onAutoRefreshChange={this.toggleAutoRefresh}
onInteract={this.resetAutoRefresh}
onRegisterResetCache={this.registerResetCache}
onClear={this.clearFilters}
/>
</Fragment>
)
}
}
export default withRouter(JobsContainer) | the_stack |
import { Tournament, Player } from '..';
import { DeepPartial } from '../../utils/DeepPartial';
import { Design } from '../../Design';
import { deepMerge } from '../../utils/DeepMerge';
import {
FatalError,
TournamentError,
NotSupportedError,
} from '../../DimensionError';
import { Dimension, NanoID } from '../../Dimension';
import EliminationState = Elimination.State;
import EliminationConfigs = Elimination.Configs;
import { RankSystem } from '../RankSystem';
/**
* The Elimination Tournament Class. Runs a single-elimination tournament.
*
* Meant for single instance use only
*/
export class Elimination extends Tournament {
configs: Tournament.TournamentConfigs<EliminationConfigs> = {
defaultMatchConfigs: {},
type: Tournament.Type.ELIMINATION,
rankSystem: null,
rankSystemConfigs: null,
tournamentConfigs: {
times: 1,
storePastResults: true,
lives: 1,
seeding: null,
},
resultHandler: null,
agentsPerMatch: [2],
consoleDisplay: true,
id: 'z3Ap49',
};
state: EliminationState = {
playerStats: new Map(),
statistics: {
totalMatches: 0,
},
currentRound: null,
results: [],
resultsMap: new Map(),
};
matchHashes: Array<string> = [];
type = Tournament.Type.ELIMINATION;
private shouldStop = false;
private resumePromise: Promise<void>;
private resumeResolver: Function;
private resolveStopPromise: Function;
constructor(
design: Design,
files: Array<string> | Array<{ file: string; name: string }>,
tournamentConfigs: Tournament.TournamentConfigsBase,
id: NanoID,
dimension: Dimension
) {
super(design, id, tournamentConfigs, dimension);
if (tournamentConfigs.consoleDisplay) {
this.configs.consoleDisplay = tournamentConfigs.consoleDisplay;
}
this.configs = deepMerge(this.configs, tournamentConfigs, true);
if (typeof this.configs.rankSystem === 'string') {
switch (tournamentConfigs.rankSystem) {
case Tournament.RankSystemTypes.WINS: {
// set default rank system configs
const winsConfigs: RankSystem.Wins.Configs = {
winValue: 3,
lossValue: 0,
tieValue: 0,
descending: true,
};
if (this.configs.rankSystemConfigs === null) {
this.configs.rankSystemConfigs = winsConfigs;
}
break;
}
default:
throw new NotSupportedError(
'We currently do not support this rank system for elimination tournaments'
);
}
} else {
throw new NotSupportedError(
"We do not support custom rank systems for elimination tournaments. Please pass in 'wins' or Tournament.RankSystemTypes.WINS instead"
);
}
// add all players
files.forEach((file) => {
this.addplayer(file);
});
}
/**
* Get the current tournament configs
*/
public getConfigs(): Tournament.TournamentConfigs<EliminationConfigs> {
return this.configs;
}
/**
* Set configs to use. Merges the provided configurations and overwrites provided fields with what is provided
* @param configs - new tournament configs to update with
*/
public setConfigs(
configs: DeepPartial<Tournament.TournamentConfigs<EliminationConfigs>> = {}
): void {
this.configs = deepMerge(this.configs, configs, true);
}
/**
* Gets the rankings of the tournament. This will return the tournament rankings in the elimination tournament
*/
public getRankings(): Array<{
player: Player;
wins: number;
losses: number;
matchesPlayed: number;
seed: number;
rank: number;
}> {
const ranks = Array.from(this.state.playerStats).sort(
(a, b) => a[1].rank - b[1].rank
);
return ranks.map((a) => a[1]);
}
/**
* Stops the tournament if it's running
*/
public stop(): Promise<void> {
return new Promise((resolve, reject) => {
if (this.status !== Tournament.Status.RUNNING) {
reject(
new TournamentError(`Can't stop a tournament that isn't running`)
);
}
this.log.info('Stopping Tournament...');
this.status = Tournament.Status.STOPPED;
this.resumePromise = new Promise((resumeResolve) => {
this.resumeResolver = resumeResolve;
});
this.shouldStop = true;
this.resolveStopPromise = resolve;
});
}
/**
* Reesumes the tournament if it's stopped
*/
public async resume(): Promise<void> {
if (this.status !== Tournament.Status.STOPPED) {
throw new TournamentError(`Can't resume a tournament that isn't stopped`);
}
this.log.info('Resuming Tournament...');
this.status = Tournament.Status.RUNNING;
this.resumeResolver();
}
/**
* Runs the tournament to completion. Resolves with {@link Elimination.State} once the tournament is finished
* @param configs - tournament configurations to use
*/
public async run(
configs?: DeepPartial<Tournament.TournamentConfigs<EliminationConfigs>>
): Promise<Elimination.State> {
this.configs = deepMerge(this.configs, configs, true);
this.initialize();
this.status = Tournament.Status.RUNNING;
while (this.matchQueue.length) {
// stop logic
if (this.shouldStop) {
this.log.info('Stopped Tournament');
this.resolveStopPromise();
// we wait for the resume function to resolve the resumePromise to continue the loop
await this.resumePromise;
this.log.info('Resumed Tournament');
this.shouldStop = false;
}
const queuedMatchInfo = this.matchQueue.shift();
const matchHash = this.matchHashes.shift();
await this.handleMatch(queuedMatchInfo, matchHash);
if (this.state.currentRound === 2) {
break;
}
if (this.matchQueue.length === 0) {
// once a round is done, perform the next round
this.generateRound();
}
}
this.status = Tournament.Status.FINISHED;
return this.state;
}
/**
* Handles a match and updates stats appropriately
* @param matchInfo - The match to run
*/
private async handleMatch(
queuedMatchInfo: Tournament.QueuedMatch,
matchHash: string
) {
const matchInfo = await this.getMatchInfoFromQueuedMatch(queuedMatchInfo);
if (matchInfo.length != 2) {
throw new FatalError(
`This shouldn't happen, tried to run a match with player count not equal to 2 in an elimination tournament`
);
}
// deal with case when one is a null, likely meaning a competitor has a bye
if (matchInfo[0] == null) {
const winner = matchInfo[1];
// store result into with matchHash key
this.state.resultsMap.set(matchHash, { winner: winner, loser: null });
return;
} else if (matchInfo[1] == null) {
const winner = matchInfo[0];
// store result into with matchHash key
this.state.resultsMap.set(matchHash, { winner: winner, loser: null });
return;
}
this.log.detail(
'Running match - Competitors: ',
matchInfo.map((player) => {
return player.tournamentID.name;
})
);
const matchRes = await this.runMatch(matchInfo);
const res: RankSystem.Results = this.configs.resultHandler(
matchRes.results
);
// store past results
if (this.configs.tournamentConfigs.storePastResults) {
if (
!(
this.dimension.hasDatabase() &&
this.dimension.databasePlugin.configs.saveTournamentMatches
)
) {
// if we have don't have a database that is set to actively store tournament matches we store locally
this.state.results.push(res);
}
}
this.state.statistics.totalMatches++;
const rankSystemConfigs: RankSystem.Wins.Configs = this.configs
.rankSystemConfigs;
// maps tournament ID to scores
const parsedRes = {};
const p0ID = matchInfo[0].tournamentID.id;
const p1ID = matchInfo[1].tournamentID.id;
parsedRes[p0ID] = 0;
parsedRes[p1ID] = 0;
res.ranks.sort((a, b) => a.rank - b.rank);
if (res.ranks[0].rank === res.ranks[1].rank) {
res.ranks.forEach((info) => {
const tournamentID = matchRes.match.mapAgentIDtoTournamentID.get(
info.agentID
);
parsedRes[tournamentID.id] += rankSystemConfigs.tieValue;
});
} else {
const winningTournamentID = matchRes.match.mapAgentIDtoTournamentID.get(
res.ranks[0].agentID
);
const losingTournamentID = matchRes.match.mapAgentIDtoTournamentID.get(
res.ranks[1].agentID
);
parsedRes[winningTournamentID.id] += rankSystemConfigs.winValue;
parsedRes[losingTournamentID.id] += rankSystemConfigs.lossValue;
}
// using scores, determine winner
let winner = this.state.playerStats.get(p0ID);
let loser = this.state.playerStats.get(p1ID);
if (parsedRes[p0ID] < parsedRes[p1ID]) {
winner = this.state.playerStats.get(p1ID);
loser = this.state.playerStats.get(p0ID);
} else if (parsedRes[p0ID] === parsedRes[p1ID]) {
if (Math.random() > 0.5) {
winner = this.state.playerStats.get(p1ID);
loser = this.state.playerStats.get(p0ID);
}
}
// update stats
winner.wins++;
winner.matchesPlayed++;
loser.losses++;
loser.matchesPlayed++;
loser.rank = this.state.currentRound;
// store result into with matchHash key
this.state.resultsMap.set(matchHash, {
winner: winner.player,
loser: loser.player,
});
}
private initialize() {
this.state.playerStats = new Map();
this.state.results = [];
switch (this.configs.rankSystem) {
case Tournament.RankSystemTypes.WINS: {
// set up the seeding array and fill it up with null to fill up all empty spots
let seeding = this.configs.tournamentConfigs.seeding;
if (seeding == null) seeding = [];
if (seeding.length > this.competitors.size) {
throw new TournamentError(
`Seeds provided cannot be greater than the number of competitors`
);
}
for (let i = 0; i < this.competitors.size - seeding.length; i++) {
seeding.push(null);
}
// find the leftover seeds that are not used
const leftOverSeeds: Set<number> = new Set();
for (let i = 0; i < this.competitors.size; i++) {
leftOverSeeds.add(i + 1);
}
for (let i = 0; i < seeding.length; i++) {
if (seeding[i] != null) {
if (leftOverSeeds.has(seeding[i])) {
leftOverSeeds.delete(seeding[i]);
} else {
throw new TournamentError(
`Duplicate seeds are not allowed. There are duplicate seeds of ${seeding[i]}`
);
}
}
}
let leftOverSeedsArr = Array.from(leftOverSeeds);
leftOverSeedsArr = this.shuffle(leftOverSeedsArr);
// setup the stats
this.competitors.forEach((player, index) => {
const seed = seeding[index];
const playerStat = {
player: player,
wins: 0,
losses: 0,
matchesPlayed: 0,
seed: seed != null ? seed : leftOverSeedsArr.shift(),
rank: 1,
};
this.state.playerStats.set(player.tournamentID.id, playerStat);
});
break;
}
}
const pow = Math.ceil(Math.log2(this.competitors.size));
const round = Math.pow(2, pow);
this.state.currentRound = round;
// generate rounds to play
this.generateFirstRounds();
this.status = Tournament.Status.INITIALIZED;
}
private generateFirstRounds() {
// get players in order of seed
const round = this.state.currentRound;
const seededArr = Array.from(this.state.playerStats).sort(
(a, b) => a[1].seed - b[1].seed
);
// 1 goes against round, 2 goes against round - 1...
for (let i = 0; i < round / 2; i++) {
const p1 = seededArr[i][1].player;
const oseed = round - (i + 1);
let p2: Player = null; // a null is a bye
if (seededArr.length > oseed) {
p2 = seededArr[oseed][1].player;
}
this.matchQueue.push([p1.tournamentID.id, p2.tournamentID.id]);
// hashes are of the form `betterseed,worseseed`, which has a 1-1 bijection with the match that should be played
// in a elimination tournament. e.g 8,9 is a matchup that can happen is during the round of (8 + 9 - 1) = 16
this.matchHashes.push(`${i + 1},${oseed + 1}`);
}
}
private generateRound() {
const oldRound = this.state.currentRound;
const nextRound = Math.floor(oldRound / 2);
// generate new hashes
const hashes: Array<Array<number>> = [];
for (let i = 0; i < nextRound / 2; i++) {
const oseed = nextRound - (i + 1);
hashes.push([i + 1, oseed + 1]);
}
// for each hash is a new match to queue up, find the winners from the previous rounds
for (let i = 0; i < hashes.length; i++) {
const hash = hashes[i];
// we can generate the match right before this one in the winners bracket through simple arithmetic
// and knowing that each hash[i] represents the better seed as it is in the next round
const oldOpponent1 = oldRound - hash[0] + 1;
const res1 = this.state.resultsMap.get(`${hash[0]},${oldOpponent1}`);
const p1 = res1.winner;
const oldOpponent2 = oldRound - hash[1] + 1;
const res2 = this.state.resultsMap.get(`${hash[1]},${oldOpponent2}`);
const p2 = res2.winner;
this.matchHashes.push(`${hash[0]},${hash[1]}`);
this.matchQueue.push([p1.tournamentID.id, p2.tournamentID.id]);
}
this.state.currentRound = nextRound;
}
/**
* Performs a Fisher Yates Shuffle
* @param arr - the array to shuffle
*/
private shuffle(arr: any[]) {
for (let i = arr.length - 1; i >= 1; i--) {
const j = Math.floor(Math.random() * i);
const tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
return arr;
}
async internalAddPlayer(): Promise<void> {
if (
this.status === Tournament.Status.INITIALIZED ||
this.status === Tournament.Status.RUNNING
)
throw new TournamentError(
'You are not allowed to add a player during the middle or after initialization of elimination tournaments'
);
}
async updatePlayer(): Promise<void> {
throw new TournamentError(
'You are not allowed to update a player during elimination tournaments'
);
}
}
/**
* The Elimination Tournament namespace
*/
export namespace Elimination {
/**
* Configuration interface for Elimination Tournaments
*/
export interface Configs extends Tournament.TournamentTypeConfig {
/**
* Number of times the elimination tournament runs
* @default `2`
*/
times: number;
/**
* Number of times a player can lose before being eliminated. Can be 1 for single elimination. 2 for double
* elimination is not implemented yet
* @default `1`
*/
lives: 1;
/**
* The seeding of the competitors in the order they are loaded.
* When set to null, no seeds are used. When the ith array element is null, the ith competitor loaded, which has * tournament ID of i, does not have a seed.
* @default `null`
*/
seeding: Array<number>;
}
/**
* The Elimination Tournament state, consisting of the current player statistics and past results
*/
export interface State extends Tournament.TournamentTypeState {
/**
* A map from a {@link Player} Tournament ID string to statistics
*/
playerStats: Map<
string,
{
player: Player;
wins: number;
losses: number;
matchesPlayed: number;
seed: number;
rank: number;
}
>;
/**
* Stats for this Tournament in this instance. Intended to be constant memory usage
*/
statistics: {
totalMatches: number;
};
currentRound: number;
/**
* A match hash in the tournament indicating what seeds are meant to compete against each other.
* This maps a match hash to the result at the part of the tournament, indicating who won and lost
*/
resultsMap: Map<string, { winner: Player; loser: Player }>;
}
} | the_stack |
'use strict';
import { GenericOAuth2Router } from '../common/generic-router';
import { AuthRequest, EndpointDefinition, AuthResponse, IdentityProvider, IdpOptions, OAuth2IdpConfig, ExpressHandler, CheckRefreshDecision, ErrorLink } from '../common/types';
import { OidcProfile, Callback, WickedApi } from 'wicked-sdk';
const { debug, info, warn, error } = require('portal-env').Logger('portal-auth:oauth2');
const Router = require('express').Router;
const request = require('request');
const passport = require('passport');
const { Issuer } = require('openid-client');
var OAuth2Strategy = require('passport-oauth').OAuth2Strategy;
var jwt = require('jsonwebtoken');
import { utils } from '../common/utils';
import { failMessage, failError, failOAuth, makeError } from '../common/utils-fail';
/**
* This is a sample of how an IdP must work to be able to integrate into
* the generic OAuth2 workflow in generic.js
*/
export class OAuth2IdP implements IdentityProvider {
private genericFlow: GenericOAuth2Router;
private basePath: string;
private authMethodId: string;
private options: IdpOptions;
private authMethodConfig: OAuth2IdpConfig;
// private authenticateWithOAuth2: ExpressHandler;
private authenticateCallback: ExpressHandler;
private baseAuthenticateSettings: any;
constructor(basePath: string, authMethodId: string, authMethodConfig: any, options: IdpOptions) {
debug(`constructor(${basePath}, ${authMethodId},...)`);
this.genericFlow = new GenericOAuth2Router(basePath, authMethodId);
this.basePath = basePath;
this.authMethodId = authMethodId;
this.authMethodConfig = authMethodConfig;
// Verify configuration
if (!authMethodConfig.clientId)
throw new Error(`OAuth2 auth method "${authMethodId}": In auth method configuration, property "config", the property "clientId" is missing.`);
if (!authMethodConfig.clientSecret)
throw new Error(`OAuth2 auth method "${authMethodId}": In auth-server configuration, property "config", the property "clientSecret" is missing.`);
if (!authMethodConfig.endpoints)
throw new Error(`OAuth2 auth method ${authMethodId}: In auth method configuration, property, config, the property "endpoints" is missing.`);
if (!authMethodConfig.endpoints.authorizeEndpoint)
throw new Error(`OAuth2 auth method ${authMethodId}: In auth method configuration, property, config, the property "endpoints.authorizeEndpoint" is missing.`);
if (!authMethodConfig.endpoints.tokenEndpoint)
throw new Error(`OAuth2 auth method ${authMethodId}: In auth method configuration, property, config, the property "endpoints.tokenEndpoint" is missing.`);
// Assemble the callback URL
const callbackUrl = `${options.externalUrlBase}/${authMethodId}/callback`;
info(`OAuth2 Authentication: Expected callback URL: ${callbackUrl}`);
const oauthStrategy = new OAuth2Strategy({
authorizationURL: authMethodConfig.endpoints.authorizeEndpoint,
tokenURL: authMethodConfig.endpoints.tokenEndpoint,
clientID: authMethodConfig.clientId,
clientSecret: authMethodConfig.clientSecret,
callbackURL: callbackUrl,
passReqToCallback: true,
}, this.verifyProfile);
// The authorization parameters can differ for each authorization
// request; it cannot be static (e.g. due to "prompt" or "prefill_username"
// parameters).
oauthStrategy.authorizationParams = this.authorizationParams;
oauthStrategy.userProfile = function (accessToken, done) {
debug(`userProfile(${this.authMethodId})`);
if (authMethodConfig.retrieveProfile) {
debug(`userProfile(${this.authMethodId}): Retrieve userProfile from profileEndpoint`);
let issuer = new Issuer({
issuer: "IdP Issuer",
authorization_endpoint: authMethodConfig.endpoints.authorizeEndpoint,
token_endpoint: authMethodConfig.endpoints.tokenEndpoint,
userinfo_endpoint: authMethodConfig.endpoints.profileEndpoint
});
let client = new issuer.Client({
client_id: authMethodConfig.clientId,
client_secret: authMethodConfig.clientSecret,
redirect_uris: [callbackUrl],
response_types: ['code']
});
client.userinfo(accessToken)
.then(function (userInfo) {
debug(`retrieveUserProfileCallback: Successfully retrieved profile from endpoint`);
done(null, userInfo);
})
} else {
done(null, accessToken);
}
};
passport.use(authMethodId, oauthStrategy);
let scope: string[] = null;
if (authMethodConfig.endpoints.authorizeScope) {
scope = authMethodConfig.endpoints.authorizeScope.split(' ');
}
this.baseAuthenticateSettings = {
session: false,
scope: scope,
};
this.genericFlow.initIdP(this);
}
public getType() {
return "oauth2";
}
public supportsPrompt(): boolean {
const promptSupported = this.authMethodConfig.doesNotSupportPrompt ? false : true;
debug(`supportsPrompt(): ${promptSupported}`);
return promptSupported;
}
public getRouter() {
return this.genericFlow.getRouter();
}
private verifyProfile = (req, accessToken, refreshTokenNotUsed, profile, done) => {
debug(`verifyProfile(${this.authMethodId})`);
if (!this.authMethodConfig.retrieveProfile) {
// Verify signing?
try {
profile = this.verifyJWT(accessToken);
debug(`verifyProfile(${this.authMethodId}): Decoded JWT Profile:`);
} catch (ex) {
error(`verifyProfile(${this.authMethodId}): JWT decode/verification failed.`);
return done(null, false, { message: ex });
}
}
debug(`verifyProfile(${this.authMethodId}): Retrieved Profile:`);
debug(profile);
try {
const authResponse = this.createAuthResponse(profile);
return done(null, authResponse);
} catch (err) {
return done(null, false, { message: err });
}
}
private verifyJWT = (accessToken) => {
if (this.authMethodConfig.certificate) {
// Decode Oauth token and verify that it has been signed by the given public cert
debug(`verifyJWT(${this.authMethodId}): Verifying JWT signature and decoding profile`);
return jwt.verify(accessToken, this.authMethodConfig.certificate);
} else {
// Do not check signing, just decode
warn(`verifyJWT(${this.authMethodId}): Decoding JWT signature, NOT verifying signature, "certificate" not specified`)
return jwt.decode(accessToken);
}
}
private authorizationParams = (options) => {
debug(`authorizationParams(): ${JSON.stringify(options)}`);
let params: any = {};
if (this.authMethodConfig.resource || this.authMethodConfig.params) {
if (this.authMethodConfig.params)
params = Object.assign({}, this.authMethodConfig.params);
if (this.authMethodConfig.resource)
params.resource = this.authMethodConfig.resource;
}
if (options.prefill_username) {
params.prefill_username = options.prefill_username;
}
if (options.prompt) {
params.prompt = options.prompt;
}
if (options.state) {
params.state = options.state;
}
return params;
}
/**
* In case the user isn't already authenticated, this method will
* be called from the generic flow implementation. It is assumed to
* initiate an authentication of the user by whatever means is
* suitable, depending on the actual Identity Provider implementation.
*
* If you need additional end points responding to any of your workflows,
* register them with the `endpoints()` method below.
*
* `authRequest` contains information on the authorization request,
* in case those are needed (such as for displaying information on the API
* or similar).
*/
public authorizeWithUi(req, res, next, authRequest: AuthRequest) {
debug('authorizeWithUi()');
debug(`authRequest: ${JSON.stringify(authRequest)}`)
// Do your thing...
const additionalSettings: any = {};
// Propagate additional parameters; the settings object is combined with these
// additionalSettings, and this is passed in to the authorizationParams method
// above, so that we can take them out again. A little complicated, but it works.
if (authRequest.prompt) {
additionalSettings.prompt = authRequest.prompt;
}
if (authRequest.prefill_username) {
additionalSettings.prefill_username = authRequest.prefill_username;
}
if (this.authMethodConfig.forwardState && authRequest.state) {
additionalSettings.state = authRequest.state;
}
const settings = Object.assign({}, this.baseAuthenticateSettings, additionalSettings);
passport.authenticate(this.authMethodId, settings)(req, res, next);
};
public getErrorLinks(): ErrorLink {
if (this.authMethodConfig.errorLink && this.authMethodConfig.errorLinkDescription) {
return {
url: this.authMethodConfig.errorLink,
description: this.authMethodConfig.errorLinkDescription
};
}
return null;
}
/**
* In case you need additional end points to be registered, pass them
* back to the generic flow implementation here; they will be registered
* as "/<authMethodName>/<uri>", and then request will be passed into
* the handler function, which is assumed to be of the signature
* `function (req, res, next)` (the standard Express signature)
*/
public endpoints(): EndpointDefinition[] {
// This is just a sample endpoint; usually this will be like "callback",
// e.g. for OAuth2 callbacks or similar.
return [
{
method: 'get',
uri: '/callback',
handler: this.callbackHandler
}
];
};
/**
* Verify username and password and return the data on the user, like
* when authorizing via some 3rd party. If this identity provider cannot
* authenticate via username and password, an error will be returned.
*
* @param {*} user Username
* @param {*} pass Password
* @param {*} callback Callback method, `function(err, authenticationData)`
*/
public authorizeByUserPass(user: string, pass: string, callback: Callback<AuthResponse>) {
const postBody = {
grant_type: "password",
username: user,
password: pass,
client_id: this.authMethodConfig.clientId,
client_secret: this.authMethodConfig.clientSecret,
scope: this.authMethodConfig.endpoints.authorizeScope
};
const config = utils.getJson(this.authMethodConfig);
if (config.params) {
Object.keys(config.params).map((key) => {
postBody[key] = config.params[key];
});
}
const uri = this.authMethodConfig.endpoints.tokenEndpoint;
const instance = this;
const postBodyParams = Object.keys(postBody).map((key) => {
return `${encodeURIComponent(key)}=${encodeURIComponent(postBody[key])}`;
}).join('&');
request.post({
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
uri,
body: postBodyParams
}, function (err, res, responseBody) {
try {
const jsonResponse = utils.getJson(responseBody);
if (res.statusCode !== 200 || jsonResponse.error) {
const err = makeError(`External IDP ${instance.authMethodId} returned an error or an unexpected status code (${res.statusCode})`, res.statusCode);
if (jsonResponse.error)
err.internalError = new Error(`Error: ${jsonResponse.error}, description. ${jsonResponse.error_description || '<no description>'}`);
return callback(err);
}
return instance.verifyProfile(null, jsonResponse.access_token, null, null, callback);
} catch (err) {
error(err);
return callback(err);
}
});
};
public checkRefreshToken(tokenInfo, apiInfo: WickedApi, callback: Callback<CheckRefreshDecision>) {
// Decide whether it's okay to refresh this token or not, e.g.
// by checking that the user is still valid in your database or such;
// for 3rd party IdPs, this may be tricky.
return callback(null, {
allowRefresh: true
});
};
/**
* Callback handler; this is the endpoint which is called when the OAuth2 provider
* returns with a success or failure response.
*/
private callbackHandler = (req, res, next) => {
// Here we want to assemble the default profile and stuff.
debug('callbackHandler()');
const instance = this;
// Do we have errors from the upstream IdP here?
if (req.query && req.query.error) {
warn(`${instance.authMethodId}.callbackHandler detected ${req.query.error} error`);
// Super special case: We get an unsolicited callback *with an error*. In this case,
// we can only display an HTML error message. Otherwise (if we know which client initiated
// the authorization request) we will redirect back to the calling client with
// the error and error_description we received here.
let authRequest;
try {
authRequest = utils.getAuthRequest(req, instance.authMethodId);
} catch (err) {
warn(`${instance.authMethodId}.callbackHandler: Invalid state: No authRequest in session`);
warn(err.stack);
}
if (authRequest) {
// This is the normal case - we get an upstream IdP error which we will forward to
// the downstream client.
(async () => {
await instance.genericFlow.failAuthorizeFlow(req, res, next, req.query.error, req.query.error_description);
})();
return;
} else {
// We have no idea where this callback actually came from, so we'll resort to displaying
// an error message instead (as HTML).
return failMessage(400, `Unexpected callback; identity provider returned error: ${req.query.error} (${req.query.error_description})`, next);
}
}
// We don't have any explicit and direct errors, so we will probably have
// an authorization code. Delegate this to passport again, and then continue
// from there when passport calls the "next" function, which is passed inline
// here.
passport.authenticate(this.authMethodId, this.baseAuthenticateSettings)(req, res, function (err) {
if (err)
return next(err);
// The authResponse is now in req.user (for this call), and we can pass that on as an authResponse
// to continueAuthorizeFlow. Note the usage of "session: false", so that this data is NOT stored
// automatically in the user session, which passport usually does by default.
debug('Successfully authenticated via passport.');
const authResponse = req.user;
instance.genericFlow.continueAuthorizeFlow(req, res, next, authResponse);
});
};
// HELPER METHODS
private createAuthResponse(profile: any): AuthResponse {
debug(`createAuthResponse(${this.authMethodId})`);
const defaultProfile = this.createDefaultProfile(profile);
const defaultGroups = this.createDefaultGroups(profile);
const customId = defaultProfile.sub;
return {
userId: null,
customId: customId,
defaultGroups: defaultGroups,
defaultProfile: defaultProfile
};
}
private createDefaultProfile(profile): OidcProfile {
debug(`createDefaultProfile(${this.authMethodId}`);
let customIdField = this.authMethodConfig.customIdField ? this.authMethodConfig.customIdField : 'upn';
let nameField = this.authMethodConfig.nameField ? this.authMethodConfig.nameField : 'name';
let firstNameField = this.authMethodConfig.firstNameField ? this.authMethodConfig.firstNameField : 'given_name';
let lastNameField = this.authMethodConfig.lastNameField ? this.authMethodConfig.lastNameField : 'family_name';
let emailField = this.authMethodConfig.emailField ? this.authMethodConfig.emailField : 'email';
if (!profile[emailField])
throw makeError('Profile must contain a valid email address.', 400);
if (!profile[customIdField])
throw makeError('Profile must contain a unique identifier field (custom ID field, UPN or similar)', 400);
const customId = `${this.authMethodId}:${profile[customIdField]}`;
const defaultProfile: OidcProfile = {
sub: customId,
email: profile[emailField],
email_verified: !!this.authMethodConfig.trustUsers
};
const name = profile[nameField];
const firstName = profile[firstNameField];
const lastName = profile[lastNameField];
if (name)
defaultProfile.name = name;
else
defaultProfile.name = utils.makeFullName(lastName, firstName);
if (firstName)
defaultProfile.given_name = firstName;
if (lastName)
defaultProfile.family_name = lastName;
// Iterate over the rest of the claims as well and return them
for (let key in profile) {
// Claim already present?
if (defaultProfile.hasOwnProperty(key))
continue;
const value = profile[key];
switch (typeof (value)) {
case "string":
case "number":
defaultProfile[key] = value;
break;
default:
debug(`createAuthResponse(${this.authMethodId}: Skipping non-string/non-number profile key ${key}`);
break;
}
}
return defaultProfile;
}
private createDefaultGroups(profile: any): string[] {
debug(`createDefaultGroups(${this.authMethodId})`);
if (!this.authMethodConfig.defaultGroups)
return [];
const groupField = this.authMethodConfig.groupField ? this.authMethodConfig.groupField : 'group';
if (!profile[groupField])
return [];
const groups = profile[groupField];
if (!Array.isArray(groups)) {
warn(`createDefaultGroups(${this.authMethodId}): When creating profile, field ${groupField} is not a string array, defaulting to no groups.`);
return [];
}
const defaultGroups = [];
const groupMap = this.authMethodConfig.defaultGroups;
for (let i = 0; i < groups.length; ++i) {
const g = groups[i];
if (groupMap[g]) {
const wickedGroup = groupMap[g];
debug(`Detected matching group ${g}: ${wickedGroup}`);
defaultGroups.push(wickedGroup);
}
}
debug(`createDefaultGroups(${this.authMethodId}): ${defaultGroups}`);
return defaultGroups;
}
} | the_stack |
import test from 'tape'
import BN from 'bn.js'
import { ethers } from "ethers"
import { ecrecover, privateToPublic, fromRpcSig } from 'ethereumjs-util'
import { LocalAddress, CryptoUtils } from '../../index'
import { LoomProvider } from '../../loom-provider'
import { soliditySha3 } from '../../solidity-helpers'
import { bytesToHexAddr } from '../../crypto-utils'
import { deployContract } from '../evm-helpers'
import { createTestClient, rejectOnTimeOut, createWeb3TestClient } from '../helpers'
import { SimpleStore } from './test-contract/SimpleStore'
test("LoomProvider/Ethers Eth Sign (/query)", (t) => testEthersSign(t, false))
test("LoomProvider/Ethers Eth Sign (/eth)", (t) => testEthersSign(t, true))
test('LoomProvider/Ethers Get version (/query)', (t: any) => testNetId(t, false))
test('LoomProvider/Ethers Get version (/eth)', (t: any) => testNetId(t, true))
test('LoomProvider/Ethers getBlockNumber (/query)', (t: any) => testBlockNumber(t, false))
test('LoomProvider/Ethers getBlockNumber (/eth)', (t: any) => testBlockNumber(t, true))
// /query getBlockByNumber fails: invalid hash (arg="hash", value=undefined, version=4.0.26)
test.skip('LoomProvider/Ethers getBlockByNumber (/query)', (t) => testBlockByNumber(t, false))
test('LoomProvider/Ethers getBlockByNumber (/eth)', (t) => testBlockByNumber(t, true))
// /query getBlockByNumber fails: invalid hash (arg="hash", value=undefined, version=4.0.26)
test.skip('LoomProvider/Ethers getBlock by hash (/query)', (t) => testBlockByHash(t, false))
test('LoomProvider/Ethers getBlock by hash (/eth)', (t) => testBlockByHash(t, true))
// Fails : LoomProvider returns null, ethers expects number
test.skip('LoomProvider/Ethers getGasPrice (/query)', (t) => testGasPrice(t, false))
test.skip('LoomProvider/Ethers getGasPrice (/eth)', (t) => testGasPrice(t, true))
test('LoomProvider/Ethers getBalance (/query)', (t) => testBalance(t, false))
test('LoomProvider/Ethers getBalance (/eth)', (t) => testBalance(t, true))
test('LoomProvider/Ethers getTransactionReceipt (/query)', (t) => testTransactionReceipt(t, false))
test('LoomProvider/Ethers getTransactionReceipt (/eth)', (t) => testTransactionReceipt(t, true))
test.skip('LoomProvider/Ethers Logs (/query)', (t) => testPastEvents(t, false))
test('LoomProvider/Ethers Logs (/eth)', (t: any) => testPastEvents(t, true))
test('LoomProvider/Ethers getStorageAt (/eth)', (t: any) => testGetStorageAt(t, true))
test.skip("LoomProvider/Ethers Event topics (/query)", (t) => testMismatchedTopic(t, true))
test.skip("LoomProvider/Ethers Event topics (/eth)", (t) => testMismatchedTopic(t, true))
async function testEthersSign(t: test.Test, useEthEndpoint: boolean) {
const { client, ethersProvider, from, privKey } = await newContractAndClient(useEthEndpoint)
try {
const msg = '0xff'
const result = await ethersProvider.getSigner().signMessage(ethers.utils.arrayify(msg))
// Checking the ecrecover
const hash = soliditySha3('\x19Ethereum Signed Message:\n32', msg).slice(2)
const { r, s, v } = fromRpcSig(result)
const pubKey = ecrecover(Buffer.from(hash, 'hex'), v, r, s)
const privateHash = soliditySha3(privKey).slice(2)
t.equal(
bytesToHexAddr(pubKey),
bytesToHexAddr(privateToPublic(Buffer.from(privateHash, 'hex'))),
'Should pubKey from ecrecover be valid'
)
} catch (err) {
t.error(err)
}
client.disconnect()
t.end()
}
async function testNetId(t: any, useEthEndpoint: boolean) {
const { client, ethersProvider } = await newContractAndClient(useEthEndpoint)
try {
const chainIdHash = soliditySha3(client.chainId)
.slice(2)
.slice(0, 13)
const netVersionFromChainId = new BN(chainIdHash).toNumber()
const result = await ethersProvider.getNetwork()
t.equal(`${netVersionFromChainId}`, `${result.chainId}`, 'Should version match')
} catch (err) {
t.error(err)
}
client.disconnect()
t.end()
}
/**
* Requires the SimpleStore solidity contract deployed on a loomchain.
* go-loom/examples/plugins/evmexample/contract/SimpleStore.sol
*
* pragma solidity ^0.4.22;
*
* contract SimpleStore {
* uint value;
* constructor() public {
* value = 10;
* }
*
* event NewValueSet(uint indexed _value);
*
* function set(uint _value) public {
* value = _value;
* emit NewValueSet(value);
* }
*
* function get() public view returns (uint) {
* return value;
* }
* }
*
*
*/
const newContractAndClient = async (useEthEndpoint: boolean) => {
const privKey = CryptoUtils.generatePrivateKey()
const client = useEthEndpoint ? createWeb3TestClient() : createTestClient()
const from = LocalAddress.fromPublicKey(CryptoUtils.publicKeyFromPrivateKey(privKey)).toString()
const loomProvider = new LoomProvider(client, privKey)
const ethersProvider = new ethers.providers.Web3Provider(loomProvider);
client.on('error', console.log)
const contractData =
'0x608060405234801561001057600080fd5b50600a60008190555061010e806100286000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806360fe47b114604e5780636d4ce63c146078575b600080fd5b348015605957600080fd5b5060766004803603810190808035906020019092919050505060a0565b005b348015608357600080fd5b50608a60d9565b6040518082815260200191505060405180910390f35b806000819055506000547fb922f092a64f1a076de6f21e4d7c6400b6e55791cc935e7bb8e7e90f7652f15b60405160405180910390a250565b600080549050905600a165627a7a72305820b76f6c855a1f95260fc70490b16774074225da52ea165a58e95eb7a72a59d1700029'
const ABI = [
{
constant: false,
inputs: [{ name: '_value', type: 'uint256' }],
name: 'set',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'get',
outputs: [{ name: '', type: 'uint256' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{ inputs: [], payable: false, stateMutability: 'nonpayable', type: 'constructor' },
{
anonymous: false,
inputs: [{ indexed: true, name: '_value', type: 'uint256' }],
name: 'NewValueSet',
type: 'event'
}
]
const result = await deployContract(loomProvider, contractData)
const contract = new ethers.Contract(result.contractAddress, ABI, ethersProvider.getSigner()) as SimpleStore
return { contract, client, ethersProvider, from, privKey }
}
async function testBlockNumber(t: any, useEthEndpoint: boolean) {
const { client, ethersProvider } = await newContractAndClient(useEthEndpoint)
try {
const blockNumber = await ethersProvider.getBlockNumber()
t.assert(typeof blockNumber === 'number', 'Block number should be a number')
} catch (err) {
t.error(err)
}
client.disconnect()
t.end()
}
async function testBlockByNumber(t: any, useEthEndpoint: boolean) {
const { client, ethersProvider } = await newContractAndClient(useEthEndpoint)
try {
const blockNumber = await ethersProvider.getBlockNumber()
const blockInfo = await ethersProvider.getBlock(blockNumber, false)
t.equal(blockInfo.number, blockNumber, 'Block number should be equal')
} catch (err) {
t.error(err)
}
client.disconnect()
t.end()
}
async function testBlockByHash(t: test.Test, useEthEndpoint: boolean) {
const { client, ethersProvider } = await newContractAndClient(useEthEndpoint)
try {
const blockNumber = await ethersProvider.getBlockNumber()
const blockInfo = await ethersProvider.getBlock(blockNumber, false)
const blockInfoByHash = await ethersProvider.getBlock(blockInfo.hash, false)
t.assert(blockInfoByHash, 'Should return block info by hash')
} catch (error) {
console.error(error)
}
client.disconnect()
t.end()
}
async function testGasPrice(t: test.Test, useEthEndpoint: boolean) {
const { client, ethersProvider } = await newContractAndClient(useEthEndpoint)
try {
const gasPrice = await ethersProvider.getGasPrice()
t.equal(gasPrice, null, "Gas price isn't used on Loomchain")
} catch (err) {
t.error(err)
}
client.disconnect()
t.end()
}
async function testBalance(t: test.Test, useEthEndpoint: boolean) {
const { client, ethersProvider, from } = await newContractAndClient(useEthEndpoint)
try {
const balance = await ethersProvider.getBalance(from)
t.equal(balance.toNumber(), 0, 'Default balance is 0')
} catch (err) {
t.error(err)
}
client.disconnect()
t.end()
}
async function testTransactionReceipt(t: test.Test, useEthEndpoint: boolean) {
t.timeoutAfter(30000)
const { contract, client, from, ethersProvider } = await newContractAndClient(useEthEndpoint)
try {
const newValue = 1
const tx = await contract.set(newValue, { gasLimit: 0 })
const contractReceipt = await tx.wait()
t.ok(contractReceipt.transactionHash, "Contract receipt has transactionHash")
const receipt = await ethersProvider.getTransactionReceipt(contractReceipt.transactionHash!);
// TODO: there is no blockTime property in tx.events.NewValueSet, it's a Loom extension that's
// not implemented on the /eth endpoint yet, re-enable this when we implement it again
// if (!useEthEndpoint) {
// t.assert(receipt.logs[0].blockTime > 0, 'blockTime should be greater than 0')
// }
t.ok(receipt.blockHash, 'blockHash should be greater than 0')
t.equal(receipt.status, 1, 'SimpleStore.set should return correct status')
} catch (err) {
t.error(err, "Unexpected errors")
}
client.disconnect()
t.end()
}
async function testPastEvents(t: test.Test, useEthEndpoint: boolean) {
const { contract, client, ethersProvider } = await newContractAndClient(useEthEndpoint)
t.timeoutAfter(20000)
try {
const newValue = 1
const blockNum = await ethersProvider.getBlockNumber()
const tx = await contract.set(newValue, { gasLimit: 0 })
const receipt = await tx.wait()
t.equal(receipt.status, 1, 'SimpleStore.set should return correct receipt.status')
const events = await ethersProvider.getLogs({
fromBlock: blockNum,
toBlock: "latest",
address: contract.address
})
t.assert(events.length > 0, 'Should have more than 0 events')
} catch (err) {
t.error(err, "Unexpected error")
}
client.disconnect()
t.end()
}
async function testGetStorageAt(t: any, useEthEndpoint: boolean) {
const { client, ethersProvider, contract } = await newContractAndClient(useEthEndpoint)
try {
const storageValue = await ethersProvider.getStorageAt(contract.address, 0x0, 'latest')
t.equal(
storageValue,
'0x000000000000000000000000000000000000000000000000000000000000000a',
'Storage value at 0x0 for contract SimpleStore'
)
} catch (err) {
t.error(err)
}
client.disconnect()
t.end()
}
async function testMismatchedTopic(t: test.Test, useEthEndpoint: boolean) {
const waitMs = 10000
let { contract, client, from, ethersProvider } = await newContractAndClient(useEthEndpoint)
const onTopicValues = [1]
const offTopicValues = [2]
try {
contract = await contract.connect(ethersProvider.getSigner())
var address = '0x1234567890123456789012345678901234567890'
var topicAddress = '0x000000000000000000000000' + address.substring(2);
const topics = [
ethers.utils.id("NewValueSet(uint256)"),
]
const f = {
address: contract.address,
topics
}
// ethersProvider.on(f, console.log)
const SetFilter = contract.filters.NewValueSet
const onTopicPromises = onTopicValues.map(v =>
rejectOnTimeOut(new Promise((resolve) => contract.on(contract.filters.NewValueSet(null), resolve)), waitMs)
)
const offTopicPromises = offTopicValues.map(v =>
rejectOnTimeOut(new Promise((resolve) => contract.on(SetFilter(v), resolve)), waitMs)
)
const shouldTrigger = onTopicPromises.map(
promise => promise
.then(() => true)
.catch(() => false)
.then(called => t.true(called, "On topic listener should be called"))
)
const shouldNotTrigger = offTopicPromises.map(
promise => promise
.then(() => true)
.catch(() => false)
.then(called => t.false(called, "Off topic listener should not be called"))
)
contract.addListener(contract.filters.NewValueSet(1), console.log)
for (const v of onTopicValues) {
await contract.set(v, { gasLimit: 10000 })
}
await Promise.all(shouldTrigger)
await Promise.all(shouldNotTrigger)
console.log("done")
} catch (err) {
console.error(err)
t.fail(err)
}
if (client) {
client.disconnect()
}
t.end()
} | the_stack |
import * as child_process from 'child_process';
import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
import * as events from 'events';
import * as stream from 'stream';
import * as rpc from 'transparent-rpc';
import * as util from 'util';
import * as net from 'net';
import * as jwt from 'jsonwebtoken';
import * as user from '../model/user';
import * as db from '../util/db';
import ThingpediaClient from '../util/thingpedia-client';
import Lock from '../util/lock';
import * as Config from '../config';
import { InternalError } from '../util/errors';
import * as secret from '../util/secret_key';
import type { EngineFactory } from './worker';
import type Engine from './engine';
import * as proto from './protocol';
class ChildProcessSocket extends stream.Duplex {
private _child : child_process.ChildProcess;
constructor(child : child_process.ChildProcess) {
super({ objectMode: true });
this._child = child;
this._child.on('error', (err) => {
console.error(`Failed to send message to child: ${err.message}`);
});
}
_read() {}
_write(data : unknown, encoding : BufferEncoding, callback : (err ?: Error|null) => void) : void {
try {
this._child.send({ type: 'rpc', data: data }, undefined, callback);
} catch(e) {
callback(e);
}
}
}
const ENABLE_SHARED_PROCESS = true;
function safeMkdirSync(dir : string) {
try {
fs.mkdirSync(dir);
} catch(e) {
if (e.code !== 'EEXIST')
throw e;
}
}
function delay(ms : number) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms);
});
}
function getUserDeveloperKey(user : user.RowWithOrg) {
if (user.developer_key)
return user.developer_key;
if (Config.ENABLE_DEVELOPER_PROGRAM || Config.WITH_THINGPEDIA === 'embedded')
return null;
return Config.THINGPEDIA_DEVELOPER_KEY;
}
class EngineProcess extends events.EventEmitter {
private _id : string|number;
useCount : number;
shared : boolean;
private _cwd : string;
private _child : child_process.ChildProcess|null;
private _rpcSocket : rpc.Socket|null;
private _rpcId : string|null;
private _sandboxed : boolean;
private _sandboxedPid : number|null;
private _hadExit : boolean;
private _starting : Promise<void>|null;
private _deadPromise : Promise<number|null>|null;
private _deadCallback : ((code : number|null) => void)|null;
private _dyingTimeout : NodeJS.Timeout|null;
constructor(id : string|number, cloudId : string|null) {
super();
this.setMaxListeners(Infinity);
this._id = id;
this.useCount = 0;
this.shared = cloudId === null;
this._cwd = this.shared ? './' : ('./' + cloudId);
safeMkdirSync(this._cwd);
this._child = null;
this._rpcSocket = null;
this._rpcId = null;
this._sandboxed = !this.shared && process.env.THINGENGINE_DISABLE_SANDBOX !== '1';
this._sandboxedPid = null;
this._hadExit = false;
this._starting = null;
this._deadPromise = null;
this._deadCallback = null;
this._dyingTimeout = null;
}
get id() {
return this._id;
}
async runEngine(user : user.RowWithOrg, thingpediaClient : ThingpediaClient|null) {
this.useCount++;
if (this.shared)
safeMkdirSync(this._cwd + '/' + user.cloud_id);
let dbProxyAccessToken : string|null = null;
if (Config.DATABASE_PROXY_URL) {
dbProxyAccessToken = await util.promisify<object, string, jwt.SignOptions, string>(jwt.sign)({
sub: String(user.id),
aud: 'dbproxy',
}, secret.getJWTSigningKey(), { /* token does not expire */ });
}
const args : rpc.RpcMarshalArgs<Parameters<EngineFactory['runEngine']>> = [thingpediaClient, {
userId: user.id,
cloudId: user.cloud_id,
authToken: user.auth_token,
developerKey: getUserDeveloperKey(user),
locale: user.locale,
timezone: user.timezone,
storageKey: user.storage_key,
modelTag: user.model_tag,
dbProxyUrl: Config.DATABASE_PROXY_URL,
dbProxyAccessToken: dbProxyAccessToken,
humanName: user.human_name,
phone: user.phone,
email: user.email,
emailVerified: !!user.email_verified,
}];
return this._rpcSocket!.call(this._rpcId!, 'runEngine', args);
}
killEngine(userId : number) {
if (!this.shared)
return this.kill();
this.useCount--;
return this._rpcSocket!.call(this._rpcId!, 'killEngine', [userId]).then(() => {
this.emit('engine-removed', userId);
}).catch((e) => {
// assume if the call fails that the engine actually died
this.emit('engine-removed', userId);
});
}
kill() {
if (this._child === null)
return;
this._deadPromise = new Promise((resolve, reject) => {
this._deadCallback = resolve;
this._dyingTimeout = setTimeout(() => {
if (this._sandboxedPid !== null) {
process.kill(this._sandboxedPid, 'SIGKILL');
this._sandboxedPid = null;
} else if (this._child !== null) {
this._child.kill('SIGKILL');
}
reject(new InternalError('ETIMEDOUT', `Timeout waiting for child ${this._id} to die`));
}, 30000);
});
console.log('Killing process with ID ' + this._id);
// in the sandbox, we cannot kill the process directly, due to signal
// restrictions in PID namespaces (the sandbox process is treated like PID 1
// and unkillable other than with SIGKILL)
// to try and terminate the process gracefully, send a message using the channel
//
// NOTE: if the child is not connected and we are sandboxed, we will send it
// SIGTERM, which does nothing
// later, we'll timeout and send it SIGKILL instead
// (same thing if sending fails)
if (this._sandboxed && this._child.connected)
this._child.send({ type: 'exit' });
else
this._child.kill();
// emit exit immediately so we close the channel
// otherwise we could race and try to talk to the dying process
this._hadExit = true;
// mark that this was a manual kill (hence we don't want to
// autorestart any user until the admin does so manually)
this.emit('exit', true);
}
restart(ms : number) {
this._child = null;
this._rpcSocket = null;
this._rpcId = null;
return this._starting = delay(ms).then(() => this.start());
}
waitReady() {
return Promise.resolve(this._starting).then(() => this);
}
waitDead() {
return Promise.resolve(this._deadPromise);
}
send(msg : proto.MasterToWorker, socket ?: net.Socket) {
this._child!.send(msg, socket);
}
private _handleInfoFD(pipe : stream.Readable) {
let buf = '';
pipe.setEncoding('utf8');
pipe.on('data', (data) => {
buf += data;
});
pipe.on('end', () => {
const parsed = JSON.parse(buf);
this._sandboxedPid = parsed['child-pid'];
});
pipe.on('error', (err) => {
console.error(`Failed to read from info-fd in process ${this._id}: ${err}`);
});
}
private _addConfigArgs(args : string[]) {
args.push(
'--thingpedia-url', Config.THINGPEDIA_URL,
'--nl-server-url', Config.NL_SERVER_URL,
'--oauth-redirect-origin', Config.OAUTH_REDIRECT_ORIGIN,
'--faq-models', JSON.stringify(Config.FAQ_MODELS),
'--notification-config', JSON.stringify(Config.NOTIFICATION_CONFIG),
);
for (const lang of Config.SUPPORTED_LANGUAGES)
args.push('--locale', lang);
}
start() {
const ALLOWED_ENVS = ['LANG', 'LOGNAME', 'USER', 'PATH',
'HOME', 'SHELL', 'THINGENGINE_PROXY',
'CI', 'THINGENGINE_DISABLE_SYSTEMD'];
function envIsAllowed(name : string) {
if (name.startsWith('LC_'))
return true;
if (ALLOWED_ENVS.indexOf(name) >= 0)
return true;
return false;
}
const env : Record<string, string> = {};
for (const name in process.env) {
if (envIsAllowed(name))
env[name] = process.env[name]!;
}
for (const key in Config.EXTRA_ENVIRONMENT)
env[key] = Config.EXTRA_ENVIRONMENT[key];
env.THINGENGINE_USER_ID = String(this._id);
const managerPath = path.dirname(module.filename);
const enginePath = path.resolve(managerPath, './worker');
let child : child_process.ChildProcess;
console.log('Spawning process with ID ' + this._id);
let processPath, args, stdio;
if (this.shared) {
args = process.execArgv.slice();
args.push(enginePath);
args.push('--shared');
this._addConfigArgs(args);
child = child_process.spawn(process.execPath, args,
{ stdio: ['ignore', 'ignore', 2, 'ignore', 'ipc'],
detached: true, // ignore ^C
cwd: this._cwd, env: env });
} else {
if (process.env.THINGENGINE_DISABLE_SANDBOX === '1') {
processPath = process.execPath;
args = process.execArgv.slice();
args.push(enginePath);
this._addConfigArgs(args);
stdio = ['ignore', 1, 2, 'ignore', 'ipc'] as Array<'ignore'|'ipc'|number>;
} else {
processPath = path.resolve(managerPath, '../../sandbox/sandbox');
args = [process.execPath].concat(process.execArgv);
args.push(enginePath);
this._addConfigArgs(args);
stdio = ['ignore', 1, 2, 'pipe', 'ipc'] as Array<'ignore'|'ipc'|number>;
const jsPrefix = path.resolve(path.dirname(managerPath), '..');
const nodepath = path.resolve(process.execPath);
if (!nodepath.startsWith('/usr/'))
env.THINGENGINE_PREFIX = jsPrefix + ':' + nodepath;
else
env.THINGENGINE_PREFIX = jsPrefix;
}
child = child_process.spawn(processPath, args,
{ stdio: stdio,
detached: true,
cwd: this._cwd, env: env });
}
if (this._sandboxed)
this._handleInfoFD(child.stdio[3] as stream.Readable);
// wrap child into something that looks like a Stream
// (readable + writable)
const socket = new ChildProcessSocket(child);
this._rpcSocket = new rpc.Socket(socket);
return this._starting = new Promise((resolve, reject) => {
child.on('error', (error) => {
console.error('Child with ID ' + this._id + ' reported an error: ' + error);
reject(new InternalError('E_WORKER_ERROR', 'Reported error ' + error));
});
child.on('disconnect', () => {
if (!this._hadExit) {
this._hadExit = true;
this.emit('exit');
}
});
child.on('exit', (code, signal) => {
this._sandboxedPid = null;
this._child = null;
if (this._dyingTimeout !== null) {
clearTimeout(this._dyingTimeout);
this._dyingTimeout = null;
}
if (this.shared || code !== 0)
console.error('Child with ID ' + this._id + ' exited with code ' + code);
reject(new InternalError('E_WORKER_ERROR', 'Exited with code ' + code));
if (this._deadCallback)
this._deadCallback(code);
if (!this._hadExit) {
this._hadExit = true;
this.emit('exit');
}
});
socket.on('error', (error) => {
console.error('Failed to communicate with ID ' + this._id + ': ' + error);
});
this._child = child;
child.on('message', (msg : proto.WorkerToMaster) => {
switch (msg.type) {
case 'ready':
this._rpcId = msg.id;
this._starting = null;
resolve();
break;
case 'rpc':
socket.push(msg.data);
break;
}
});
});
}
}
interface EngineProxy {
cloudId : string;
process : EngineProcess|null;
engine : rpc.Proxy<Engine>|null;
thingpediaClient : ThingpediaClient|null;
}
export default class EngineManager extends events.EventEmitter implements rpc.Stubbable {
$rpcMethods = ['isRunning', 'getProcessId', 'startUser', 'killUser', 'killAllUsers', 'restartUser', 'deleteUser', 'clearCache', 'restartUserWithoutCache'] as const;
$free ?: () => void;
private _shardId : number;
private _processes : Record<string, EngineProcess>;
private _rrproc : EngineProcess[];
private _nextProcess : number;
private _engines : Record<number, EngineProxy>;
private _locks : Record<number, Lock>;
private _stopped : boolean;
constructor(shardId : number) {
super();
this._shardId = shardId;
this._processes = {};
this._rrproc = [];
this._nextProcess = 0;
this._engines = {};
this._locks = {};
this._stopped = false;
}
private _findProcessForUser(user : user.RowWithOrg) {
if (ENABLE_SHARED_PROCESS && user.developer_key === null && !user.force_separate_process) {
const child = this._rrproc[this._nextProcess];
this._nextProcess++;
this._nextProcess = this._nextProcess % this._rrproc.length;
return child.waitReady();
} else {
const child = new EngineProcess(user.id, user.cloud_id);
this._processes[user.id] = child;
child.on('exit', () => {
if (this._processes[user.id] === child)
delete this._processes[user.id];
});
return child.start().then(() => child);
}
}
private async _lockUser(userId : number) {
if (!this._locks[userId])
this._locks[userId] = new Lock();
return this._locks[userId].acquire();
}
private async _runUser(user : user.RowWithOrg) {
const engines = this._engines;
const obj : EngineProxy = {
cloudId: user.cloud_id,
process: null,
engine: null,
thingpediaClient : null
};
engines[user.id] = obj;
const die = (manual : boolean) => {
obj.process!.removeListener('exit', die);
obj.process!.removeListener('engine-removed', onRemoved);
if (obj.thingpediaClient)
(obj.thingpediaClient as any /* FIXME */).$free();
if (engines[user.id] !== obj)
return;
delete engines[user.id];
// if the EngineManager is being stopped, the user will die
// the "hard" way (by killing the worker process)
// we don't want to restart it either way
if (this._stopped)
manual = true;
if (!manual && obj.process!.shared) {
// if the process died, some user might have been killed as a side effect
// set timeout to restart the user 10 s in the future
setTimeout(() => {
this.restartUser(user.id);
}, 10000);
}
};
const onRemoved = (deadUserId : number) => {
if (user.id !== deadUserId)
return;
die(true);
};
const child = await this._findProcessForUser(user);
console.log('Running engine for user ' + user.id + ' in shard ' + this._shardId);
obj.process = child;
child.on('engine-removed', onRemoved);
child.on('exit', die);
if (Config.WITH_THINGPEDIA === 'embedded')
obj.thingpediaClient = new ThingpediaClient(user.developer_key, user.locale);
else
obj.thingpediaClient = null;
return child.runEngine(user, obj.thingpediaClient);
}
isRunning(userId : number) {
return (this._engines[userId] !== undefined && this._engines[userId].process !== null);
}
getProcessId(userId : number) {
return (this._engines[userId] !== undefined && this._engines[userId].process !== null) ? this._engines[userId].process!.id : -1;
}
async sendSocket(userId : number, replyId : string, socket : net.Socket) {
if (this._engines[userId] === undefined)
throw new InternalError('E_INVALID_USER', 'Invalid user ID');
if (this._engines[userId].process === null)
throw new InternalError('E_ENGINE_DEAD', 'Engine dead');
const releaseLock = await this._lockUser(userId);
try {
this._engines[userId].process!.send({ type: 'direct', target: userId, replyId: replyId }, socket);
} finally {
releaseLock();
}
}
private _startSharedProcesses(nprocesses : number) {
const promises = new Array(nprocesses);
this._rrproc = new Array(nprocesses);
this._nextProcess = 0;
for (let i = 0; i < nprocesses; i++) {
const procId = `${this._shardId}/S${i}`;
const proc = new EngineProcess(procId, null);
proc.on('exit', () => {
if (this._stopped)
return;
proc.restart(5000);
});
this._rrproc[i] = proc;
promises[i] = proc.start();
this._processes[procId] = proc;
}
return Promise.all(promises);
}
private _getNProcesses() {
let nprocesses;
if (ENABLE_SHARED_PROCESS) {
const ncpus = os.cpus().length;
nprocesses = 2 * ncpus;
} else {
nprocesses = 0;
}
return nprocesses;
}
async start() {
await this._startSharedProcesses(this._getNProcesses());
await db.withClient(async (client) => {
const rows = await user.getAllForShardId(client, this._shardId);
return Promise.all(rows.map((r) => {
return this._runUser(r).catch((e) => {
console.error('User ' + r.id + ' failed to start: ' + e.message);
});
}));
});
}
async startUser(userId : number) {
console.log('Requested start of user ' + userId);
const releaseLock = await this._lockUser(userId);
try {
await this._startUserLocked(userId);
} finally {
releaseLock();
}
}
private async _startUserLocked(userId : number) {
return db.withClient((dbClient) => {
return user.get(dbClient, userId);
}).then((user) => {
return this._runUser(user);
});
}
async stop() {
this._stopped = true;
await this.killAllUsers();
console.log(`EngineManager stopped`);
}
killAllUsers() {
const promises = [];
for (const userId in this._processes) {
const proc = this._processes[userId];
proc.kill();
promises.push(proc.waitDead());
}
return Promise.all(promises).then(() => true);
}
private async _killUserLocked(userId : number) {
const obj = this._engines[userId];
if (!obj || obj.process === null)
return;
await obj.process.killEngine(userId);
}
async killUser(userId : number) {
console.log('Requested killing user ' + userId);
const releaseLock = await this._lockUser(userId);
try {
await this._killUserLocked(userId);
} finally {
releaseLock();
}
}
private _getUserCloudIdForPath(userId : number) {
const obj = this._engines[userId];
if (obj) {
if (obj.process !== null)
obj.process.killEngine(userId);
return Promise.resolve(obj.cloudId);
} else {
return db.withClient((dbClient) => {
return user.get(dbClient, userId);
}).then((user) => {
return user.cloud_id;
});
}
}
async restartUser(userId : number) {
console.log('Requested restart of user ' + userId);
const releaseLock = await this._lockUser(userId);
try {
await this._killUserLocked(userId);
await this._startUserLocked(userId);
} finally {
releaseLock();
}
}
async deleteUser(userId : number) {
console.log(`Deleting all data for ${userId}`);
const releaseLock = await this._lockUser(userId);
try {
await this._killUserLocked(userId);
const dir = path.resolve('.', await this._getUserCloudIdForPath(userId));
await util.promisify(child_process.execFile)('/bin/rm', ['-rf', dir]); //'
} finally {
releaseLock();
delete this._locks[userId];
}
}
private async _clearCacheLocked(userId : number) {
const dir = path.resolve('.', await this._getUserCloudIdForPath(userId), 'cache');
await util.promisify(child_process.execFile)('/bin/rm',
['-rf', dir]);
}
async clearCache(userId : number) {
console.log(`Clearing cache for ${userId}`);
const releaseLock = await this._lockUser(userId);
try {
await this._clearCacheLocked(userId);
} finally {
releaseLock();
}
}
// restart a user with a clean cache folder
// this is useful if the user just lost their developer key,
// as after restart they will be placed in a shared process,
// and we don't want them having access to unapproved (and dangerous)
// devices through the cache
async restartUserWithoutCache(userId : number) {
console.log(`Requested cache clear & restart of user ${userId}`);
const releaseLock = await this._lockUser(userId);
try {
await this._killUserLocked(userId);
await this._clearCacheLocked(userId);
await this._startUserLocked(userId);
} finally {
releaseLock();
}
}
} | the_stack |
import { NO_BREAK_SPACE, TAB_CHARACTER, ATOM_CLASS_NAME } from '../renderers/editor-dom'
import { MARKUP_SECTION_TYPE, LIST_SECTION_TYPE, LIST_ITEM_TYPE } from '../models/types'
import { isTextNode, isElementNode, getAttributes, normalizeTagName } from '../utils/dom-utils'
import { any, detect, forEach, Indexable, ForEachable } from '../utils/array-utils'
import { TAB } from '../utils/characters'
import { ZWNJ } from '../renderers/editor-dom'
import SectionParser from '../parsers/section'
import Markup from '../models/markup'
import Markerable, { isMarkerable } from '../models/_markerable'
import PostNodeBuilder from '../models/post-node-builder'
import { Dict } from '../utils/types'
import Section from '../models/_section'
import Post from '../models/post'
import { Cloneable } from '../models/_cloneable'
import MarkupSection, { hasInferredTagName } from '../models/markup-section'
import RenderTree from '../models/render-tree'
import { isMarker } from '../models/marker'
import { isAtom } from '../models/atom'
import RenderNode from '../models/render-node'
import Markuperable from '../utils/markuperable'
import ListItem from '../models/list-item'
import ListSection from '../models/list-section'
const GOOGLE_DOCS_CONTAINER_ID_REGEX = /^docs-internal-guid/
const NO_BREAK_SPACE_REGEX = new RegExp(NO_BREAK_SPACE, 'g')
const TAB_CHARACTER_REGEX = new RegExp(TAB_CHARACTER, 'g')
export function transformHTMLText(textContent: string) {
let text = textContent
text = text.replace(NO_BREAK_SPACE_REGEX, ' ')
text = text.replace(TAB_CHARACTER_REGEX, TAB)
return text
}
export function trimSectionText(section: Section) {
if (isMarkerable(section) && section.markers.length) {
let { head, tail } = section.markers
head!.value = head!.value.replace(/^\s+/, '')
tail!.value = tail!.value.replace(/\s+$/, '')
}
}
function isGoogleDocsContainer(element: Node) {
return (
isElementNode(element) &&
normalizeTagName(element.tagName) === normalizeTagName('b') &&
GOOGLE_DOCS_CONTAINER_ID_REGEX.test(element.id)
)
}
function detectRootElement(element: HTMLElement) {
let childNodes: Indexable<Node> = element.childNodes || []
let googleDocsContainer = detect(childNodes, isGoogleDocsContainer)
if (googleDocsContainer) {
return googleDocsContainer
} else {
return element
}
}
const TAG_REMAPPING: Dict<string> = {
b: 'strong',
i: 'em',
}
function remapTagName(tagName: string) {
let normalized = normalizeTagName(tagName)
let remapped = TAG_REMAPPING[normalized]
return remapped || normalized
}
function trim(str: string) {
return str.replace(/^\s+/, '').replace(/\s+$/, '')
}
function walkMarkerableNodes(parent: Node, callback: (node: Node) => void) {
let currentNode: Node | null = parent
if (isTextNode(currentNode) || (isElementNode(currentNode) && currentNode.classList.contains(ATOM_CLASS_NAME))) {
callback(currentNode)
} else {
currentNode = currentNode.firstChild
while (currentNode) {
walkMarkerableNodes(currentNode, callback)
currentNode = currentNode.nextSibling
}
}
}
/**
* Parses DOM element -> Post
* @private
*/
export default class DOMParser {
builder: PostNodeBuilder
sectionParser: SectionParser
constructor(builder: PostNodeBuilder, options = {}) {
this.builder = builder
this.sectionParser = new SectionParser(this.builder, options)
}
parse(element: HTMLElement) {
const post = this.builder.createPost()
let rootElement = detectRootElement(element)
this._eachChildNode(rootElement, child => {
let sections = this.parseSections(child as HTMLElement)
this.appendSections(post, sections)
})
// trim leading/trailing whitespace of markerable sections to avoid
// unnessary whitespace from indented HTML input
forEach(post.sections, section => trimSectionText(section))
return post
}
appendSections(post: Post, sections: ForEachable<Cloneable<Section>>) {
forEach(sections, section => this.appendSection(post, section))
}
appendSection(post: Post, section: Cloneable<Section>) {
if (
section.isBlank ||
(isMarkerable(section) && trim(section.text) === '' && !any(section.markers, marker => marker.isAtom))
) {
return
}
let lastSection = post.sections.tail
if (
lastSection &&
hasInferredTagName(lastSection) &&
hasInferredTagName(section) &&
lastSection.tagName === section.tagName
) {
lastSection.join(section)
} else {
post.sections.append(section)
}
}
_eachChildNode(element: Node, callback: (element: Node) => void) {
let nodes = isTextNode(element) ? [element] : element.childNodes
forEach(nodes, node => callback(node))
}
parseSections(element: HTMLElement) {
return this.sectionParser.parse(element)
}
// walk up from the textNode until the rootNode, converting each
// parentNode into a markup
collectMarkups(textNode: Text, rootNode: Node) {
let markups: Markup[] = []
let currentNode = textNode.parentNode
while (currentNode && currentNode !== rootNode) {
let markup = this.markupFromNode(currentNode)
if (markup) {
markups.push(markup)
}
currentNode = currentNode.parentNode
}
return markups
}
// Turn an element node into a markup
markupFromNode(node: Node) {
if (isElementNode(node) && Markup.isValidElement(node)) {
let tagName = remapTagName(node.tagName)
let attributes = getAttributes(node)
return this.builder.createMarkup(tagName, attributes)
}
}
// FIXME should move to the section parser?
// FIXME the `collectMarkups` logic could simplify the section parser?
reparseSection(section: Section, renderTree: RenderTree) {
switch (section.type) {
case LIST_SECTION_TYPE:
return this.reparseListSection(section as ListSection, renderTree)
case LIST_ITEM_TYPE:
return this.reparseListItem(section as ListItem, renderTree)
case MARKUP_SECTION_TYPE:
return this.reparseMarkupSection(section as MarkupSection, renderTree)
default:
return // can only parse the above types
}
}
reparseMarkupSection(section: MarkupSection, renderTree: RenderTree) {
return this._reparseSectionContainingMarkers(section, renderTree)
}
reparseListItem(listItem: ListItem, renderTree: RenderTree) {
return this._reparseSectionContainingMarkers(listItem, renderTree)
}
reparseListSection(listSection: ListSection, renderTree: RenderTree) {
listSection.items.forEach(li => this.reparseListItem(li, renderTree))
}
_reparseSectionContainingMarkers(section: Markerable, renderTree: RenderTree) {
let element = section.renderNode.element!
let seenRenderNodes: RenderNode[] = []
let previousMarker: Markuperable
walkMarkerableNodes(element, node => {
let marker!: Markuperable
let renderNode = renderTree.getElementRenderNode(node)
if (renderNode) {
if (isMarker(renderNode.postNode!)) {
let text = transformHTMLText(node.textContent || '')
let markups = this.collectMarkups(node as Text, element)
if (text.length) {
marker = renderNode.postNode!
marker.value = text
marker.markups = markups
} else {
renderNode.scheduleForRemoval()
}
} else if (isAtom(renderNode.postNode!)) {
let { headTextNode, tailTextNode } = renderNode
if (headTextNode!.textContent !== ZWNJ) {
let value = headTextNode!.textContent!.replace(new RegExp(ZWNJ, 'g'), '')
headTextNode!.textContent = ZWNJ
if (previousMarker && previousMarker.isMarker) {
previousMarker.value += value
if (previousMarker.renderNode) {
previousMarker.renderNode.markDirty()
}
} else {
let postNode = renderNode.postNode
let newMarkups = postNode.markups.slice()
let newPreviousMarker = this.builder.createMarker(value, newMarkups)
section.markers.insertBefore(newPreviousMarker, postNode)
let newPreviousRenderNode = renderTree.buildRenderNode(newPreviousMarker)
newPreviousRenderNode.markDirty()
section.renderNode.markDirty()
seenRenderNodes.push(newPreviousRenderNode)
section.renderNode.childNodes.insertBefore(newPreviousRenderNode, renderNode)
}
}
if (tailTextNode!.textContent !== ZWNJ) {
let value = tailTextNode!.textContent!.replace(new RegExp(ZWNJ, 'g'), '')
tailTextNode!.textContent = ZWNJ
if (renderNode.postNode.next && renderNode.postNode.next.isMarker) {
let nextMarker = renderNode.postNode.next
if (nextMarker.renderNode) {
let nextValue = nextMarker.renderNode.element!.textContent
nextMarker.renderNode.element!.textContent = value + nextValue
} else {
let nextValue = value + nextMarker.value
nextMarker.value = nextValue
}
} else {
let postNode = renderNode.postNode
let newMarkups = postNode.markups.slice()
let newMarker = this.builder.createMarker(value, newMarkups)
section.markers.insertAfter(newMarker, postNode)
let newRenderNode = renderTree.buildRenderNode(newMarker)
seenRenderNodes.push(newRenderNode)
newRenderNode.markDirty()
section.renderNode.markDirty()
section.renderNode.childNodes.insertAfter(newRenderNode, renderNode)
}
}
if (renderNode) {
marker = renderNode.postNode
}
}
} else if (isTextNode(node)) {
let text = transformHTMLText(node.textContent!)
let markups = this.collectMarkups(node, element)
marker = this.builder.createMarker(text, markups)
renderNode = renderTree.buildRenderNode(marker)
renderNode.element = node
renderNode.markClean()
section.renderNode.markDirty()
let previousRenderNode = previousMarker && previousMarker.renderNode
section.markers.insertAfter(marker, previousMarker)
section.renderNode.childNodes.insertAfter(renderNode, previousRenderNode!)
}
if (renderNode) {
seenRenderNodes.push(renderNode)
}
previousMarker = marker
})
let renderNode = section.renderNode.childNodes.head
while (renderNode) {
if (seenRenderNodes.indexOf(renderNode) === -1) {
renderNode.scheduleForRemoval()
}
renderNode = renderNode.next
}
}
} | the_stack |
import ts from '../internal/typescript.js';
import {ImportMapResolver} from './import-map-resolver.js';
import {Deferred} from '../shared/deferred.js';
import {
parseNpmStyleSpecifier,
changeFileExtension,
classifySpecifier,
resolveUrlPath,
trimTrailingSlash,
trimLeadingSlash,
} from './util.js';
import type {Result} from '../shared/util.js';
import type {CachingCdn} from './caching-cdn.js';
import type {PackageJson, NpmFileLocation} from './util.js';
import {
PackageDependencies,
DependencyGraph,
NodeModulesDirectory,
NodeModulesLayoutMaker,
} from './node-modules-layout-maker.js';
type PackageName = string;
type PackageVersion = string;
type FilePath = string;
type FileContent = string;
/**
* The top-level project. Used as a referrer.
*/
const root = Symbol();
/**
* Fetches typings for TypeScript imports and their transitive dependencies, and
* for standard libraries.
*/
export class TypesFetcher {
private readonly _cdn: CachingCdn;
private readonly _importMapResolver: ImportMapResolver;
private readonly _rootPackageJson: PackageJson | undefined;
private readonly _rootDependencies: PackageDependencies = {};
private readonly _dependencyGraph: DependencyGraph = {};
private readonly _filesByPackageVersion = new Map<
PackageName,
Map<PackageVersion, Map<FilePath, Promise<Result<FileContent, number>>>>
>();
/**
* Fetch all ".d.ts" typing files for the full transitive dependency tree of
* the given project source files and standard libs.
*
* @param cdn Interface to unpkg.com or similar CDN service for fetching
* assets.
* @param importMapResolver Resolves bare modules to custom URLs, for
* optionally overriding the CDN.
* @param rootPackageJson The parsed package.json file for the root project,
* or undefined if there isn't one.
* @param sources Project TypeScript source file contents. All bare module
* imports in these sources will be followed.
* @param tsLibs Case-insensitive TypeScript standard libraries to fetch, e.g.
* "es2020", "DOM".
*/
static async fetchTypes(
cdn: CachingCdn,
importMapResolver: ImportMapResolver,
rootPackageJson: PackageJson | undefined,
sources: string[],
tsLibs: string[]
): Promise<{
files: Map<FilePath, FileContent>;
layout: NodeModulesDirectory;
dependencyGraph: {
root: PackageDependencies;
deps: DependencyGraph;
};
}> {
const fetcher = new TypesFetcher(cdn, importMapResolver, rootPackageJson);
// Note we use Promise.allSettled instead of Promise.all because we really
// do want to ignore exceptions due to 404s etc., and don't want one error
// to fail the entire tree. If the .d.ts files for an import fail to load
// for any reason, then they won't exist in the virtual filesystem passed to
// TypeScript, and the user will therefore see a "missing types" error. An
// improvement would be to surface some more detail to the user, though,
// especially for non-404 errors.
await Promise.allSettled([
...sources.map((source) =>
fetcher._handleBareAndRelativeSpecifiers(source, root)
),
...tsLibs.map((lib) => fetcher._addTypeScriptStandardLib(lib)),
]);
const layout = new NodeModulesLayoutMaker().layout(
fetcher._rootDependencies,
fetcher._dependencyGraph
);
const files = new Map();
await fetcher._materializeNodeModulesTree(layout, files, '');
// Note in practice we only really need "files", but it's useful to also
// return the dependency graph and layout for testing.
return {
files,
layout,
dependencyGraph: {
root: fetcher._rootDependencies,
deps: fetcher._dependencyGraph,
},
};
}
private constructor(
cdn: CachingCdn,
importMapResolver: ImportMapResolver,
rootPackageJson: PackageJson | undefined
) {
this._cdn = cdn;
this._importMapResolver = importMapResolver;
this._rootPackageJson = rootPackageJson;
}
private async _addTypeScriptStandardLib(lib: string): Promise<void> {
return this._handleBareSpecifier(
`typescript/lib/lib.${lib.toLowerCase()}.js`,
root
);
}
private async _handleBareAndRelativeSpecifiers(
sourceText: string,
referrer: NpmFileLocation | typeof root
): Promise<void> {
const fileInfo = ts.preProcessFile(sourceText, undefined, true);
const promises = [];
for (const {fileName: specifier} of fileInfo.importedFiles) {
const kind = classifySpecifier(specifier);
if (kind === 'bare') {
promises.push(this._handleBareSpecifier(specifier, referrer));
} else if (kind === 'relative' && referrer !== root) {
// Note we never need to follow relative imports from project root files
// because those can only be other project files, which are already
// being processed, since we pass all project files to this class.
promises.push(this._handleRelativeSpecifier(specifier, referrer));
}
}
for (const {fileName: lib} of fileInfo.libReferenceDirectives) {
promises.push(this._addTypeScriptStandardLib(lib));
}
await Promise.allSettled(promises);
}
private async _handleBareSpecifier(
bare: string,
referrer: NpmFileLocation | typeof root
): Promise<void> {
let location = parseNpmStyleSpecifier(bare);
if (location === undefined) {
return;
}
// Versions don't make much sense with an import map, since you just have
// bare specifier -> URL. We can leave whatever version we already have; it
// will always be ignored.
const handledByImportMap = this._importMapResolver.resolve(bare) !== null;
// Get the version range based on the referrer's package.json.
if (!handledByImportMap) {
location.version = await this._getDependencyVersion(
referrer,
location.pkg
);
}
// Get the ".d.ts" path by changing extension, or looking up the "typings"
// field, etc.
location.path = await this._getDtsPath(location);
// Resolve the concrete version.
if (!handledByImportMap) {
location = await this._cdn.canonicalize(location);
}
if (referrer === root || location.pkg !== referrer.pkg) {
// Note the two package names can be the same in the case that a typings
// file imports another module from the same package using its own bare
// module name, instead of a relative path. TypeScript does support this
// case, and it does happen (e.g. @material/base does this). We don't need
// a self-edge in the dependency graph, though.
this._addEdgeToDependencyGraph(referrer, location);
}
// Stop early if we've already handled this specifier.
if (
this._filesByPackageVersion
.get(location.pkg)
?.get(location.version)
?.get(location.path) !== undefined
) {
return;
}
// Ready to fetch and recurse.
const dtsResult = await this._fetchAndAddToOutputFiles(location);
if (dtsResult.error !== undefined) {
return;
}
await this._handleBareAndRelativeSpecifiers(dtsResult.result, location);
}
private async _handleRelativeSpecifier(
relative: string,
referrer: NpmFileLocation
): Promise<void> {
const location = {
// We know package and version must be the same as the referrer, since
// this is a relative path, and we are therefore still in the same
// package.
pkg: referrer.pkg,
version: referrer.version,
// Make the path package-root relative, instead of referrer-path relative.
path: trimLeadingSlash(resolveUrlPath(referrer.path, relative).slice(1)),
};
location.path = changeFileExtension(location.path, 'd.ts');
// Stop early if we've already handled this specifier.
if (
this._filesByPackageVersion
.get(location.pkg)
?.get(location.version)
?.get(location.path) !== undefined
) {
return;
}
const dtsResult = await this._fetchAndAddToOutputFiles(location);
if (dtsResult.error !== undefined) {
return;
}
await this._handleBareAndRelativeSpecifiers(dtsResult.result, location);
}
private async _getDependencyVersion(
from: NpmFileLocation | typeof root,
to: string
): Promise<string> {
const packageJson =
from === root
? this._rootPackageJson
: await this._fetchPackageJsonAndAddToOutputFiles(from);
return packageJson?.dependencies?.[to] ?? 'latest';
}
private async _getDtsPath(location: NpmFileLocation): Promise<string> {
if (location.path !== '') {
return changeFileExtension(location.path, 'd.ts');
}
const packageJson = await this._fetchPackageJsonAndAddToOutputFiles(
location
);
return (
packageJson?.typings ??
packageJson?.types ??
(packageJson?.main !== undefined
? changeFileExtension(packageJson.main, 'd.ts')
: undefined) ??
'index.d.ts'
);
}
private async _fetchPackageJsonAndAddToOutputFiles(location: {
pkg: string;
version: string;
}): Promise<PackageJson> {
const result = await this._fetchAndAddToOutputFiles({
...location,
path: 'package.json',
});
if (result.error !== undefined) {
throw new Error(
`Could not fetch package.json for ` +
`${location.pkg}@${location.version}: ${result.error}`
);
}
return JSON.parse(result.result) as PackageJson;
}
private async _fetchAndAddToOutputFiles(
location: NpmFileLocation
): Promise<Result<string, number>> {
const importMapUrl = this._importMapResolver.resolve(
trimTrailingSlash(`${location.pkg}/${location.path}`)
);
if (importMapUrl === null) {
location = await this._cdn.canonicalize(location);
}
let versions = this._filesByPackageVersion.get(location.pkg);
if (versions === undefined) {
versions = new Map();
this._filesByPackageVersion.set(location.pkg, versions);
}
let files = versions.get(location.version);
if (files === undefined) {
files = new Map();
versions.set(location.version, files);
}
let promise = files.get(location.path);
if (promise !== undefined) {
return promise;
}
const deferred = new Deferred<Result<string, number>>();
promise = deferred.promise;
files.set(location.path, promise);
let content;
if (importMapUrl !== null) {
const r = await fetch(importMapUrl);
if (r.status !== 200) {
const err = {error: r.status};
deferred.resolve(err);
return err;
}
content = await r.text();
} else {
try {
const r = await this._cdn.fetch(location);
content = r.content;
} catch {
const err = {error: 404};
deferred.resolve(err);
return err;
}
}
const result = {result: content};
deferred.resolve(result);
return result;
}
/**
* Record in our dependency graph that some package depends on another.
*/
private _addEdgeToDependencyGraph(
from: {pkg: string; version: string} | typeof root,
to: {pkg: string; version: string}
) {
if (from === root) {
this._rootDependencies[to.pkg] = to.version;
} else {
let fromVersions = this._dependencyGraph[from.pkg];
if (fromVersions === undefined) {
fromVersions = {};
this._dependencyGraph[from.pkg] = fromVersions;
}
let deps = fromVersions[from.version];
if (deps === undefined) {
deps = {};
fromVersions[from.version] = deps;
}
deps[to.pkg] = to.version;
}
}
/**
* Materialize a node_modules/ file tree for the given layout into the given
* file map, using the files we've fetched.
*
* For example, given the layout ...
*
* ROOT
* ├── A1
* ├── B1
* │ └── A2
* └── C1
* └── A2
*
* ... and where each package just contains one "index.d.ts" file, then
* populates the file map with keys:
*
* a/index.d.ts
* b/index.d.ts
* b/node_modules/a/index.d.ts
* c/index.d.ts
* c/node_modules/a/index.d.ts
*/
private async _materializeNodeModulesTree(
layout: NodeModulesDirectory,
fileMap: Map<FilePath, FileContent>,
prefix: FilePath
): Promise<void> {
for (const [pkg, entry] of Object.entries(layout)) {
const files = this._filesByPackageVersion.get(pkg)?.get(entry.version);
if (files === undefined) {
continue;
}
for (const [pkgRelativePath, promise] of files) {
const result = await promise;
if (result.error === undefined) {
const fullyQualifiedPath = `${prefix}${pkg}/${pkgRelativePath}`;
fileMap.set(fullyQualifiedPath, result.result);
}
}
await this._materializeNodeModulesTree(
entry.nodeModules,
fileMap,
`${prefix}${pkg}/node_modules/`
);
}
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs, enums } from "../types";
import * as utilities from "../utilities";
/**
* Associates an SSM Document to an instance or EC2 tag.
*
* ## Example Usage
* ### Create an association for a specific instance
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const example = new aws.ssm.Association("example", {targets: [{
* key: "InstanceIds",
* values: [aws_instance.example.id],
* }]});
* ```
* ### Create an association for all managed instances in an AWS account
*
* To target all managed instances in an AWS account, set the `key` as `"InstanceIds"` with `values` set as `["*"]`. This example also illustrates how to use an Amazon owned SSM document named `AmazonCloudWatch-ManageAgent`.
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const example = new aws.ssm.Association("example", {
* targets: [{
* key: "InstanceIds",
* values: ["*"],
* }],
* });
* ```
* ### Create an association for a specific tag
*
* This example shows how to target all managed instances that are assigned a tag key of `Environment` and value of `Development`.
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const example = new aws.ssm.Association("example", {
* targets: [{
* key: "tag:Environment",
* values: ["Development"],
* }],
* });
* ```
*
* ## Import
*
* SSM associations can be imported using the `association_id`, e.g.
*
* ```sh
* $ pulumi import aws:ssm/association:Association test-association 10abcdef-0abc-1234-5678-90abcdef123456
* ```
*/
export class Association extends pulumi.CustomResource {
/**
* Get an existing Association resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: AssociationState, opts?: pulumi.CustomResourceOptions): Association {
return new Association(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'aws:ssm/association:Association';
/**
* Returns true if the given object is an instance of Association. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is Association {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Association.__pulumiType;
}
/**
* By default, when you create a new or update associations, the system runs it immediately and then according to the schedule you specified. Enable this option if you do not want an association to run immediately after you create or update it. This parameter is not supported for rate expressions. Default: `false`.
*/
public readonly applyOnlyAtCronInterval!: pulumi.Output<boolean | undefined>;
/**
* The ID of the SSM association.
*/
public /*out*/ readonly associationId!: pulumi.Output<string>;
/**
* The descriptive name for the association.
*/
public readonly associationName!: pulumi.Output<string | undefined>;
/**
* Specify the target for the association. This target is required for associations that use an `Automation` document and target resources by using rate controls. This should be set to the SSM document `parameter` that will define how your automation will branch out.
*/
public readonly automationTargetParameterName!: pulumi.Output<string | undefined>;
/**
* The compliance severity for the association. Can be one of the following: `UNSPECIFIED`, `LOW`, `MEDIUM`, `HIGH` or `CRITICAL`
*/
public readonly complianceSeverity!: pulumi.Output<string | undefined>;
/**
* The document version you want to associate with the target(s). Can be a specific version or the default version.
*/
public readonly documentVersion!: pulumi.Output<string>;
/**
* The instance ID to apply an SSM document to. Use `targets` with key `InstanceIds` for document schema versions 2.0 and above.
*/
public readonly instanceId!: pulumi.Output<string | undefined>;
/**
* The maximum number of targets allowed to run the association at the same time. You can specify a number, for example 10, or a percentage of the target set, for example 10%.
*/
public readonly maxConcurrency!: pulumi.Output<string | undefined>;
/**
* The number of errors that are allowed before the system stops sending requests to run the association on additional targets. You can specify a number, for example 10, or a percentage of the target set, for example 10%.
*/
public readonly maxErrors!: pulumi.Output<string | undefined>;
/**
* The name of the SSM document to apply.
*/
public readonly name!: pulumi.Output<string>;
/**
* An output location block. Output Location is documented below.
*/
public readonly outputLocation!: pulumi.Output<outputs.ssm.AssociationOutputLocation | undefined>;
/**
* A block of arbitrary string parameters to pass to the SSM document.
*/
public readonly parameters!: pulumi.Output<{[key: string]: string}>;
/**
* A cron expression when the association will be applied to the target(s).
*/
public readonly scheduleExpression!: pulumi.Output<string | undefined>;
/**
* A block containing the targets of the SSM association. Targets are documented below. AWS currently supports a maximum of 5 targets.
*/
public readonly targets!: pulumi.Output<outputs.ssm.AssociationTarget[]>;
/**
* Create a Association resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args?: AssociationArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: AssociationArgs | AssociationState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as AssociationState | undefined;
inputs["applyOnlyAtCronInterval"] = state ? state.applyOnlyAtCronInterval : undefined;
inputs["associationId"] = state ? state.associationId : undefined;
inputs["associationName"] = state ? state.associationName : undefined;
inputs["automationTargetParameterName"] = state ? state.automationTargetParameterName : undefined;
inputs["complianceSeverity"] = state ? state.complianceSeverity : undefined;
inputs["documentVersion"] = state ? state.documentVersion : undefined;
inputs["instanceId"] = state ? state.instanceId : undefined;
inputs["maxConcurrency"] = state ? state.maxConcurrency : undefined;
inputs["maxErrors"] = state ? state.maxErrors : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["outputLocation"] = state ? state.outputLocation : undefined;
inputs["parameters"] = state ? state.parameters : undefined;
inputs["scheduleExpression"] = state ? state.scheduleExpression : undefined;
inputs["targets"] = state ? state.targets : undefined;
} else {
const args = argsOrState as AssociationArgs | undefined;
inputs["applyOnlyAtCronInterval"] = args ? args.applyOnlyAtCronInterval : undefined;
inputs["associationName"] = args ? args.associationName : undefined;
inputs["automationTargetParameterName"] = args ? args.automationTargetParameterName : undefined;
inputs["complianceSeverity"] = args ? args.complianceSeverity : undefined;
inputs["documentVersion"] = args ? args.documentVersion : undefined;
inputs["instanceId"] = args ? args.instanceId : undefined;
inputs["maxConcurrency"] = args ? args.maxConcurrency : undefined;
inputs["maxErrors"] = args ? args.maxErrors : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["outputLocation"] = args ? args.outputLocation : undefined;
inputs["parameters"] = args ? args.parameters : undefined;
inputs["scheduleExpression"] = args ? args.scheduleExpression : undefined;
inputs["targets"] = args ? args.targets : undefined;
inputs["associationId"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Association.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Association resources.
*/
export interface AssociationState {
/**
* By default, when you create a new or update associations, the system runs it immediately and then according to the schedule you specified. Enable this option if you do not want an association to run immediately after you create or update it. This parameter is not supported for rate expressions. Default: `false`.
*/
applyOnlyAtCronInterval?: pulumi.Input<boolean>;
/**
* The ID of the SSM association.
*/
associationId?: pulumi.Input<string>;
/**
* The descriptive name for the association.
*/
associationName?: pulumi.Input<string>;
/**
* Specify the target for the association. This target is required for associations that use an `Automation` document and target resources by using rate controls. This should be set to the SSM document `parameter` that will define how your automation will branch out.
*/
automationTargetParameterName?: pulumi.Input<string>;
/**
* The compliance severity for the association. Can be one of the following: `UNSPECIFIED`, `LOW`, `MEDIUM`, `HIGH` or `CRITICAL`
*/
complianceSeverity?: pulumi.Input<string>;
/**
* The document version you want to associate with the target(s). Can be a specific version or the default version.
*/
documentVersion?: pulumi.Input<string>;
/**
* The instance ID to apply an SSM document to. Use `targets` with key `InstanceIds` for document schema versions 2.0 and above.
*/
instanceId?: pulumi.Input<string>;
/**
* The maximum number of targets allowed to run the association at the same time. You can specify a number, for example 10, or a percentage of the target set, for example 10%.
*/
maxConcurrency?: pulumi.Input<string>;
/**
* The number of errors that are allowed before the system stops sending requests to run the association on additional targets. You can specify a number, for example 10, or a percentage of the target set, for example 10%.
*/
maxErrors?: pulumi.Input<string>;
/**
* The name of the SSM document to apply.
*/
name?: pulumi.Input<string>;
/**
* An output location block. Output Location is documented below.
*/
outputLocation?: pulumi.Input<inputs.ssm.AssociationOutputLocation>;
/**
* A block of arbitrary string parameters to pass to the SSM document.
*/
parameters?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A cron expression when the association will be applied to the target(s).
*/
scheduleExpression?: pulumi.Input<string>;
/**
* A block containing the targets of the SSM association. Targets are documented below. AWS currently supports a maximum of 5 targets.
*/
targets?: pulumi.Input<pulumi.Input<inputs.ssm.AssociationTarget>[]>;
}
/**
* The set of arguments for constructing a Association resource.
*/
export interface AssociationArgs {
/**
* By default, when you create a new or update associations, the system runs it immediately and then according to the schedule you specified. Enable this option if you do not want an association to run immediately after you create or update it. This parameter is not supported for rate expressions. Default: `false`.
*/
applyOnlyAtCronInterval?: pulumi.Input<boolean>;
/**
* The descriptive name for the association.
*/
associationName?: pulumi.Input<string>;
/**
* Specify the target for the association. This target is required for associations that use an `Automation` document and target resources by using rate controls. This should be set to the SSM document `parameter` that will define how your automation will branch out.
*/
automationTargetParameterName?: pulumi.Input<string>;
/**
* The compliance severity for the association. Can be one of the following: `UNSPECIFIED`, `LOW`, `MEDIUM`, `HIGH` or `CRITICAL`
*/
complianceSeverity?: pulumi.Input<string>;
/**
* The document version you want to associate with the target(s). Can be a specific version or the default version.
*/
documentVersion?: pulumi.Input<string>;
/**
* The instance ID to apply an SSM document to. Use `targets` with key `InstanceIds` for document schema versions 2.0 and above.
*/
instanceId?: pulumi.Input<string>;
/**
* The maximum number of targets allowed to run the association at the same time. You can specify a number, for example 10, or a percentage of the target set, for example 10%.
*/
maxConcurrency?: pulumi.Input<string>;
/**
* The number of errors that are allowed before the system stops sending requests to run the association on additional targets. You can specify a number, for example 10, or a percentage of the target set, for example 10%.
*/
maxErrors?: pulumi.Input<string>;
/**
* The name of the SSM document to apply.
*/
name?: pulumi.Input<string>;
/**
* An output location block. Output Location is documented below.
*/
outputLocation?: pulumi.Input<inputs.ssm.AssociationOutputLocation>;
/**
* A block of arbitrary string parameters to pass to the SSM document.
*/
parameters?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A cron expression when the association will be applied to the target(s).
*/
scheduleExpression?: pulumi.Input<string>;
/**
* A block containing the targets of the SSM association. Targets are documented below. AWS currently supports a maximum of 5 targets.
*/
targets?: pulumi.Input<pulumi.Input<inputs.ssm.AssociationTarget>[]>;
} | the_stack |
import { JSONValue } from 'k6';
import { Selection } from 'k6/html';
import {
CookieJar,
CookieJarCookies,
FileData,
RefinedResponse,
Response,
ResponseType,
del,
get,
options,
patch,
post,
put,
request,
batch,
file,
cookieJar,
} from 'k6/http';
const address = 'http://example.com';
let response: Response;
let responseDefault: RefinedResponse<undefined>;
let responseBinary: RefinedResponse<'binary'>;
let responseNone: RefinedResponse<'none'>;
let responseText: RefinedResponse<'text'>;
let responsesArray: Response[];
let responsesArrayDefault: Array<RefinedResponse<undefined>>;
let responsesArrayBinary: Array<RefinedResponse<'binary'>>;
let responsesArrayNone: Array<RefinedResponse<'none'>>;
let responsesArrayText: Array<RefinedResponse<'text'>>;
let responsesMap: { [name: string]: Response };
let responsesMapDefault: { [name: string]: RefinedResponse<undefined> };
let responsesMapBinary: { [name: string]: RefinedResponse<'binary'> };
let responsesMapNone: { [name: string]: RefinedResponse<'none'> };
let responsesMapText: { [name: string]: RefinedResponse<'text'> };
let fileData: FileData;
let html: Selection;
let json: JSONValue | undefined;
let cookies: CookieJarCookies;
let jar: CookieJar;
// del
del(); // $ExpectError
del(5); // $ExpectError
responseDefault = del(address);
del(address, 5); // $ExpectError
responseDefault = del(address, 'skadoosh');
responseDefault = del(address, {});
responseDefault = del(address, { item: '576' });
del(address, {}, 5); // $ExpectError
responseBinary = del(address, null, { responseType: 'binary' });
del(address, {}, {}, 5); // $ExpectError
// get
get(); // $ExpectError
get(5); // $ExpectError
responseDefault = get(address);
get(address, 5); // $ExpectError
responseDefault = get(address, {});
responseBinary = get(address, { responseType: 'binary' });
responseNone = get(address, { responseType: 'none' });
responseText = get(address, { responseType: 'text' });
get(address, {}, 5); // $ExpectError
// options
options(); // $ExpectError
options(5); // $ExpectError
responseDefault = options(address);
options(address, 5); // $ExpectError
responseDefault = options(address, 'choices choices');
responseDefault = options(address, {});
responseDefault = options(address, { theme: 'forest' });
options(address, {}, 5); // $ExpectError
responseNone = options(address, {}, { responseType: 'none' });
options(address, {}, {}, 5); // $ExpectError
// patch
patch(); // $ExpectError
patch(5); // $ExpectError
responseDefault = patch(address);
patch(address, 5); // $ExpectError
responseDefault = patch(address, 'a life of contrasts and patchwork');
responseDefault = patch(address, {});
responseDefault = patch(address, { weaponOfChoice: 'pen' });
patch(address, {}, 5); // $ExpectError
responseBinary = patch(address, {}, { responseType: 'binary' });
patch(address, {}, {}, 5); // $ExpectError
// post
post(); // $ExpectError
post(5); // $ExpectError
responseDefault = post(address);
post(address, 5); // $ExpectError
responseDefault = post(address, 'hello in cyberspace');
responseDefault = post(address, {});
responseDefault = post(address, { query: 'kittens' });
post(address, {}, 5); // $ExpectError
responseNone = post(address, null, { responseType: 'none' });
post(address, {}, {}, 5); // $ExpectError
// put
put(); // $ExpectError
put(5); // $ExpectError
responseDefault = put(address);
put(address, 5); // $ExpectError
responseDefault = put(address, 'cat in box');
responseDefault = put(address, {});
responseDefault = put(address, { box: 'cat' });
put(address, {}, 5); // $ExpectError
responseText = put(address, null, { responseType: 'text' });
put(address, {}, {}, 5); // $ExpectError
// request
request(); // $ExpectError
request(5); // $ExpectError
request('get'); // $ExpectError
request('get', 5); // $ExpectError
responseDefault = request('get', address);
request('post', address, 5); // $ExpectError
responseDefault = request('post', address, 'welcome to the internet');
responseDefault = request('post', address, {});
responseDefault = request('post', address, { query: 'quokka' });
request('post', address, {}, 5); // $ExpectError
responseBinary = request('post', address, {}, { responseType: 'binary' });
request('post', address, {}, {}, 5); // $ExpectError
// batch
batch(); // $ExpectError
batch(5); // $ExpectError
batch([ address ], 5); // $ExpectError
// batch(Array)
responsesArray = batch([]);
responsesArrayDefault = batch([ address ]);
responsesArrayDefault = batch([ address, address, address ]);
responsesArrayDefault = batch([
[ 'GET', address ],
[ 'POST', address, 'hello' ],
[ 'POST', address, { title: 'Hello' }, {} ]
]);
responsesArrayBinary = batch([
[ 'GET', address, null, { responseType: 'binary' } ],
[ 'GET', address, null, { responseType: 'binary' } ],
[ 'GET', address, null, { responseType: 'binary' } ]
]);
responsesArrayNone = batch([
[ 'GET', address, null, { responseType: 'none' } ],
[ 'GET', address, null, { responseType: 'none' } ],
[ 'GET', address, null, { responseType: 'none' } ]
]);
responsesArrayText = batch([
[ 'GET', address, null, { responseType: 'text' } ],
[ 'GET', address, null, { responseType: 'text' } ],
[ 'GET', address, null, { responseType: 'text' } ]
]);
/*
Incorrectly passes due to https://github.com/microsoft/TypeScript/issues/32070
This is an obscure pattern that probably won't happen in practice.
To be enabled when the ability becomes available.
/// $ExpectError
responsesArrayText = batch([
[ 'GET', address, null, { responseType: 'binary' } ],
[ 'GET', address, null, { responseType: 'none' } ],
[ 'GET', address, null, { responseType: 'text' } ]
]);
*/
responsesArray = batch([
[ 'GET', address, null, { responseType: 'binary' } ],
[ 'GET', address, null, { responseType: 'none' } ],
[ 'GET', address, null, { responseType: 'text' } ]
]);
responsesArrayDefault = batch([ { method: 'GET', url: address } ]);
responsesArrayDefault = batch([
{ method: 'GET', url: address },
{ method: 'GET', url: address },
{ method: 'GET', url: address }
]);
responsesArrayBinary = batch([
{ method: 'GET', url: address, params: { responseType: 'binary' } },
{ method: 'GET', url: address, params: { responseType: 'binary' } },
{ method: 'GET', url: address, params: { responseType: 'binary' } }
]);
responsesArray = batch([
{ method: 'GET', url: address, params: { responseType: 'binary' } },
{ method: 'GET', url: address, params: { responseType: 'none' } },
{ method: 'GET', url: address, params: { responseType: 'text' } }
]);
// batch(object)
responsesMap = batch({});
responsesMapDefault = batch({ home: address });
responsesMapDefault = batch({
home: address,
about: address,
forum: address
});
responsesMapBinary = batch({
home: [ 'GET', address, null, { responseType: 'binary' } ],
about: [ 'GET', address, null, { responseType: 'binary' } ],
forum: [ 'GET', address, null, { responseType: 'binary' } ]
});
responsesMapNone = batch({
home: [ 'GET', address, null, { responseType: 'none' } ],
about: [ 'GET', address, null, { responseType: 'none' } ],
forum: [ 'GET', address, null, { responseType: 'none' } ]
});
responsesMapText = batch({
home: [ 'GET', address, null, { responseType: 'text' } ],
about: [ 'GET', address, null, { responseType: 'text' } ],
forum: [ 'GET', address, null, { responseType: 'text' } ]
});
// $ExpectError
responsesMapBinary = batch({
home: [ 'GET', address, null, { responseType: 'binary' } ],
about: [ 'GET', address, null, { responseType: 'none' } ],
forum: [ 'GET', address, null, { responseType: 'text' } ]
});
responsesMap = batch({
home: [ 'GET', address, null, { responseType: 'binary' } ],
about: [ 'GET', address, null, { responseType: 'none' } ],
forum: [ 'GET', address, null, { responseType: 'text' } ]
});
responsesMapDefault = batch({ home: { method: 'GET', url: address } });
responsesMapDefault = batch({
home: { method: 'GET', url: address },
about: { method: 'GET', url: address },
forum: { method: 'GET', url: address }
});
responsesMapText = batch({
home: { method: 'GET', url: address, params: { responseType: 'text' } },
about: { method: 'GET', url: address, params: { responseType: 'text' } },
forum: { method: 'GET', url: address, params: { responseType: 'text' } }
});
responsesMap = batch({
home: { method: 'GET', url: address, params: { responseType: 'binary' } },
about: { method: 'GET', url: address, params: { responseType: 'none' } },
forum: { method: 'GET', url: address, params: { responseType: 'text' } }
});
// file
file(); // $ExpectError
file(5); // $ExpectError
fileData = file('important data');
fileData = file([ 1, 2, 3 ]);
file('', 5); // $ExpectError
fileData = file('important data', 'data.txt');
file('important data', 'data.txt', 5); // $ExpectError
fileData = file('important data', 'data.txt', 'text/plain');
file('important data', 'data.txt', 'text/plain', 5); // $ExpectError
post(address, {
recipient: 'research-lab-XIII',
data: file('important data', 'data.txt'),
summary: file('short digest', 'summary.txt'),
analysis: file('thorough analysis', 'analysis.txt')
});
// Response.clickLink
response = get(address);
responseDefault = response.clickLink();
response.clickLink(5); // $ExpectError
responseDefault = response.clickLink({});
responseBinary = response.clickLink({
selector: 'div.menu span#home',
params: { responseType: 'binary' }
});
response.clickLink({}, 5); // $ExpectError
// Response.html
response = get(address);
html = response.html();
response.html(5); // $ExpectError
html = response.html('div span.item');
response.html('div span.item', 5); // $ExpectError
// Response.json
response = get(address);
json = response.json();
response.json(5); // $ExpectError
json = response.json('user.name');
response.json('user.name', 5); // $ExpectError
// Response.submitForm
response = get(address);
responseDefault = response.submitForm();
response.submitForm(5); // $ExpectError
responseDefault = response.submitForm({});
responseText = response.submitForm({
formSelector: 'div.input form',
fields: {
title: 'How to train your dragon',
body: 'This post shares my years of experience training dragons.'
},
submitSelector: 'div.input form button.submit',
params: { responseType: 'text' }
});
response.submitForm({}, 5); // $ExpectError
// cookieJar
jar = cookieJar();
cookieJar(5); // $ExpectError
// CookieJar.cookiesForURL
jar = cookieJar();
jar.cookiesForURL(); // $ExpectError
jar.cookiesForURL(5); // $ExpectError
cookies = jar.cookiesForURL(address);
jar.cookiesForURL(address, 5); // $ExpectError
// CookieJar.set
jar = cookieJar();
jar.set(); // $ExpectError
jar.set(5); // $ExpectError
jar.set('session'); // $ExpectError
jar.set('session', 5); // $ExpectError
jar.set('session', 'abc123'); // $ExpectType void
jar.set('session', 'abc123', null); // $ExpectType void
jar.set('session', 'abc123', {}); // $ExpectType void
jar.set('session', 'abc123', { badoption: true }); // $ExpectError
jar.set('session', 'abc123', { domain: 'example.com' }); // $ExpectType void
// $ExpectType void
jar.set('session', 'abc123', {
domain: address,
path: '/index.html',
expires: '2019-06-23T18:04:45Z',
max_age: 10,
secure: true,
http_only: true,
});
jar.set('session', 'abc123', {}, 5); // $ExpectError | the_stack |
import type { BaseButtonTheme } from '@instructure/shared-types'
import type {
BaseButtonProps,
BaseButtonStyleProps,
BaseButtonStyle
} from './props'
/**
* ---
* private: true
* ---
* Generates the style object from the theme and provided additional information
* @param {Object} componentTheme The theme variable object.
* @param {Object} props the props of the component, the style is applied to
* @param {Object} state the state of the component, the style is applied to
* @return {Object} The final style object, which will be used in the component
*/
const generateStyle = (
componentTheme: BaseButtonTheme,
props: BaseButtonProps,
state: BaseButtonStyleProps
): BaseButtonStyle => {
const {
size,
color,
textAlign,
shape,
withBackground,
withBorder,
isCondensed
} = props
const { isDisabled, hasOnlyIconVisible } = state
const shapeVariants = {
circle: { borderRadius: '50%' },
rectangle: {}
}
const sizeVariants = {
small: {
content: {
fontSize: componentTheme.smallFontSize,
paddingLeft: componentTheme.smallPaddingHorizontal,
paddingRight: componentTheme.smallPaddingHorizontal,
...(hasOnlyIconVisible && {
paddingLeft: 0,
paddingRight: 0,
height: componentTheme.smallHeight,
width: componentTheme.smallHeight
})
},
children: {
paddingTop: componentTheme.smallPaddingTop,
paddingBottom: componentTheme.smallPaddingBottom
},
iconSVG: {
fontSize: isCondensed
? componentTheme.smallFontSize
: componentTheme.iconSizeSmall
}
},
medium: {
content: {
fontSize: componentTheme.mediumFontSize,
paddingLeft: componentTheme.mediumPaddingHorizontal,
paddingRight: componentTheme.mediumPaddingHorizontal,
...(hasOnlyIconVisible && {
paddingLeft: 0,
paddingRight: 0,
height: componentTheme.mediumHeight,
width: componentTheme.mediumHeight
})
},
children: {
paddingTop: componentTheme.mediumPaddingTop,
paddingBottom: componentTheme.mediumPaddingBottom
},
iconSVG: {
fontSize: isCondensed
? componentTheme.mediumFontSize
: componentTheme.iconSizeMedium
}
},
large: {
content: {
fontSize: componentTheme.largeFontSize,
paddingLeft: componentTheme.largePaddingHorizontal,
paddingRight: componentTheme.largePaddingHorizontal,
...(hasOnlyIconVisible && {
paddingLeft: 0,
paddingRight: 0,
height: componentTheme.largeHeight,
width: componentTheme.largeHeight
})
},
children: {
paddingTop: componentTheme.largePaddingTop,
paddingBottom: componentTheme.largePaddingBottom
},
iconSVG: {
fontSize: isCondensed
? componentTheme.largeFontSize
: componentTheme.iconSizeLarge
}
}
}
const colorVariants = {
primary: withBackground
? {
default: {
color: componentTheme.primaryColor,
background: componentTheme.primaryBackground,
borderColor: componentTheme.primaryBorderColor
},
active: {
background: componentTheme.primaryActiveBackground,
boxShadow: componentTheme.primaryActiveBoxShadow
},
hover: {
background: componentTheme.primaryHoverBackground
}
}
: {
default: {
color: componentTheme.primaryGhostColor,
borderColor: componentTheme.primaryGhostBorderColor,
background: componentTheme.primaryGhostBackground
},
active: {
background: componentTheme.primaryGhostActiveBackground,
boxShadow: componentTheme.primaryGhostActiveBoxShadow
},
hover: {
background: componentTheme.primaryGhostHoverBackground
}
},
secondary: withBackground
? {
default: {
color: componentTheme.secondaryColor,
background: componentTheme.secondaryBackground,
borderColor: componentTheme.secondaryBorderColor
},
active: {
background: componentTheme.secondaryActiveBackground,
boxShadow: componentTheme.secondaryActiveBoxShadow
},
hover: {
background: componentTheme.secondaryHoverBackground
}
}
: {
default: {
color: componentTheme.secondaryGhostColor,
borderColor: componentTheme.secondaryGhostBorderColor,
background: componentTheme.secondaryGhostBackground
},
active: {
background: componentTheme.secondaryGhostActiveBackground,
boxShadow: componentTheme.secondaryGhostActiveBoxShadow
},
hover: {
background: componentTheme.secondaryGhostHoverBackground
}
},
'primary-inverse': withBackground
? {
default: {
color: componentTheme.primaryInverseColor,
background: componentTheme.primaryInverseBackground,
borderColor: componentTheme.primaryInverseBorderColor
},
active: {
background: componentTheme.primaryInverseActiveBackground,
boxShadow: componentTheme.primaryInverseActiveBoxShadow
},
hover: {
background: componentTheme.primaryInverseHoverBackground
}
}
: {
default: {
color: componentTheme.primaryInverseGhostColor,
borderColor: componentTheme.primaryInverseGhostBorderColor,
background: componentTheme.primaryInverseGhostBackground
},
active: {
background: componentTheme.primaryInverseGhostActiveBackground,
boxShadow: componentTheme.primaryInverseGhostActiveBoxShadow
},
hover: {
background: componentTheme.primaryInverseGhostHoverBackground
}
},
success: withBackground
? {
default: {
color: componentTheme.successColor,
background: componentTheme.successBackground,
borderColor: componentTheme.successBorderColor
},
active: {
background: componentTheme.successActiveBackground,
boxShadow: componentTheme.successActiveBoxShadow
},
hover: {
background: componentTheme.successHoverBackground
}
}
: {
default: {
color: componentTheme.successGhostColor,
borderColor: componentTheme.successGhostBorderColor,
background: componentTheme.successGhostBackground
},
active: {
background: componentTheme.successGhostActiveBackground,
boxShadow: componentTheme.successGhostActiveBoxShadow
},
hover: {
background: componentTheme.successGhostHoverBackground
}
},
danger: withBackground
? {
default: {
color: componentTheme.dangerColor,
background: componentTheme.dangerBackground,
borderColor: componentTheme.dangerBorderColor
},
active: {
background: componentTheme.dangerActiveBackground,
boxShadow: componentTheme.dangerActiveBoxShadow
},
hover: {
background: componentTheme.dangerHoverBackground
}
}
: {
default: {
color: componentTheme.dangerGhostColor,
borderColor: componentTheme.dangerGhostBorderColor,
background: componentTheme.dangerGhostBackground
},
active: {
background: componentTheme.dangerGhostActiveBackground,
boxShadow: componentTheme.dangerGhostActiveBoxShadow
},
hover: {
background: componentTheme.dangerGhostHoverBackground
}
}
}
return {
baseButton: {
label: 'baseButton',
appearance: 'none',
textDecoration: 'none' /* for links styled as buttons */,
touchAction: 'manipulation',
'&::-moz-focus-inner': {
border: '0' /* removes default dotted focus outline in Firefox */
},
'*': {
pointerEvents:
'none' /* Ensures that button or link is always the event target */
},
'&:active > [class$=-baseButton__content]': colorVariants[color!].active,
'&:hover > [class$=-baseButton__content]': colorVariants[color!].hover
},
content: {
label: 'baseButton__content',
boxSizing: 'border-box',
width: '100%',
display: 'block',
direction: 'inherit',
userSelect: 'none',
transition: 'background 0.2s, transform 0.2s',
transform: componentTheme.transform,
fontFamily: componentTheme.fontFamily,
fontWeight: componentTheme.fontWeight,
textTransform: componentTheme.textTransform,
letterSpacing: componentTheme.letterSpacing,
borderStyle: componentTheme.borderStyle,
borderWidth: componentTheme.borderWidth,
borderRadius: componentTheme.borderRadius,
lineHeight: componentTheme.lineHeight,
textAlign,
'&:hover': { transform: componentTheme.hoverTransform },
...sizeVariants[size!].content,
...colorVariants[color!].default,
...shapeVariants[shape!],
...(isCondensed && {
paddingLeft: 0,
paddingRight: 0
}),
...(isDisabled && {
opacity: 0.5
}),
...(hasOnlyIconVisible && {
lineHeight: 1
}),
...(!withBorder && {
borderStyle: 'none'
})
},
children: {
label: 'baseButton__children',
display: 'block',
...sizeVariants[size!].children,
...(isCondensed && {
paddingTop: 0,
paddingBottom: 0
})
},
iconSVG: {
label: 'baseButton__iconSVG',
display: 'flex',
alignItems: 'center',
...sizeVariants[size!].iconSVG
},
childrenLayout: {
label: 'baseButton__childrenLayout',
display: 'flex',
height: '100%',
width: '100%',
justifyContent:
hasOnlyIconVisible || textAlign === 'center' ? 'center' : 'flex-start',
boxSizing: 'border-box',
alignItems: 'center',
flexDirection: 'row',
maxWidth: '100%',
overflowX: 'visible',
overflowY: 'visible',
unicodeBidi: 'isolate'
},
iconOnly: {
label: 'baseButton__iconOnly',
boxSizing: 'border-box',
minWidth: '0.0625rem',
flexShrink: 0,
maxWidth: '100%',
overflowX: 'visible',
overflowY: 'visible',
unicodeBidi: 'isolate'
},
iconWrapper: {
label: 'baseButton__iconWrapper',
boxSizing: 'border-box',
minWidth: '0.0625rem',
paddingInlineEnd: isCondensed
? componentTheme.iconTextGapCondensed
: componentTheme.iconTextGap,
flexShrink: 0,
maxWidth: '100%',
overflowX: 'visible',
overflowY: 'visible',
unicodeBidi: 'isolate'
},
childrenWrapper: {
label: 'baseButton__childrenWrapper',
boxSizing: 'border-box',
minWidth: '0.0625rem',
flexShrink: 1,
maxWidth: '100%',
overflowX: 'visible',
overflowY: 'visible',
unicodeBidi: 'isolate'
}
}
}
export default generateStyle | the_stack |
/* eslint-disable @typescript-eslint/class-name-casing */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-empty-interface */
/* eslint-disable @typescript-eslint/no-namespace */
/* eslint-disable no-irregular-whitespace */
import {
OAuth2Client,
JWT,
Compute,
UserRefreshClient,
BaseExternalAccountClient,
GaxiosPromise,
GoogleConfigurable,
createAPIRequest,
MethodOptions,
StreamMethodOptions,
GlobalOptions,
GoogleAuth,
BodyResponseCallback,
APIRequestContext,
} from 'googleapis-common';
import {Readable} from 'stream';
export namespace fcmdata_v1beta1 {
export interface Options extends GlobalOptions {
version: 'v1beta1';
}
interface StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?:
| string
| OAuth2Client
| JWT
| Compute
| UserRefreshClient
| BaseExternalAccountClient
| GoogleAuth;
/**
* V1 error format.
*/
'$.xgafv'?: string;
/**
* OAuth access token.
*/
access_token?: string;
/**
* Data format for response.
*/
alt?: string;
/**
* JSONP
*/
callback?: string;
/**
* Selector specifying which fields to include in a partial response.
*/
fields?: string;
/**
* API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
*/
key?: string;
/**
* OAuth 2.0 token for the current user.
*/
oauth_token?: string;
/**
* Returns response with indentations and line breaks.
*/
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
*/
quotaUser?: string;
/**
* Legacy upload protocol for media (e.g. "media", "multipart").
*/
uploadType?: string;
/**
* Upload protocol for media (e.g. "raw", "multipart").
*/
upload_protocol?: string;
}
/**
* Firebase Cloud Messaging Data API
*
* Provides additional information about Firebase Cloud Messaging (FCM) message sends and deliveries.
*
* @example
* ```js
* const {google} = require('googleapis');
* const fcmdata = google.fcmdata('v1beta1');
* ```
*/
export class Fcmdata {
context: APIRequestContext;
projects: Resource$Projects;
constructor(options: GlobalOptions, google?: GoogleConfigurable) {
this.context = {
_options: options || {},
google,
};
this.projects = new Resource$Projects(this.context);
}
}
/**
* Message delivery data for a given date, app, and analytics label combination.
*/
export interface Schema$GoogleFirebaseFcmDataV1beta1AndroidDeliveryData {
/**
* The analytics label associated with the messages sent. All messages sent without an analytics label will be grouped together in a single entry.
*/
analyticsLabel?: string | null;
/**
* The app ID to which the messages were sent.
*/
appId?: string | null;
/**
* The data for the specified appId, date, and analyticsLabel.
*/
data?: Schema$GoogleFirebaseFcmDataV1beta1Data;
/**
* The date represented by this entry.
*/
date?: Schema$GoogleTypeDate;
}
/**
* Data detailing messaging delivery
*/
export interface Schema$GoogleFirebaseFcmDataV1beta1Data {
/**
* Count of messages accepted by FCM intended to Android devices. The targeted device must have opted in to the collection of usage and diagnostic information.
*/
countMessagesAccepted?: string | null;
/**
* Additional information about delivery performance for messages that were successfully delivered.
*/
deliveryPerformancePercents?: Schema$GoogleFirebaseFcmDataV1beta1DeliveryPerformancePercents;
/**
* Additional general insights about message delivery.
*/
messageInsightPercents?: Schema$GoogleFirebaseFcmDataV1beta1MessageInsightPercents;
/**
* Mutually exclusive breakdown of message delivery outcomes.
*/
messageOutcomePercents?: Schema$GoogleFirebaseFcmDataV1beta1MessageOutcomePercents;
}
/**
* Overview of delivery performance for messages that were successfully delivered. All percentages are calculated with countMessagesAccepted as the denominator. These categories are not mutually exclusive; a message can be delayed for multiple reasons.
*/
export interface Schema$GoogleFirebaseFcmDataV1beta1DeliveryPerformancePercents {
/**
* The percentage of accepted messages that were delayed because the device was in doze mode. Only [normal priority messages](https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message) should be delayed due to doze mode.
*/
delayedDeviceDoze?: number | null;
/**
* The percentage of accepted messages that were delayed because the target device was not connected at the time of sending. These messages were eventually delivered when the device reconnected.
*/
delayedDeviceOffline?: number | null;
/**
* The percentage of accepted messages that were delayed due to message throttling, such as [collapsible message throttling](https://firebase.google.com/docs/cloud-messaging/concept-options#collapsible_throttling) or [maximum message rate throttling](https://firebase.google.com/docs/cloud-messaging/concept-options#device_throttling).
*/
delayedMessageThrottled?: number | null;
/**
* The percentage of accepted messages that were delayed because the intended device user-profile was [stopped](https://firebase.google.com/docs/cloud-messaging/android/receive#handling_messages) on the target device at the time of the send. The messages were eventually delivered when the user-profile was started again.
*/
delayedUserStopped?: number | null;
/**
* The percentage of accepted messages that were delivered to the device without delay from the FCM system.
*/
deliveredNoDelay?: number | null;
}
/**
* Response message for ListAndroidDeliveryData.
*/
export interface Schema$GoogleFirebaseFcmDataV1beta1ListAndroidDeliveryDataResponse {
/**
* The delivery data for the provided app. There will be one entry per combination of app, date, and analytics label.
*/
androidDeliveryData?: Schema$GoogleFirebaseFcmDataV1beta1AndroidDeliveryData[];
/**
* A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no subsequent pages.
*/
nextPageToken?: string | null;
}
/**
* Additional information about message delivery. All percentages are calculated with countMessagesAccepted as the denominator.
*/
export interface Schema$GoogleFirebaseFcmDataV1beta1MessageInsightPercents {
/**
* The percentage of accepted messages that had their priority lowered from high to normal due to [app standby buckets](https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message).
*/
priorityLowered?: number | null;
}
/**
* Percentage breakdown of message delivery outcomes. These categories are mutually exclusive. All percentages are calculated with countMessagesAccepted as the denominator. These categories may not account for all message outcomes.
*/
export interface Schema$GoogleFirebaseFcmDataV1beta1MessageOutcomePercents {
/**
* The percentage of all accepted messages that were successfully delivered to the device.
*/
delivered?: number | null;
/**
* The percentage of accepted messages that were dropped because the application was force stopped on the device at the time of delivery and retries were unsuccessful.
*/
droppedAppForceStopped?: number | null;
/**
* The percentage of accepted messages that were dropped because the target device is inactive. FCM will drop messages if the target device is deemed inactive by our servers. If a device does reconnect, we call [OnDeletedMessages()](https://firebase.google.com/docs/cloud-messaging/android/receive#override-ondeletedmessages) in our SDK instead of delivering the messages.
*/
droppedDeviceInactive?: number | null;
/**
* The percentage of accepted messages that were dropped due to [too many undelivered non-collapsible messages](https://firebase.google.com/docs/cloud-messaging/concept-options#collapsible_and_non-collapsible_messages). Specifically, each app instance can only have 100 pending messages stored on our servers for a device which is disconnected. When that device reconnects, those messages are delivered. When there are more than the maximum pending messages, we call [OnDeletedMessages()](https://firebase.google.com/docs/cloud-messaging/android/receive#override-ondeletedmessages) in our SDK instead of delivering the messages.
*/
droppedTooManyPendingMessages?: number | null;
/**
* The percentage of messages accepted on this day that were not dropped and not delivered, due to the device being disconnected (as of the end of the America/Los_Angeles day when the message was sent to FCM). A portion of these messages will be delivered the next day when the device connects but others may be destined to devices that ultimately never reconnect.
*/
pending?: number | null;
}
/**
* Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values * A month and day value, with a zero year, such as an anniversary * A year on its own, with zero month and day values * A year and month value, with a zero day, such as a credit card expiration date Related types are google.type.TimeOfDay and `google.protobuf.Timestamp`.
*/
export interface Schema$GoogleTypeDate {
/**
* Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant.
*/
day?: number | null;
/**
* Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day.
*/
month?: number | null;
/**
* Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year.
*/
year?: number | null;
}
export class Resource$Projects {
context: APIRequestContext;
androidApps: Resource$Projects$Androidapps;
constructor(context: APIRequestContext) {
this.context = context;
this.androidApps = new Resource$Projects$Androidapps(this.context);
}
}
export class Resource$Projects$Androidapps {
context: APIRequestContext;
deliveryData: Resource$Projects$Androidapps$Deliverydata;
constructor(context: APIRequestContext) {
this.context = context;
this.deliveryData = new Resource$Projects$Androidapps$Deliverydata(
this.context
);
}
}
export class Resource$Projects$Androidapps$Deliverydata {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* List aggregate delivery data for the given Android application.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/fcmdata.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const fcmdata = google.fcmdata('v1beta1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: ['https://www.googleapis.com/auth/cloud-platform'],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await fcmdata.projects.androidApps.deliveryData.list({
* // The maximum number of entries to return. The service may return fewer than this value. If unspecified, at most 1,000 entries will be returned. The maximum value is 10,000; values above 10,000 will be capped to 10,000. This default may change over time.
* pageSize: 'placeholder-value',
* // A page token, received from a previous `ListAndroidDeliveryDataRequest` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `ListAndroidDeliveryDataRequest` must match the call that provided the page token.
* pageToken: 'placeholder-value',
* // Required. The application for which to list delivery data. Format: `projects/{project_id\}/androidApps/{app_id\}`
* parent: 'projects/my-project/androidApps/my-androidApp',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "androidDeliveryData": [],
* // "nextPageToken": "my_nextPageToken"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
list(
params: Params$Resource$Projects$Androidapps$Deliverydata$List,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
list(
params?: Params$Resource$Projects$Androidapps$Deliverydata$List,
options?: MethodOptions
): GaxiosPromise<Schema$GoogleFirebaseFcmDataV1beta1ListAndroidDeliveryDataResponse>;
list(
params: Params$Resource$Projects$Androidapps$Deliverydata$List,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
list(
params: Params$Resource$Projects$Androidapps$Deliverydata$List,
options:
| MethodOptions
| BodyResponseCallback<Schema$GoogleFirebaseFcmDataV1beta1ListAndroidDeliveryDataResponse>,
callback: BodyResponseCallback<Schema$GoogleFirebaseFcmDataV1beta1ListAndroidDeliveryDataResponse>
): void;
list(
params: Params$Resource$Projects$Androidapps$Deliverydata$List,
callback: BodyResponseCallback<Schema$GoogleFirebaseFcmDataV1beta1ListAndroidDeliveryDataResponse>
): void;
list(
callback: BodyResponseCallback<Schema$GoogleFirebaseFcmDataV1beta1ListAndroidDeliveryDataResponse>
): void;
list(
paramsOrCallback?:
| Params$Resource$Projects$Androidapps$Deliverydata$List
| BodyResponseCallback<Schema$GoogleFirebaseFcmDataV1beta1ListAndroidDeliveryDataResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$GoogleFirebaseFcmDataV1beta1ListAndroidDeliveryDataResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$GoogleFirebaseFcmDataV1beta1ListAndroidDeliveryDataResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$GoogleFirebaseFcmDataV1beta1ListAndroidDeliveryDataResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Projects$Androidapps$Deliverydata$List;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Projects$Androidapps$Deliverydata$List;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://fcmdata.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1beta1/{+parent}/deliveryData').replace(
/([^:]\/)\/+/g,
'$1'
),
method: 'GET',
},
options
),
params,
requiredParams: ['parent'],
pathParams: ['parent'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$GoogleFirebaseFcmDataV1beta1ListAndroidDeliveryDataResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$GoogleFirebaseFcmDataV1beta1ListAndroidDeliveryDataResponse>(
parameters
);
}
}
}
export interface Params$Resource$Projects$Androidapps$Deliverydata$List
extends StandardParameters {
/**
* The maximum number of entries to return. The service may return fewer than this value. If unspecified, at most 1,000 entries will be returned. The maximum value is 10,000; values above 10,000 will be capped to 10,000. This default may change over time.
*/
pageSize?: number;
/**
* A page token, received from a previous `ListAndroidDeliveryDataRequest` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `ListAndroidDeliveryDataRequest` must match the call that provided the page token.
*/
pageToken?: string;
/**
* Required. The application for which to list delivery data. Format: `projects/{project_id\}/androidApps/{app_id\}`
*/
parent?: string;
}
} | the_stack |
import { Util } from '../../global'
import { KeyValue } from '../../types'
import { Rectangle, Angle, Point } from '../../geometry'
import { ObjectExt, StringExt, FunctionExt } from '../../util'
import { Cell } from '../../model/cell'
import { Node } from '../../model/node'
import { Edge } from '../../model/edge'
import { Model } from '../../model/model'
import { Collection } from '../../model/collection'
import { View } from '../../view/view'
import { CellView } from '../../view/cell'
import { NodeView } from '../../view/node'
import { Graph } from '../../graph/graph'
import { Renderer } from '../../graph/renderer'
import { notify } from '../transform/util'
import { Handle } from '../common'
export class Selection extends View<Selection.EventArgs> {
public readonly options: Selection.Options
protected readonly collection: Collection
protected $container: JQuery<HTMLElement>
protected $selectionContainer: JQuery<HTMLElement>
protected $selectionContent: JQuery<HTMLElement>
protected boxCount: number
protected boxesUpdated: boolean
public get graph() {
return this.options.graph
}
protected get boxClassName() {
return this.prefixClassName(Private.classNames.box)
}
protected get $boxes() {
return this.$container.children(`.${this.boxClassName}`)
}
protected get handleOptions() {
return this.options
}
constructor(options: Selection.Options) {
super()
this.options = ObjectExt.merge({}, Private.defaultOptions, options)
if (this.options.model) {
this.options.collection = this.options.model.collection
}
if (this.options.collection) {
this.collection = this.options.collection
} else {
this.collection = new Collection([], {
comparator: Private.depthComparator,
})
this.options.collection = this.collection
}
this.boxCount = 0
this.createContainer()
this.initHandles()
this.startListening()
}
protected startListening() {
const graph = this.graph
const collection = this.collection
this.delegateEvents(
{
[`mousedown .${this.boxClassName}`]: 'onSelectionBoxMouseDown',
[`touchstart .${this.boxClassName}`]: 'onSelectionBoxMouseDown',
},
true,
)
graph.on('scale', this.onGraphTransformed, this)
graph.on('translate', this.onGraphTransformed, this)
graph.model.on('updated', this.onModelUpdated, this)
collection.on('added', this.onCellAdded, this)
collection.on('removed', this.onCellRemoved, this)
collection.on('reseted', this.onReseted, this)
collection.on('updated', this.onCollectionUpdated, this)
collection.on('node:change:position', this.onNodePositionChanged, this)
collection.on('cell:changed', this.onCellChanged, this)
}
protected stopListening() {
const graph = this.graph
const collection = this.collection
this.undelegateEvents()
graph.off('scale', this.onGraphTransformed, this)
graph.off('translate', this.onGraphTransformed, this)
graph.model.off('updated', this.onModelUpdated, this)
collection.off('added', this.onCellAdded, this)
collection.off('removed', this.onCellRemoved, this)
collection.off('reseted', this.onReseted, this)
collection.off('updated', this.onCollectionUpdated, this)
collection.off('node:change:position', this.onNodePositionChanged, this)
collection.off('cell:changed', this.onCellChanged, this)
}
protected onRemove() {
this.stopListening()
}
protected onGraphTransformed() {
this.updateSelectionBoxes({ async: false })
}
protected onCellChanged() {
this.updateSelectionBoxes()
}
protected translating: boolean
protected onNodePositionChanged({
node,
options,
}: Collection.EventArgs['node:change:position']) {
const { showNodeSelectionBox, pointerEvents } = this.options
const { ui, selection } = options
let allowTranslating = !this.translating
/* Scenarios where this method is not called:
* 1. ShowNodeSelection is true or ponterEvents is none
* 2. Avoid circular calls with the selection tag
*/
allowTranslating =
allowTranslating &&
(showNodeSelectionBox !== true || pointerEvents === 'none')
allowTranslating = allowTranslating && ui && !selection
if (allowTranslating) {
this.translating = true
const current = node.position()
const previous = node.previous('position')!
const dx = current.x - previous.x
const dy = current.y - previous.y
if (dx !== 0 || dy !== 0) {
this.translateSelectedNodes(dx, dy, node, options)
}
this.translating = false
}
}
protected onModelUpdated({ removed }: Collection.EventArgs['updated']) {
if (removed && removed.length) {
this.unselect(removed)
}
}
isEmpty() {
return this.length <= 0
}
isSelected(cell: Cell | string) {
return this.collection.has(cell)
}
get length() {
return this.collection.length
}
get cells() {
return this.collection.toArray()
}
select(cells: Cell | Cell[], options: Selection.AddOptions = {}) {
options.dryrun = true
const items = this.filter(Array.isArray(cells) ? cells : [cells])
this.collection.add(items, options)
return this
}
unselect(cells: Cell | Cell[], options: Selection.RemoveOptions = {}) {
// dryrun to prevent cell be removed from graph
options.dryrun = true
this.collection.remove(Array.isArray(cells) ? cells : [cells], options)
return this
}
reset(cells?: Cell | Cell[], options: Selection.SetOptions = {}) {
if (cells) {
if (options.batch) {
const filterCells = this.filter(Array.isArray(cells) ? cells : [cells])
this.collection.reset(filterCells, { ...options, ui: true })
return this
}
const prev = this.cells
const next = this.filter(Array.isArray(cells) ? cells : [cells])
const prevMap: KeyValue<Cell> = {}
const nextMap: KeyValue<Cell> = {}
prev.forEach((cell) => (prevMap[cell.id] = cell))
next.forEach((cell) => (nextMap[cell.id] = cell))
const added: Cell[] = []
const removed: Cell[] = []
next.forEach((cell) => {
if (!prevMap[cell.id]) {
added.push(cell)
}
})
prev.forEach((cell) => {
if (!nextMap[cell.id]) {
removed.push(cell)
}
})
if (removed.length) {
this.unselect(removed, { ...options, ui: true })
}
if (added.length) {
this.select(added, { ...options, ui: true })
}
if (removed.length === 0 && added.length === 0) {
this.updateContainer()
}
return this
}
return this.clean(options)
}
clean(options: Selection.SetOptions = {}) {
if (this.length) {
if (options.batch === false) {
this.unselect(this.cells, options)
} else {
this.collection.reset([], { ...options, ui: true })
}
}
return this
}
setFilter(filter?: Selection.Filter) {
this.options.filter = filter
}
setContent(content?: Selection.Content) {
this.options.content = content
}
startSelecting(evt: JQuery.MouseDownEvent) {
// Flow: startSelecting => adjustSelection => stopSelecting
evt = this.normalizeEvent(evt) // eslint-disable-line
this.clean()
let x
let y
const graphContainer = this.graph.container
if (
evt.offsetX != null &&
evt.offsetY != null &&
graphContainer.contains(evt.target)
) {
x = evt.offsetX
y = evt.offsetY
} else {
const offset = this.$(graphContainer).offset()!
const scrollLeft = graphContainer.scrollLeft
const scrollTop = graphContainer.scrollTop
x = evt.clientX - offset.left + window.pageXOffset + scrollLeft
y = evt.clientY - offset.top + window.pageYOffset + scrollTop
}
this.$container.css({
top: y,
left: x,
width: 1,
height: 1,
})
this.setEventData<EventData.Selecting>(evt, {
action: 'selecting',
clientX: evt.clientX,
clientY: evt.clientY,
offsetX: x,
offsetY: y,
scrollerX: 0,
scrollerY: 0,
})
this.delegateDocumentEvents(Private.documentEvents, evt.data)
}
filter(cells: Cell[]) {
const filter = this.options.filter
if (Array.isArray(filter)) {
return cells.filter(
(cell) => !filter.includes(cell) && !filter.includes(cell.shape),
)
}
if (typeof filter === 'function') {
return cells.filter((cell) => FunctionExt.call(filter, this.graph, cell))
}
return cells
}
protected stopSelecting(evt: JQuery.MouseUpEvent) {
const graph = this.graph
const eventData = this.getEventData<EventData.Common>(evt)
const action = eventData.action
switch (action) {
case 'selecting': {
let width = this.$container.width()!
let height = this.$container.height()!
const offset = this.$container.offset()!
const origin = graph.pageToLocal(offset.left, offset.top)
const scale = graph.transform.getScale()
width /= scale.sx
height /= scale.sy
const rect = new Rectangle(origin.x, origin.y, width, height)
const cells = this.getCellViewsInArea(rect).map((view) => view.cell)
this.reset(cells, { batch: true })
this.hideRubberband()
break
}
case 'translating': {
const client = graph.snapToGrid(evt.clientX, evt.clientY)
if (!this.options.following) {
const data = eventData as EventData.Translating
this.updateSelectedNodesPosition({
dx: data.clientX - data.originX,
dy: data.clientY - data.originY,
})
}
this.graph.model.stopBatch('move-selection')
this.notifyBoxEvent('box:mouseup', evt, client.x, client.y)
break
}
default: {
this.clean()
break
}
}
}
protected onMouseUp(evt: JQuery.MouseUpEvent) {
const action = this.getEventData<EventData.Common>(evt).action
if (action) {
this.stopSelecting(evt)
this.undelegateDocumentEvents()
}
}
protected onSelectionBoxMouseDown(evt: JQuery.MouseDownEvent) {
if (!this.options.following) {
evt.stopPropagation()
}
const e = this.normalizeEvent(evt)
if (this.options.movable) {
this.startTranslating(e)
}
const activeView = this.getCellViewFromElem(e.target)!
this.setEventData<EventData.SelectionBox>(e, { activeView })
const client = this.graph.snapToGrid(e.clientX, e.clientY)
this.notifyBoxEvent('box:mousedown', e, client.x, client.y)
this.delegateDocumentEvents(Private.documentEvents, e.data)
}
protected startTranslating(evt: JQuery.MouseDownEvent) {
this.graph.model.startBatch('move-selection')
const client = this.graph.snapToGrid(evt.clientX, evt.clientY)
this.setEventData<EventData.Translating>(evt, {
action: 'translating',
clientX: client.x,
clientY: client.y,
originX: client.x,
originY: client.y,
})
}
protected getSelectionOffset(client: Point, data: EventData.Translating) {
let dx = client.x - data.clientX
let dy = client.y - data.clientY
const restrict = this.graph.hook.getRestrictArea()
if (restrict) {
const cells = this.collection.toArray()
const totalBBox =
Cell.getCellsBBox(cells, { deep: true }) || Rectangle.create()
const minDx = restrict.x - totalBBox.x
const minDy = restrict.y - totalBBox.y
const maxDx =
restrict.x + restrict.width - (totalBBox.x + totalBBox.width)
const maxDy =
restrict.y + restrict.height - (totalBBox.y + totalBBox.height)
if (dx < minDx) {
dx = minDx
}
if (dy < minDy) {
dy = minDy
}
if (maxDx < dx) {
dx = maxDx
}
if (maxDy < dy) {
dy = maxDy
}
if (!this.options.following) {
const offsetX = client.x - data.originX
const offsetY = client.y - data.originY
dx = offsetX <= minDx || offsetX >= maxDx ? 0 : dx
dy = offsetY <= minDy || offsetY >= maxDy ? 0 : dy
}
}
return {
dx,
dy,
}
}
protected updateSelectedNodesPosition(offset: { dx: number; dy: number }) {
const { dx, dy } = offset
if (dx || dy) {
if ((this.translateSelectedNodes(dx, dy), this.boxesUpdated)) {
if (this.collection.length > 1) {
this.updateSelectionBoxes()
}
} else {
const scale = this.graph.transform.getScale()
this.$boxes.add(this.$selectionContainer).css({
left: `+=${dx * scale.sx}`,
top: `+=${dy * scale.sy}`,
})
}
}
}
protected autoScrollGraph(x: number, y: number) {
const scroller = this.graph.scroller.widget
if (scroller) {
return scroller.autoScroll(x, y)
}
return { scrollerX: 0, scrollerY: 0 }
}
protected adjustSelection(evt: JQuery.MouseMoveEvent) {
const e = this.normalizeEvent(evt)
const eventData = this.getEventData<EventData.Common>(e)
const action = eventData.action
switch (action) {
case 'selecting': {
const data = eventData as EventData.Selecting
if (data.moving !== true) {
this.$container.appendTo(this.graph.container)
this.showRubberband()
data.moving = true
}
const { scrollerX, scrollerY } = this.autoScrollGraph(
e.clientX,
e.clientY,
)
data.scrollerX += scrollerX
data.scrollerY += scrollerY
const dx = e.clientX - data.clientX + data.scrollerX
const dy = e.clientY - data.clientY + data.scrollerY
const left = parseInt(this.$container.css('left'), 10)
const top = parseInt(this.$container.css('top'), 10)
this.$container.css({
left: dx < 0 ? data.offsetX + dx : left,
top: dy < 0 ? data.offsetY + dy : top,
width: Math.abs(dx),
height: Math.abs(dy),
})
break
}
case 'translating': {
const client = this.graph.snapToGrid(e.clientX, e.clientY)
const data = eventData as EventData.Translating
const offset = this.getSelectionOffset(client, data)
if (this.options.following) {
this.updateSelectedNodesPosition(offset)
} else {
this.updateContainerPosition(offset)
}
if (offset.dx) {
data.clientX = client.x
}
if (offset.dy) {
data.clientY = client.y
}
this.notifyBoxEvent('box:mousemove', evt, client.x, client.y)
break
}
default:
break
}
this.boxesUpdated = false
}
protected translateSelectedNodes(
dx: number,
dy: number,
exclude?: Cell,
otherOptions?: KeyValue,
) {
const map: { [id: string]: boolean } = {}
const excluded: Cell[] = []
if (exclude) {
map[exclude.id] = true
}
this.collection.toArray().forEach((cell) => {
cell.getDescendants({ deep: true }).forEach((child) => {
map[child.id] = true
})
})
if (otherOptions && otherOptions.translateBy) {
const currentCell = this.graph.getCellById(otherOptions.translateBy)
if (currentCell) {
map[currentCell.id] = true
currentCell.getDescendants({ deep: true }).forEach((child) => {
map[child.id] = true
})
excluded.push(currentCell)
}
}
this.collection.toArray().forEach((cell) => {
if (!map[cell.id]) {
const options = {
...otherOptions,
selection: this.cid,
exclude: excluded,
}
cell.translate(dx, dy, options)
this.graph.model.getConnectedEdges(cell).forEach((edge) => {
if (!map[edge.id]) {
edge.translate(dx, dy, options)
map[edge.id] = true
}
})
}
})
}
protected getCellViewsInArea(rect: Rectangle) {
const graph = this.graph
const options = {
strict: this.options.strict,
}
let views: CellView[] = []
if (this.options.rubberNode) {
if (this.options.useCellGeometry) {
views = views.concat(
graph.model
.getNodesInArea(rect, options)
.map((node) => graph.renderer.findViewByCell(node))
.filter((view) => view != null) as CellView[],
)
} else {
views = views.concat(graph.renderer.findViewsInArea(rect, options))
}
}
if (this.options.rubberEdge) {
if (this.options.useCellGeometry) {
views = views.concat(
graph.model
.getEdgesInArea(rect, options)
.map((edge) => graph.renderer.findViewByCell(edge))
.filter((view) => view != null) as CellView[],
)
} else {
views = views.concat(graph.renderer.findEdgeViewsInArea(rect, options))
}
}
return views
}
protected notifyBoxEvent<
K extends keyof Selection.BoxEventArgs,
T extends JQuery.TriggeredEvent,
>(name: K, e: T, x: number, y: number) {
const data = this.getEventData<EventData.SelectionBox>(e)
const view = data.activeView
this.trigger(name, { e, view, x, y, cell: view.cell })
}
protected getSelectedClassName(cell: Cell) {
return this.prefixClassName(`${cell.isNode() ? 'node' : 'edge'}-selected`)
}
protected addCellSelectedClassName(cell: Cell) {
const view = this.graph.renderer.findViewByCell(cell)
if (view) {
view.addClass(this.getSelectedClassName(cell))
}
}
protected removeCellUnSelectedClassName(cell: Cell) {
const view = this.graph.renderer.findViewByCell(cell)
if (view) {
view.removeClass(this.getSelectedClassName(cell))
}
}
protected destroySelectionBox(cell: Cell) {
this.removeCellUnSelectedClassName(cell)
if (this.canShowSelectionBox(cell)) {
this.$container.find(`[data-cell-id="${cell.id}"]`).remove()
if (this.$boxes.length === 0) {
this.hide()
}
this.boxCount = Math.max(0, this.boxCount - 1)
}
}
protected destroyAllSelectionBoxes(cells: Cell[]) {
cells.forEach((cell) => this.removeCellUnSelectedClassName(cell))
this.hide()
this.$boxes.remove()
this.boxCount = 0
}
hide() {
this.$container
.removeClass(this.prefixClassName(Private.classNames.rubberband))
.removeClass(this.prefixClassName(Private.classNames.selected))
}
protected showRubberband() {
this.$container.addClass(
this.prefixClassName(Private.classNames.rubberband),
)
}
protected hideRubberband() {
this.$container.removeClass(
this.prefixClassName(Private.classNames.rubberband),
)
}
protected showSelected() {
this.$container
.removeAttr('style')
.addClass(this.prefixClassName(Private.classNames.selected))
}
protected createContainer() {
this.container = document.createElement('div')
this.$container = this.$(this.container)
this.$container.addClass(this.prefixClassName(Private.classNames.root))
if (this.options.className) {
this.$container.addClass(this.options.className)
}
this.$selectionContainer = this.$('<div/>').addClass(
this.prefixClassName(Private.classNames.inner),
)
this.$selectionContent = this.$('<div/>').addClass(
this.prefixClassName(Private.classNames.content),
)
this.$selectionContainer.append(this.$selectionContent)
this.$selectionContainer.attr(
'data-selection-length',
this.collection.length,
)
this.$container.prepend(this.$selectionContainer)
this.$handleContainer = this.$selectionContainer
}
protected updateContainerPosition(offset: { dx: number; dy: number }) {
if (offset.dx || offset.dy) {
this.$selectionContainer.css({
left: `+=${offset.dx}`,
top: `+=${offset.dy}`,
})
}
}
protected updateContainer() {
const origin = { x: Infinity, y: Infinity }
const corner = { x: 0, y: 0 }
const cells = this.collection
.toArray()
.filter((cell) => this.canShowSelectionBox(cell))
cells.forEach((cell) => {
const view = this.graph.renderer.findViewByCell(cell)
if (view) {
const bbox = view.getBBox({
useCellGeometry: this.options.useCellGeometry,
})
origin.x = Math.min(origin.x, bbox.x)
origin.y = Math.min(origin.y, bbox.y)
corner.x = Math.max(corner.x, bbox.x + bbox.width)
corner.y = Math.max(corner.y, bbox.y + bbox.height)
}
})
this.$selectionContainer
.css({
position: 'absolute',
pointerEvents: 'none',
left: origin.x,
top: origin.y,
width: corner.x - origin.x,
height: corner.y - origin.y,
})
.attr('data-selection-length', this.collection.length)
const boxContent = this.options.content
if (boxContent) {
if (typeof boxContent === 'function') {
const content = FunctionExt.call(
boxContent,
this.graph,
this,
this.$selectionContent[0],
)
if (content) {
this.$selectionContent.html(content)
}
} else {
this.$selectionContent.html(boxContent)
}
}
if (this.collection.length > 0 && !this.container.parentNode) {
this.$container.appendTo(this.graph.container)
} else if (this.collection.length <= 0 && this.container.parentNode) {
this.container.parentNode.removeChild(this.container)
}
}
protected canShowSelectionBox(cell: Cell) {
return (
(cell.isNode() && this.options.showNodeSelectionBox === true) ||
(cell.isEdge() && this.options.showEdgeSelectionBox === true)
)
}
protected createSelectionBox(cell: Cell) {
this.addCellSelectedClassName(cell)
if (this.canShowSelectionBox(cell)) {
const view = this.graph.renderer.findViewByCell(cell)
if (view) {
const bbox = view.getBBox({
useCellGeometry: this.options.useCellGeometry,
})
const className = this.boxClassName
this.$('<div/>')
.addClass(className)
.addClass(`${className}-${cell.isNode() ? 'node' : 'edge'}`)
.attr('data-cell-id', cell.id)
.css({
position: 'absolute',
left: bbox.x,
top: bbox.y,
width: bbox.width,
height: bbox.height,
pointerEvents: this.options.pointerEvents || 'auto',
})
.appendTo(this.container)
this.showSelected()
this.boxCount += 1
}
}
}
protected updateSelectionBoxes(
options: Renderer.RequestViewUpdateOptions = {},
) {
if (this.collection.length > 0) {
this.boxesUpdated = true
this.graph.renderer.requestViewUpdate(this as any, 1, 2, options)
}
}
confirmUpdate() {
if (this.boxCount) {
this.hide()
this.$boxes.each((_, elem) => {
const cellId = this.$(elem).remove().attr('data-cell-id')
const cell = this.collection.get(cellId)
if (cell) {
this.createSelectionBox(cell)
}
})
this.updateContainer()
}
return 0
}
protected getCellViewFromElem(elem: Element) {
const id = elem.getAttribute('data-cell-id')
if (id) {
const cell = this.collection.get(id)
if (cell) {
return this.graph.renderer.findViewByCell(cell)
}
}
return null
}
protected onCellRemoved({ cell }: Collection.EventArgs['removed']) {
this.destroySelectionBox(cell)
this.updateContainer()
}
protected onReseted({ previous, current }: Collection.EventArgs['reseted']) {
this.destroyAllSelectionBoxes(previous)
current.forEach((cell) => {
this.listenCellRemoveEvent(cell)
this.createSelectionBox(cell)
})
this.updateContainer()
}
protected onCellAdded({ cell }: Collection.EventArgs['added']) {
// The collection do not known the cell was removed when cell was
// removed by interaction(such as, by "delete" shortcut), so we should
// manually listen to cell's remove evnet.
this.listenCellRemoveEvent(cell)
this.createSelectionBox(cell)
this.updateContainer()
}
protected listenCellRemoveEvent(cell: Cell) {
cell.off('removed', this.onCellRemoved, this)
cell.on('removed', this.onCellRemoved, this)
}
protected onCollectionUpdated({
added,
removed,
options,
}: Collection.EventArgs['updated']) {
added.forEach((cell) => {
this.trigger('cell:selected', { cell, options })
this.graph.trigger('cell:selected', { cell, options })
if (cell.isNode()) {
this.trigger('node:selected', { cell, options, node: cell })
this.graph.trigger('node:selected', { cell, options, node: cell })
} else if (cell.isEdge()) {
this.trigger('edge:selected', { cell, options, edge: cell })
this.graph.trigger('edge:selected', { cell, options, edge: cell })
}
})
removed.forEach((cell) => {
this.trigger('cell:unselected', { cell, options })
this.graph.trigger('cell:unselected', { cell, options })
if (cell.isNode()) {
this.trigger('node:unselected', { cell, options, node: cell })
this.graph.trigger('node:unselected', { cell, options, node: cell })
} else if (cell.isEdge()) {
this.trigger('edge:unselected', { cell, options, edge: cell })
this.graph.trigger('edge:unselected', { cell, options, edge: cell })
}
})
const args = {
added,
removed,
options,
selected: this.cells,
}
this.trigger('selection:changed', args)
this.graph.trigger('selection:changed', args)
}
// #region handle
protected deleteSelectedCells() {
const cells = this.collection.toArray()
this.clean()
this.graph.model.removeCells(cells, { selection: this.cid })
}
protected startRotate({ e }: Handle.EventArgs) {
const cells = this.collection.toArray()
const center = Cell.getCellsBBox(cells)!.getCenter()
const client = this.graph.snapToGrid(e.clientX!, e.clientY!)
const angles = cells.reduce<{ [id: string]: number }>(
(memo, cell: Node) => {
memo[cell.id] = Angle.normalize(cell.getAngle())
return memo
},
{},
)
this.setEventData<EventData.Rotation>(e, {
center,
angles,
start: client.theta(center),
})
}
protected doRotate({ e }: Handle.EventArgs) {
const data = this.getEventData<EventData.Rotation>(e)
const grid = this.graph.options.rotating.grid
const gridSize =
typeof grid === 'function'
? FunctionExt.call(grid, this.graph, null as any)
: grid
const client = this.graph.snapToGrid(e.clientX!, e.clientY!)
const delta = data.start - client.theta(data.center)
if (!data.rotated) {
data.rotated = true
}
if (Math.abs(delta) > 0.001) {
this.collection.toArray().forEach((node: Node) => {
const angle = Util.snapToGrid(
data.angles[node.id] + delta,
gridSize || 15,
)
node.rotate(angle, {
absolute: true,
center: data.center,
selection: this.cid,
})
})
this.updateSelectionBoxes()
}
}
protected stopRotate({ e }: Handle.EventArgs) {
const data = this.getEventData<EventData.Rotation>(e)
if (data.rotated) {
data.rotated = false
this.collection.toArray().forEach((node: Node) => {
notify(
'node:rotated',
e as JQuery.MouseUpEvent,
this.graph.findViewByCell(node) as NodeView,
)
})
}
}
protected startResize({ e }: Handle.EventArgs) {
const gridSize = this.graph.getGridSize()
const cells = this.collection.toArray()
const bbox = Cell.getCellsBBox(cells)!
const bboxes = cells.map((cell) => cell.getBBox())
const maxWidth = bboxes.reduce((maxWidth, bbox) => {
return bbox.width < maxWidth ? bbox.width : maxWidth
}, Infinity)
const maxHeight = bboxes.reduce((maxHeight, bbox) => {
return bbox.height < maxHeight ? bbox.height : maxHeight
}, Infinity)
this.setEventData<EventData.Resizing>(e, {
bbox,
cells: this.graph.model.getSubGraph(cells),
minWidth: (gridSize * bbox.width) / maxWidth,
minHeight: (gridSize * bbox.height) / maxHeight,
})
}
protected doResize({ e, dx, dy }: Handle.EventArgs) {
const data = this.eventData<EventData.Resizing>(e)
const bbox = data.bbox
const width = bbox.width
const height = bbox.height
const newWidth = Math.max(width + dx, data.minWidth)
const newHeight = Math.max(height + dy, data.minHeight)
if (!data.resized) {
data.resized = true
}
if (
Math.abs(width - newWidth) > 0.001 ||
Math.abs(height - newHeight) > 0.001
) {
this.graph.model.resizeCells(newWidth, newHeight, data.cells, {
selection: this.cid,
})
bbox.width = newWidth
bbox.height = newHeight
this.updateSelectionBoxes()
}
}
protected stopResize({ e }: Handle.EventArgs) {
const data = this.eventData<EventData.Resizing>(e)
if (data.resized) {
data.resized = false
this.collection.toArray().forEach((node: Node) => {
notify(
'node:resized',
e as JQuery.MouseUpEvent,
this.graph.findViewByCell(node) as NodeView,
)
})
}
}
// #endregion
@View.dispose()
dispose() {
this.clean()
this.remove()
}
}
export namespace Selection {
export interface CommonOptions extends Handle.Options {
model?: Model
collection?: Collection
className?: string
strict?: boolean
filter?: Filter
showEdgeSelectionBox?: boolean
showNodeSelectionBox?: boolean
movable?: boolean
following?: boolean
useCellGeometry?: boolean
content?: Content
// Can select node or edge when rubberband
rubberNode?: boolean
rubberEdge?: boolean
// Whether to respond event on the selectionBox
pointerEvents?: 'none' | 'auto'
}
export interface Options extends CommonOptions {
graph: Graph
}
export type Content =
| null
| false
| string
| ((
this: Graph,
selection: Selection,
contentElement: HTMLElement,
) => string)
export type Filter =
| null
| (string | { id: string })[]
| ((this: Graph, cell: Cell) => boolean)
export interface SetOptions extends Collection.SetOptions {
batch?: boolean
}
export interface AddOptions extends Collection.AddOptions {}
export interface RemoveOptions extends Collection.RemoveOptions {}
}
export namespace Selection {
interface SelectionBoxEventArgs<T> {
e: T
view: CellView
cell: Cell
x: number
y: number
}
export interface BoxEventArgs {
'box:mousedown': SelectionBoxEventArgs<JQuery.MouseDownEvent>
'box:mousemove': SelectionBoxEventArgs<JQuery.MouseMoveEvent>
'box:mouseup': SelectionBoxEventArgs<JQuery.MouseUpEvent>
}
export interface SelectionEventArgs {
'cell:selected': { cell: Cell; options: Model.SetOptions }
'node:selected': { cell: Cell; node: Node; options: Model.SetOptions }
'edge:selected': { cell: Cell; edge: Edge; options: Model.SetOptions }
'cell:unselected': { cell: Cell; options: Model.SetOptions }
'node:unselected': { cell: Cell; node: Node; options: Model.SetOptions }
'edge:unselected': { cell: Cell; edge: Edge; options: Model.SetOptions }
'selection:changed': {
added: Cell[]
removed: Cell[]
selected: Cell[]
options: Model.SetOptions
}
}
export interface EventArgs extends BoxEventArgs, SelectionEventArgs {}
}
export interface Selection extends Handle {}
ObjectExt.applyMixins(Selection, Handle)
// private
// -------
namespace Private {
const base = 'widget-selection'
export const classNames = {
root: base,
inner: `${base}-inner`,
box: `${base}-box`,
content: `${base}-content`,
rubberband: `${base}-rubberband`,
selected: `${base}-selected`,
}
export const documentEvents = {
mousemove: 'adjustSelection',
touchmove: 'adjustSelection',
mouseup: 'onMouseUp',
touchend: 'onMouseUp',
touchcancel: 'onMouseUp',
}
export const defaultOptions: Partial<Selection.Options> = {
movable: true,
following: true,
strict: false,
useCellGeometry: false,
content(selection) {
return StringExt.template(
'<%= length %> node<%= length > 1 ? "s":"" %> selected.',
)({ length: selection.length })
},
handles: [
{
name: 'remove',
position: 'nw',
events: {
mousedown: 'deleteSelectedCells',
},
},
{
name: 'rotate',
position: 'sw',
events: {
mousedown: 'startRotate',
mousemove: 'doRotate',
mouseup: 'stopRotate',
},
},
{
name: 'resize',
position: 'se',
events: {
mousedown: 'startResize',
mousemove: 'doResize',
mouseup: 'stopResize',
},
},
],
}
export function depthComparator(cell: Cell) {
return cell.getAncestors().length
}
}
namespace EventData {
export interface Common {
action: 'selecting' | 'translating'
}
export interface Selecting extends Common {
action: 'selecting'
moving?: boolean
clientX: number
clientY: number
offsetX: number
offsetY: number
scrollerX: number
scrollerY: number
}
export interface Translating extends Common {
action: 'translating'
clientX: number
clientY: number
originX: number
originY: number
}
export interface SelectionBox {
activeView: CellView
}
export interface Rotation {
rotated?: boolean
center: Point.PointLike
start: number
angles: { [id: string]: number }
}
export interface Resizing {
resized?: boolean
bbox: Rectangle
cells: Cell[]
minWidth: number
minHeight: number
}
} | the_stack |
import assert from 'assert';
import * as fs from 'fs';
import {InferenceSession, Tensor, TypedTensor} from 'onnxruntime-common';
import * as path from 'path';
import {assertTensorEqual} from '../../test-utils';
const SQUEEZENET_INPUT0_DATA = require(path.join(__dirname, '../../testdata/squeezenet.input0.json'));
const SQUEEZENET_OUTPUT0_DATA = require(path.join(__dirname, '../../testdata/squeezenet.output0.json'));
describe('UnitTests - InferenceSession.create()', () => {
const modelPath = path.join(__dirname, '../../testdata/squeezenet.onnx');
const modelBuffer = fs.readFileSync(modelPath);
const createAny: any = InferenceSession.create;
// #region test bad arguments
it('BAD CALL - no argument', async () => {
await assert.rejects(async () => {
await createAny();
}, {name: 'TypeError', message: /argument\[0\]/});
});
it('BAD CALL - byteOffset negative number (ArrayBuffer, number)', async () => {
await assert.rejects(async () => {
await createAny(modelBuffer.buffer, -1);
}, {name: 'RangeError', message: /'byteOffset'/});
});
it('BAD CALL - byteOffset out of range (ArrayBuffer, number)', async () => {
await assert.rejects(async () => {
await createAny(modelBuffer.buffer, 100000000);
}, {name: 'RangeError', message: /'byteOffset'/});
});
it('BAD CALL - byteLength negative number (ArrayBuffer, number)', async () => {
await assert.rejects(async () => {
await createAny(modelBuffer.buffer, 0, -1);
}, {name: 'RangeError', message: /'byteLength'/});
});
it('BAD CALL - byteLength out of range (ArrayBuffer, number)', async () => {
await assert.rejects(async () => {
await createAny(modelBuffer.buffer, 0, 100000000);
}, {name: 'RangeError', message: /'byteLength'/});
});
it('BAD CALL - options type mismatch (string, string)', async () => {
await assert.rejects(async () => {
await createAny(modelPath, 'cpu');
}, {name: 'TypeError', message: /'options'/});
});
it('BAD CALL - options type mismatch (Uint8Array, string)', async () => {
await assert.rejects(async () => {
await createAny(modelBuffer, 'cpu');
}, {name: 'TypeError', message: /'options'/});
});
it('BAD CALL - options type mismatch (ArrayBuffer, number, number, string)', async () => {
await assert.rejects(async () => {
await createAny(modelBuffer.buffer, modelBuffer.byteOffset, modelBuffer.byteLength, 'cpu');
}, {name: 'TypeError', message: /'options'/});
});
it('EXPECTED FAILURE - Load model failed', async () => {
await assert.rejects(async () => {
await InferenceSession.create('/this/is/an/invalid/path.onnx');
}, {name: 'Error', message: /failed/});
});
it('EXPECTED FAILURE - empty buffer', async () => {
await assert.rejects(async () => {
await InferenceSession.create(new Uint8Array(0));
}, {name: 'Error', message: /No graph was found in the protobuf/});
});
// #endregion
it('metadata: inputNames', async () => {
const session = await InferenceSession.create(modelPath);
assert.deepStrictEqual(session.inputNames, ['data_0']);
});
it('metadata: outputNames', async () => {
const session = await InferenceSession.create(modelPath);
assert.deepStrictEqual(session.outputNames, ['softmaxout_1']);
});
});
describe('UnitTests - InferenceSession.run()', () => {
let session: InferenceSession|null = null;
let sessionAny: any;
const input0 = new Tensor('float32', SQUEEZENET_INPUT0_DATA, [1, 3, 224, 224]);
const expectedOutput0 = new Tensor('float32', SQUEEZENET_OUTPUT0_DATA, [1, 1000, 1, 1]);
before(async () => {
session = await InferenceSession.create(path.join(__dirname, '../../testdata/squeezenet.onnx'));
sessionAny = session;
});
// #region test bad input(feeds)
it('BAD CALL - input type mismatch (null)', async () => {
await assert.rejects(async () => {
await sessionAny.run(null);
}, {name: 'TypeError', message: /'feeds'/});
});
it('BAD CALL - input type mismatch (single tensor)', async () => {
await assert.rejects(async () => {
await sessionAny.run(input0);
}, {name: 'TypeError', message: /'feeds'/});
});
it('BAD CALL - input type mismatch (tensor array)', async () => {
await assert.rejects(async () => {
await sessionAny.run([input0]);
}, {name: 'TypeError', message: /'feeds'/});
});
it('EXPECTED FAILURE - input name missing', async () => {
await assert.rejects(async () => {
await sessionAny.run({});
}, {name: 'Error', message: /input 'data_0' is missing/});
});
it('EXPECTED FAILURE - input name incorrect', async () => {
await assert.rejects(async () => {
await sessionAny.run({'data_1': input0}); // correct name should be 'data_0'
}, {name: 'Error', message: /input 'data_0' is missing/});
});
// #endregion
// #region test fetches overrides
it('run() - no fetches', async () => {
const result = await session!.run({'data_0': input0});
assertTensorEqual(result.softmaxout_1, expectedOutput0);
});
it('run() - fetches names', async () => {
const result = await session!.run({'data_0': input0}, ['softmaxout_1']);
assertTensorEqual(result.softmaxout_1, expectedOutput0);
});
it('run() - fetches object', async () => {
const result = await session!.run({'data_0': input0}, {'softmaxout_1': null});
assertTensorEqual(result.softmaxout_1, expectedOutput0);
});
// TODO: enable after buffer reuse is implemented
it.skip('run() - fetches object (pre-allocated)', async () => {
const preAllocatedOutputBuffer = new Float32Array(expectedOutput0.size);
const result = await session!.run(
{'data_0': input0}, {'softmaxout_1': new Tensor(preAllocatedOutputBuffer, expectedOutput0.dims)});
const softmaxout_1 = result.softmaxout_1 as TypedTensor<'float32'>;
assert.strictEqual(softmaxout_1.data.buffer, preAllocatedOutputBuffer.buffer);
assert.strictEqual(softmaxout_1.data.byteOffset, preAllocatedOutputBuffer.byteOffset);
assertTensorEqual(result.softmaxout_1, expectedOutput0);
});
// #endregion
// #region test bad output(fetches)
it('BAD CALL - fetches type mismatch (null)', async () => {
await assert.rejects(async () => {
await sessionAny.run({'data_0': input0}, null);
}, {name: 'TypeError', message: /argument\[1\]/});
});
it('BAD CALL - fetches type mismatch (number)', async () => {
await assert.rejects(async () => {
await sessionAny.run({'data_0': input0}, 1);
}, {name: 'TypeError', message: /argument\[1\]/});
});
it('BAD CALL - fetches type mismatch (Tensor)', async () => {
await assert.rejects(async () => {
await sessionAny.run(
{'data_0': input0}, new Tensor(new Float32Array(expectedOutput0.size), expectedOutput0.dims));
}, {name: 'TypeError', message: /'fetches'/});
});
it('BAD CALL - fetches as array (empty array)', async () => {
await assert.rejects(async () => {
await sessionAny.run({'data_0': input0}, []);
}, {name: 'TypeError', message: /'fetches'/});
});
it('BAD CALL - fetches as array (non-string elements)', async () => {
await assert.rejects(async () => {
await sessionAny.run({'data_0': input0}, [1, 2, 3]);
}, {name: 'TypeError', message: /'fetches'/});
});
it('BAD CALL - fetches as array (invalid name)', async () => {
await assert.rejects(async () => {
await sessionAny.run({'data_0': input0}, ['im_a_wrong_output_name']);
}, {name: 'RangeError', message: /'fetches'/});
});
// #endregion
it('BAD CALL - options type mismatch (number)', async () => {
await assert.rejects(async () => {
await sessionAny.run({'data_0': input0}, ['softmaxout_1'], 1);
}, {name: 'TypeError', message: /'options'/});
});
});
describe('UnitTests - InferenceSession.SessionOptions', () => {
const modelPath = path.join(__dirname, '../../testdata/test_types_FLOAT.pb');
const createAny: any = InferenceSession.create;
it('BAD CALL - type mismatch', async () => {
await assert.rejects(async () => {
await createAny(modelPath, 'cpu');
}, {name: 'TypeError', message: /'options'/});
});
describe('executionProviders', () => {
it.skip('BAD CALL - type mismatch', async () => {
await assert.rejects(async () => {
await createAny(modelPath, {executionProviders: 'bad-EP-name'});
}, {name: 'TypeError', message: /executionProviders/});
});
it.skip('EXPECTED FAILURE - invalid EP name, string list', async () => {
await assert.rejects(async () => {
await createAny(modelPath, {executionProviders: ['bad-EP-name']});
}, {name: 'Error', message: /executionProviders.+bad-EP-name/});
});
it.skip('EXPECTED FAILURE - invalid EP name, object list', async () => {
await assert.rejects(async () => {
await createAny(modelPath, {executionProviders: [{name: 'bad-EP-name'}]});
}, {name: 'Error', message: /executionProviders.+bad-EP-name/});
});
it('string list (CPU)', async () => {
await InferenceSession.create(modelPath, {executionProviders: ['cpu']});
});
it('object list (CPU)', async () => {
await InferenceSession.create(modelPath, {executionProviders: [{name: 'cpu'}]});
});
});
describe('intraOpNumThreads', () => {
it('BAD CALL - type mismatch', async () => {
await assert.rejects(async () => {
await createAny(modelPath, {intraOpNumThreads: 'bad-value'});
}, {name: 'TypeError', message: /intraOpNumThreads/});
});
it('BAD CALL - non-integer', async () => {
await assert.rejects(async () => {
await createAny(modelPath, {intraOpNumThreads: 1.5});
}, {name: 'RangeError', message: /intraOpNumThreads/});
});
it('BAD CALL - negative integer', async () => {
await assert.rejects(async () => {
await createAny(modelPath, {intraOpNumThreads: -1});
}, {name: 'RangeError', message: /intraOpNumThreads/});
});
it('intraOpNumThreads = 1', async () => {
await InferenceSession.create(modelPath, {intraOpNumThreads: 1});
});
});
describe('interOpNumThreads', () => {
it('BAD CALL - type mismatch', async () => {
await assert.rejects(async () => {
await createAny(modelPath, {interOpNumThreads: 'bad-value'});
}, {name: 'TypeError', message: /interOpNumThreads/});
});
it('BAD CALL - non-integer', async () => {
await assert.rejects(async () => {
await createAny(modelPath, {interOpNumThreads: 1.5});
}, {name: 'RangeError', message: /interOpNumThreads/});
});
it('BAD CALL - negative integer', async () => {
await assert.rejects(async () => {
await createAny(modelPath, {interOpNumThreads: -1});
}, {name: 'RangeError', message: /interOpNumThreads/});
});
it('interOpNumThreads = 1', async () => {
await InferenceSession.create(modelPath, {interOpNumThreads: 1});
});
});
describe('graphOptimizationLevel', () => {
it('BAD CALL - type mismatch', async () => {
await assert.rejects(async () => {
await createAny(modelPath, {graphOptimizationLevel: 0});
}, {name: 'TypeError', message: /graphOptimizationLevel/});
});
it('BAD CALL - invalid config', async () => {
await assert.rejects(async () => {
await createAny(modelPath, {graphOptimizationLevel: 'bad-value'});
}, {name: 'TypeError', message: /graphOptimizationLevel/});
});
it('graphOptimizationLevel = basic', async () => {
await InferenceSession.create(modelPath, {graphOptimizationLevel: 'basic'});
});
});
describe('enableCpuMemArena', () => {
it('BAD CALL - type mismatch', async () => {
await assert.rejects(async () => {
await createAny(modelPath, {enableCpuMemArena: 0});
}, {name: 'TypeError', message: /enableCpuMemArena/});
});
it('enableCpuMemArena = true', async () => {
await InferenceSession.create(modelPath, {enableCpuMemArena: true});
});
});
describe('enableMemPattern', () => {
it('BAD CALL - type mismatch', async () => {
await assert.rejects(async () => {
await createAny(modelPath, {enableMemPattern: 0});
}, {name: 'TypeError', message: /enableMemPattern/});
});
it('enableMemPattern = true', async () => {
await InferenceSession.create(modelPath, {enableMemPattern: true});
});
});
describe('executionMode', () => {
it('BAD CALL - type mismatch', async () => {
await assert.rejects(async () => {
await createAny(modelPath, {executionMode: 0});
}, {name: 'TypeError', message: /executionMode/});
});
it('BAD CALL - invalid config', async () => {
await assert.rejects(async () => {
await createAny(modelPath, {executionMode: 'bad-value'});
}, {name: 'TypeError', message: /executionMode/});
});
it('executionMode = sequential', async () => {
await InferenceSession.create(modelPath, {executionMode: 'sequential'});
});
});
});
describe('UnitTests - InferenceSession.RunOptions', () => {
let session: InferenceSession|null = null;
let sessionAny: any;
const input0 = new Tensor('float32', [1, 2, 3, 4, 5], [1, 5]);
const expectedOutput0 = new Tensor('float32', [1, 2, 3, 4, 5], [1, 5]);
before(async () => {
const modelPath = path.join(__dirname, '../../testdata/test_types_FLOAT.pb');
session = await InferenceSession.create(modelPath);
sessionAny = session;
});
describe('logSeverityLevel', () => {
it('BAD CALL - type mismatch', async () => {
await assert.rejects(async () => {
await sessionAny.run({input: input0}, {logSeverityLevel: 'error'});
}, {name: 'TypeError', message: /logSeverityLevel/});
});
it('BAD CALL - out of range', async () => {
await assert.rejects(async () => {
await sessionAny.run({input: input0}, {logSeverityLevel: 8});
}, {name: 'RangeError', message: /logSeverityLevel/});
});
it('BAD CALL - out of range', async () => {
await assert.rejects(async () => {
await sessionAny.run({input: input0}, {logSeverityLevel: 8});
}, {name: 'RangeError', message: /logSeverityLevel/});
});
it('logSeverityLevel = 4', async () => {
const result = await sessionAny.run({input: input0}, {logSeverityLevel: 4});
assertTensorEqual(result.output, expectedOutput0);
});
});
}); | the_stack |
import {ComponentPortal, PortalModule} from '@angular/cdk/portal';
import {CdkScrollable, ScrollingModule} from '@angular/cdk/scrolling';
import {MockNgZone} from '@angular/cdk/testing';
import {Component, ElementRef, NgModule, NgZone} from '@angular/core';
import {inject, TestBed} from '@angular/core/testing';
import {Subscription} from 'rxjs';
import {
ConnectedOverlayPositionChange,
ConnectedPositionStrategy,
ConnectionPositionPair,
Overlay,
OverlayContainer,
OverlayModule,
OverlayRef,
} from '../index';
// Default width and height of the overlay and origin panels throughout these tests.
const DEFAULT_HEIGHT = 30;
const DEFAULT_WIDTH = 60;
// For all tests, we assume the browser window is 1024x786 (outerWidth x outerHeight).
// The karma config has been set to this for local tests, and it is the default size
// for tests on CI (both SauceLabs and Browserstack).
describe('ConnectedPositionStrategy', () => {
let overlay: Overlay;
let overlayContainer: OverlayContainer;
let zone: MockNgZone;
let overlayRef: OverlayRef;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ScrollingModule, OverlayModule, OverlayTestModule],
providers: [{provide: NgZone, useFactory: () => zone = new MockNgZone()}]
});
inject([Overlay, OverlayContainer], (o: Overlay, oc: OverlayContainer) => {
overlay = o;
overlayContainer = oc;
})();
});
afterEach(() => {
overlayContainer.ngOnDestroy();
if (overlayRef) {
overlayRef.dispose();
}
});
function attachOverlay(positionStrategy: ConnectedPositionStrategy) {
overlayRef = overlay.create({positionStrategy});
overlayRef.attach(new ComponentPortal(TestOverlay));
zone.simulateZoneExit();
}
describe('with origin on document body', () => {
const ORIGIN_HEIGHT = DEFAULT_HEIGHT;
const ORIGIN_WIDTH = DEFAULT_WIDTH;
const OVERLAY_HEIGHT = DEFAULT_HEIGHT;
const OVERLAY_WIDTH = DEFAULT_WIDTH;
let originElement: HTMLElement;
let positionStrategy: ConnectedPositionStrategy;
let fakeElementRef: ElementRef<HTMLElement>;
let originRect: ClientRect | null;
let originCenterX: number | null;
let originCenterY: number | null;
beforeEach(() => {
// The origin and overlay elements need to be in the document body in order to have geometry.
originElement = createPositionedBlockElement();
document.body.appendChild(originElement);
fakeElementRef = new ElementRef<HTMLElement>(originElement);
});
afterEach(() => {
document.body.removeChild(originElement);
// Reset the origin geometry after each test so we don't accidently keep state between tests.
originRect = null;
originCenterX = null;
originCenterY = null;
});
describe('when not near viewport edge, not scrolled', () => {
// Place the original element close to the center of the window.
// (1024 / 2, 768 / 2). It's not exact, since outerWidth/Height includes browser
// chrome, but it doesn't really matter for these tests.
const ORIGIN_LEFT = 500;
const ORIGIN_TOP = 350;
beforeEach(() => {
originElement.style.left = `${ORIGIN_LEFT}px`;
originElement.style.top = `${ORIGIN_TOP}px`;
originRect = originElement.getBoundingClientRect();
originCenterX = originRect.left + (ORIGIN_WIDTH / 2);
originCenterY = originRect.top + (ORIGIN_HEIGHT / 2);
});
// Preconditions are set, now just run the full set of simple position tests.
runSimplePositionTests();
});
describe('when scrolled', () => {
// Place the original element decently far outside the unscrolled document (1024x768).
const ORIGIN_LEFT = 2500;
const ORIGIN_TOP = 2500;
// Create a very large element that will make the page scrollable.
let veryLargeElement: HTMLElement = document.createElement('div');
veryLargeElement.style.width = '4000px';
veryLargeElement.style.height = '4000px';
beforeEach(() => {
// Scroll the page such that the origin element is roughly in the
// center of the visible viewport (2500 - 1024/2, 2500 - 768/2).
document.body.appendChild(veryLargeElement);
document.body.scrollTop = 2100;
document.body.scrollLeft = 2100;
originElement.style.top = `${ORIGIN_TOP}px`;
originElement.style.left = `${ORIGIN_LEFT}px`;
originRect = originElement.getBoundingClientRect();
originCenterX = originRect.left + (ORIGIN_WIDTH / 2);
originCenterY = originRect.top + (ORIGIN_HEIGHT / 2);
});
afterEach(() => {
document.body.removeChild(veryLargeElement);
document.body.scrollTop = 0;
document.body.scrollLeft = 0;
});
// Preconditions are set, now just run the full set of simple position tests.
runSimplePositionTests();
});
describe('when near viewport edge', () => {
it('should reposition the overlay if it would go off the top of the screen', () => {
// We can use the real ViewportRuler in this test since we know that zero is
// always the top of the viewport.
originElement.style.top = '5px';
originElement.style.left = '200px';
originRect = originElement.getBoundingClientRect();
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'end', originY: 'top'},
{overlayX: 'end', overlayY: 'bottom'})
.withFallbackPosition(
{originX: 'start', originY: 'bottom'},
{overlayX: 'start', overlayY: 'top'});
attachOverlay(positionStrategy);
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.top)).toBe(Math.floor(originRect.bottom));
expect(Math.floor(overlayRect.left)).toBe(Math.floor(originRect.left));
});
it('should reposition the overlay if it would go off the left of the screen', () => {
// We can use the real ViewportRuler in this test since we know that zero is
// always the left edge of the viewport.
originElement.style.top = '200px';
originElement.style.left = '5px';
originRect = originElement.getBoundingClientRect();
originCenterY = originRect.top + (ORIGIN_HEIGHT / 2);
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'start', originY: 'bottom'},
{overlayX: 'end', overlayY: 'top'})
.withFallbackPosition(
{originX: 'end', originY: 'center'},
{overlayX: 'start', overlayY: 'center'});
attachOverlay(positionStrategy);
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.top)).toBe(Math.floor(originCenterY - (OVERLAY_HEIGHT / 2)));
expect(Math.floor(overlayRect.left)).toBe(Math.floor(originRect.right));
});
it('should reposition the overlay if it would go off the bottom of the screen', () => {
originElement.style.bottom = '25px';
originElement.style.left = '200px';
originRect = originElement.getBoundingClientRect();
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'start', originY: 'bottom'},
{overlayX: 'start', overlayY: 'top'})
.withFallbackPosition(
{originX: 'end', originY: 'top'},
{overlayX: 'end', overlayY: 'bottom'});
attachOverlay(positionStrategy);
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.bottom)).toBe(Math.floor(originRect.top));
expect(Math.floor(overlayRect.right)).toBe(Math.floor(originRect.right));
});
it('should reposition the overlay if it would go off the right of the screen', () => {
originElement.style.top = '200px';
originElement.style.right = '25px';
originRect = originElement.getBoundingClientRect();
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'end', originY: 'center'},
{overlayX: 'start', overlayY: 'center'})
.withFallbackPosition(
{originX: 'start', originY: 'bottom'},
{overlayX: 'end', overlayY: 'top'});
attachOverlay(positionStrategy);
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.top)).toBe(Math.floor(originRect.bottom));
expect(Math.floor(overlayRect.right)).toBe(Math.floor(originRect.left));
});
it('should recalculate and set the last position with recalculateLastPosition()', () => {
// Push the trigger down so the overlay doesn't have room to open on the bottom.
originElement.style.bottom = '25px';
originRect = originElement.getBoundingClientRect();
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'start', originY: 'bottom'},
{overlayX: 'start', overlayY: 'top'})
.withFallbackPosition(
{originX: 'start', originY: 'top'},
{overlayX: 'start', overlayY: 'bottom'});
// This should apply the fallback position, as the original position won't fit.
attachOverlay(positionStrategy);
// Now make the overlay small enough to fit in the first preferred position.
overlayRef.overlayElement.style.height = '15px';
// This should only re-align in the last position, even though the first would fit.
positionStrategy.recalculateLastPosition();
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.bottom)).toBe(Math.floor(originRect.top),
'Expected overlay to be re-aligned to the trigger in the previous position.');
});
it('should default to the initial position, if no positions fit in the viewport', () => {
// Make the origin element taller than the viewport.
originElement.style.height = '1000px';
originElement.style.top = '0';
originRect = originElement.getBoundingClientRect();
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'start', originY: 'top'},
{overlayX: 'start', overlayY: 'bottom'});
attachOverlay(positionStrategy);
positionStrategy.recalculateLastPosition();
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.bottom)).toBe(Math.floor(originRect.top),
'Expected overlay to be re-aligned to the trigger in the initial position.');
});
it('should position a panel properly when rtl', () => {
// must make the overlay longer than the origin to properly test attachment
originRect = originElement.getBoundingClientRect();
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'start', originY: 'bottom'},
{overlayX: 'start', overlayY: 'top'})
.withDirection('rtl');
attachOverlay(positionStrategy);
overlayRef.overlayElement.style.width = `500px`;
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.top)).toBe(Math.floor(originRect.bottom));
expect(Math.floor(overlayRect.right)).toBe(Math.floor(originRect.right));
});
it('should position a panel with the x offset provided', () => {
originRect = originElement.getBoundingClientRect();
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'start', originY: 'top'},
{overlayX: 'start', overlayY: 'top'});
positionStrategy.withOffsetX(10);
attachOverlay(positionStrategy);
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.top)).toBe(Math.floor(originRect.top));
expect(Math.floor(overlayRect.left)).toBe(Math.floor(originRect.left + 10));
});
it('should position a panel with the y offset provided', () => {
originRect = originElement.getBoundingClientRect();
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'start', originY: 'top'},
{overlayX: 'start', overlayY: 'top'});
positionStrategy.withOffsetY(50);
attachOverlay(positionStrategy);
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.top)).toBe(Math.floor(originRect.top + 50));
expect(Math.floor(overlayRect.left)).toBe(Math.floor(originRect.left));
});
it('should allow for the fallback positions to specify their own offsets', () => {
originElement.style.bottom = '0';
originElement.style.left = '50%';
originElement.style.position = 'fixed';
originRect = originElement.getBoundingClientRect();
positionStrategy = overlay.position()
.connectedTo(
fakeElementRef,
{originX: 'start', originY: 'top'},
{overlayX: 'start', overlayY: 'top'})
.withFallbackPosition(
{originX: 'start', originY: 'top'},
{overlayX: 'start', overlayY: 'bottom'},
-100, -100);
positionStrategy.withOffsetY(50).withOffsetY(50);
attachOverlay(positionStrategy);
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.bottom)).toBe(Math.floor(originRect.top - 100));
expect(Math.floor(overlayRect.left)).toBe(Math.floor(originRect.left - 100));
});
});
it('should emit onPositionChange event when position changes', () => {
originElement.style.top = '200px';
originElement.style.right = '25px';
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'end', originY: 'center'},
{overlayX: 'start', overlayY: 'center'})
.withFallbackPosition(
{originX: 'start', originY: 'bottom'},
{overlayX: 'end', overlayY: 'top'});
const positionChangeHandler = jasmine.createSpy('positionChangeHandler');
const subscription = positionStrategy.onPositionChange.subscribe(positionChangeHandler);
attachOverlay(positionStrategy);
const latestCall = positionChangeHandler.calls.mostRecent();
expect(positionChangeHandler).toHaveBeenCalled();
expect(latestCall.args[0] instanceof ConnectedOverlayPositionChange)
.toBe(true, `Expected strategy to emit an instance of ConnectedOverlayPositionChange.`);
// If the strategy is re-applied and the initial position would now fit,
// the position change event should be emitted again.
originElement.style.top = '200px';
originElement.style.left = '200px';
positionStrategy.apply();
expect(positionChangeHandler).toHaveBeenCalledTimes(2);
subscription.unsubscribe();
});
it('should emit the onPositionChange event even if none of the positions fit', () => {
originElement.style.bottom = '25px';
originElement.style.right = '25px';
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'end', originY: 'bottom'},
{overlayX: 'start', overlayY: 'top'})
.withFallbackPosition(
{originX: 'start', originY: 'bottom'},
{overlayX: 'end', overlayY: 'top'});
const positionChangeHandler = jasmine.createSpy('positionChangeHandler');
const subscription = positionStrategy.onPositionChange.subscribe(positionChangeHandler);
attachOverlay(positionStrategy);
expect(positionChangeHandler).toHaveBeenCalled();
subscription.unsubscribe();
});
it('should complete the onPositionChange stream on dispose', () => {
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'end', originY: 'bottom'},
{overlayX: 'start', overlayY: 'top'});
const completeHandler = jasmine.createSpy('complete handler');
positionStrategy.onPositionChange.subscribe(undefined, undefined, completeHandler);
attachOverlay(positionStrategy);
positionStrategy.dispose();
expect(completeHandler).toHaveBeenCalled();
});
it('should pick the fallback position that shows the largest area of the element', () => {
originElement.style.top = '200px';
originElement.style.right = '25px';
originRect = originElement.getBoundingClientRect();
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'end', originY: 'center'},
{overlayX: 'start', overlayY: 'center'})
.withFallbackPosition(
{originX: 'end', originY: 'top'},
{overlayX: 'start', overlayY: 'bottom'})
.withFallbackPosition(
{originX: 'end', originY: 'top'},
{overlayX: 'end', overlayY: 'top'});
attachOverlay(positionStrategy);
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.top)).toBe(Math.floor(originRect.top));
expect(Math.floor(overlayRect.left)).toBe(Math.floor(originRect.left));
});
it('should re-use the preferred position when re-applying while locked in', () => {
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'end', originY: 'center'},
{overlayX: 'start', overlayY: 'center'})
.withLockedPosition(true)
.withFallbackPosition(
{originX: 'start', originY: 'bottom'},
{overlayX: 'end', overlayY: 'top'});
const recalcSpy = spyOn(positionStrategy._positionStrategy, 'reapplyLastPosition');
attachOverlay(positionStrategy);
expect(recalcSpy).not.toHaveBeenCalled();
positionStrategy.apply();
expect(recalcSpy).toHaveBeenCalled();
});
/**
* Run all tests for connecting the overlay to the origin such that first preferred
* position does not go off-screen. We do this because there are several cases where we
* want to run the exact same tests with different preconditions (e.g., not scroll, scrolled,
* different element sized, etc.).
*/
function runSimplePositionTests() {
it('should position a panel below, left-aligned', () => {
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'start', originY: 'bottom'},
{overlayX: 'start', overlayY: 'top'});
attachOverlay(positionStrategy);
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.top)).toBe(Math.floor(originRect!.bottom));
expect(Math.floor(overlayRect.left)).toBe(Math.floor(originRect!.left));
});
it('should position to the right, center aligned vertically', () => {
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'end', originY: 'center'},
{overlayX: 'start', overlayY: 'center'});
attachOverlay(positionStrategy);
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.top)).toBe(Math.floor(originCenterY! - (OVERLAY_HEIGHT / 2)));
expect(Math.floor(overlayRect.left)).toBe(Math.floor(originRect!.right));
});
it('should position to the left, below', () => {
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'start', originY: 'bottom'},
{overlayX: 'end', overlayY: 'top'});
attachOverlay(positionStrategy);
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.top)).toBe(Math.floor(originRect!.bottom));
expect(Math.round(overlayRect.right)).toBe(Math.round(originRect!.left));
});
it('should position above, right aligned', () => {
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'end', originY: 'top'},
{overlayX: 'end', overlayY: 'bottom'});
attachOverlay(positionStrategy);
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.round(overlayRect.bottom)).toBe(Math.round(originRect!.top));
expect(Math.round(overlayRect.right)).toBe(Math.round(originRect!.right));
});
it('should position below, centered', () => {
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'center', originY: 'bottom'},
{overlayX: 'center', overlayY: 'top'});
attachOverlay(positionStrategy);
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.top)).toBe(Math.floor(originRect!.bottom));
expect(Math.floor(overlayRect.left)).toBe(Math.floor(originCenterX! - (OVERLAY_WIDTH / 2)));
});
it('should center the overlay on the origin', () => {
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'center', originY: 'center'},
{overlayX: 'center', overlayY: 'center'});
attachOverlay(positionStrategy);
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.top)).toBe(Math.floor(originRect!.top));
expect(Math.floor(overlayRect.left)).toBe(Math.floor(originRect!.left));
});
it('should allow for the positions to be updated after init', () => {
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'start', originY: 'bottom'},
{overlayX: 'start', overlayY: 'top'});
attachOverlay(positionStrategy);
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.top)).toBe(Math.floor(originRect!.bottom));
expect(Math.floor(overlayRect.left)).toBe(Math.floor(originRect!.left));
positionStrategy.withPositions([new ConnectionPositionPair(
{originX: 'start', originY: 'bottom'},
{overlayX: 'end', overlayY: 'top'}
)]);
positionStrategy.apply();
overlayRect = overlayRef.overlayElement.getBoundingClientRect();
expect(Math.floor(overlayRect.top)).toBe(Math.floor(originRect!.bottom));
expect(Math.floor(overlayRect.right)).toBe(Math.floor(originRect!.left));
});
}
});
describe('onPositionChange with scrollable view properties', () => {
let scrollable: HTMLDivElement;
let positionChangeHandler: jasmine.Spy;
let onPositionChangeSubscription: Subscription;
let positionChange: ConnectedOverlayPositionChange;
let fakeElementRef: ElementRef<HTMLElement>;
let positionStrategy: ConnectedPositionStrategy;
beforeEach(() => {
// Set up the origin
let originElement = createBlockElement();
originElement.style.margin = '0 1000px 1000px 0'; // Added so that the container scrolls
// Create a scrollable container and put the origin inside
scrollable = createOverflowContainerElement();
document.body.appendChild(scrollable);
scrollable.appendChild(originElement);
// Create a strategy with knowledge of the scrollable container
fakeElementRef = new ElementRef<HTMLElement>(originElement);
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'start', originY: 'bottom'},
{overlayX: 'start', overlayY: 'top'});
positionStrategy.withScrollableContainers([
new CdkScrollable(new ElementRef<HTMLElement>(scrollable), null!, null!)]);
positionChangeHandler = jasmine.createSpy('positionChangeHandler');
onPositionChangeSubscription =
positionStrategy.onPositionChange.subscribe(positionChangeHandler);
attachOverlay(positionStrategy);
});
afterEach(() => {
onPositionChangeSubscription.unsubscribe();
document.body.removeChild(scrollable);
});
it('should not have origin or overlay clipped or out of view without scroll', () => {
expect(positionChangeHandler).toHaveBeenCalled();
positionChange = positionChangeHandler.calls.mostRecent().args[0];
expect(positionChange.scrollableViewProperties).toEqual({
isOriginClipped: false,
isOriginOutsideView: false,
isOverlayClipped: false,
isOverlayOutsideView: false
});
});
it('should evaluate if origin is clipped if scrolled slightly down', () => {
scrollable.scrollTop = 10; // Clip the origin by 10 pixels
positionStrategy.apply();
expect(positionChangeHandler).toHaveBeenCalled();
positionChange = positionChangeHandler.calls.mostRecent().args[0];
expect(positionChange.scrollableViewProperties).toEqual({
isOriginClipped: true,
isOriginOutsideView: false,
isOverlayClipped: false,
isOverlayOutsideView: false
});
});
it('should evaluate if origin is out of view and overlay is clipped if scrolled enough', () => {
scrollable.scrollTop = 31; // Origin is 30 pixels, move out of view and clip the overlay 1px
positionStrategy.apply();
expect(positionChangeHandler).toHaveBeenCalled();
positionChange = positionChangeHandler.calls.mostRecent().args[0];
expect(positionChange.scrollableViewProperties).toEqual({
isOriginClipped: true,
isOriginOutsideView: true,
isOverlayClipped: true,
isOverlayOutsideView: false
});
});
it('should evaluate the overlay and origin are both out of the view', () => {
scrollable.scrollTop = 61; // Scroll by overlay height + origin height + 1px buffer
positionStrategy.apply();
expect(positionChangeHandler).toHaveBeenCalled();
positionChange = positionChangeHandler.calls.mostRecent().args[0];
expect(positionChange.scrollableViewProperties).toEqual({
isOriginClipped: true,
isOriginOutsideView: true,
isOverlayClipped: true,
isOverlayOutsideView: true
});
});
});
describe('positioning properties', () => {
let originElement: HTMLElement;
let positionStrategy: ConnectedPositionStrategy;
let fakeElementRef: ElementRef<HTMLElement>;
beforeEach(() => {
// The origin and overlay elements need to be in the document body in order to have geometry.
originElement = createPositionedBlockElement();
document.body.appendChild(originElement);
fakeElementRef = new ElementRef<HTMLElement>(originElement);
});
afterEach(() => {
document.body.removeChild(originElement);
});
describe('in ltr', () => {
it('should use `left` when positioning an element at the start', () => {
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'start', originY: 'top'},
{overlayX: 'start', overlayY: 'top'});
attachOverlay(positionStrategy);
expect(overlayRef.overlayElement.style.left).toBeTruthy();
expect(overlayRef.overlayElement.style.right).toBeFalsy();
});
it('should use `right` when positioning an element at the end', () => {
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'end', originY: 'top'},
{overlayX: 'end', overlayY: 'top'});
attachOverlay(positionStrategy);
expect(overlayRef.overlayElement.style.right).toBeTruthy();
expect(overlayRef.overlayElement.style.left).toBeFalsy();
});
});
describe('in rtl', () => {
it('should use `right` when positioning an element at the start', () => {
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'start', originY: 'top'},
{overlayX: 'start', overlayY: 'top'}
)
.withDirection('rtl');
attachOverlay(positionStrategy);
expect(overlayRef.overlayElement.style.right).toBeTruthy();
expect(overlayRef.overlayElement.style.left).toBeFalsy();
});
it('should use `left` when positioning an element at the end', () => {
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'end', originY: 'top'},
{overlayX: 'end', overlayY: 'top'}
).withDirection('rtl');
attachOverlay(positionStrategy);
expect(overlayRef.overlayElement.style.left).toBeTruthy();
expect(overlayRef.overlayElement.style.right).toBeFalsy();
});
});
describe('vertical', () => {
it('should use `top` when positioning at element along the top', () => {
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'start', originY: 'top'},
{overlayX: 'start', overlayY: 'top'}
);
attachOverlay(positionStrategy);
expect(overlayRef.overlayElement.style.top).toBeTruthy();
expect(overlayRef.overlayElement.style.bottom).toBeFalsy();
});
it('should use `bottom` when positioning at element along the bottom', () => {
positionStrategy = overlay.position().connectedTo(
fakeElementRef,
{originX: 'start', originY: 'bottom'},
{overlayX: 'start', overlayY: 'bottom'}
);
attachOverlay(positionStrategy);
expect(overlayRef.overlayElement.style.bottom).toBeTruthy();
expect(overlayRef.overlayElement.style.top).toBeFalsy();
});
});
});
});
/** Creates an absolutely positioned, display: block element with a default size. */
function createPositionedBlockElement() {
let element = createBlockElement();
element.style.position = 'absolute';
return element;
}
/** Creates a block element with a default size. */
function createBlockElement() {
let element = document.createElement('div');
element.style.width = `${DEFAULT_WIDTH}px`;
element.style.height = `${DEFAULT_HEIGHT}px`;
element.style.backgroundColor = 'rebeccapurple';
element.style.zIndex = '100';
return element;
}
/** Creates an overflow container with a set height and width with margin. */
function createOverflowContainerElement() {
let element = document.createElement('div');
element.style.position = 'relative';
element.style.overflow = 'auto';
element.style.height = '300px';
element.style.width = '300px';
element.style.margin = '100px';
return element;
}
@Component({
template: `<div style="width: ${DEFAULT_WIDTH}px; height: ${DEFAULT_HEIGHT}px;"></div>`
})
class TestOverlay { }
@NgModule({
imports: [OverlayModule, PortalModule],
exports: [TestOverlay],
declarations: [TestOverlay],
entryComponents: [TestOverlay],
})
class OverlayTestModule { } | the_stack |
import { MemoryUsage } from "@here/harp-text-canvas";
import { Math2D } from "@here/harp-utils";
import * as THREE from "three";
import { getPixelFromImage, screenToUvCoordinates } from "./PixelPicker";
/**
* Declares an interface for a `struct` containing a [[BoxBuffer]]'s attribute state information.
*/
export interface State {
positionAttributeCount: number;
colorAttributeCount: number;
uvAttributeCount: number;
indexAttributeCount: number;
pickInfoCount: number;
}
/**
* Initial number of boxes in BoxBuffer.
*/
const START_BOX_BUFFER_SIZE = 0;
/**
* Maximum number of boxes in BoxBuffer.
*/
const MAX_BOX_BUFFER_SIZE = 32 * 1024;
/**
* Number of vertices per box/glyph element: 4 corners.
*/
const NUM_VERTICES_PER_ELEMENT = 4;
/**
* Number of indices added per box/glyph: 2 triangles, 6 indices.
*/
const NUM_INDICES_PER_ELEMENT = 6;
/**
* Number of values per position.
*/
const NUM_POSITION_VALUES_PER_VERTEX = 3;
/**
* Number of values per color.
*/
const NUM_COLOR_VALUES_PER_VERTEX = 4;
/**
* Number of values per UV.
*/
const NUM_UV_VALUES_PER_VERTEX = 4;
/**
* Number of values per index.
*/
const NUM_INDEX_VALUES_PER_VERTEX = 1;
/**
* Number of bytes for float in an Float32Array.
*/
const NUM_BYTES_PER_FLOAT = 4;
/**
* Number of bytes for integer number in an UInt32Array.
*/
const NUM_BYTES_PER_INT32 = 4;
/**
* SubClass of [[THREE.Mesh]] to identify meshes that have been created by [[BoxBuffer]] and
* [[TextBuffer]]. Add the isEmpty flag to quickly test for empty meshes.
*/
export class BoxBufferMesh extends THREE.Mesh {
constructor(geometry: THREE.BufferGeometry, material: THREE.Material | THREE.Material[]) {
super(geometry, material);
this.type = "BoxBufferMesh";
}
/**
* A mesh that has no positions and indices set is defined to be empty.
*
* @returns `True` if no indices have been added to the mesh.
*/
get isEmpty(): boolean {
if (this.geometry === undefined) {
return true;
} else {
const bufferGeometry = this.geometry as THREE.BufferGeometry;
return bufferGeometry.index === null || bufferGeometry.index.count === 0;
}
}
}
/**
* Buffer for (untransformed) `Box2` objects. Can be used to create a single geometry for screen-
* aligned boxes, like POIs.
*/
export class BoxBuffer {
/**
* {@link @here/harp-datasource-protocol#BufferAttribute} holding the `BoxBuffer` position data.
*/
private m_positionAttribute?: THREE.BufferAttribute;
/**
* {@link @here/harp-datasource-protocol#BufferAttribute} holding the `BoxBuffer` color data.
*/
private m_colorAttribute?: THREE.BufferAttribute;
/**
* {@link @here/harp-datasource-protocol#BufferAttribute} holding the `BoxBuffer` uv data.
*/
private m_uvAttribute?: THREE.BufferAttribute;
/**
* {@link @here/harp-datasource-protocol#BufferAttribute} holding the `BoxBuffer` index data.
*/
private m_indexAttribute?: THREE.BufferAttribute;
private readonly m_pickInfos: Array<any | undefined>;
/**
* [[BufferGeometry]] holding all the different
* {@link @here/harp-datasource-protocol#BufferAttribute}s.
*/
private m_geometry: THREE.BufferGeometry | undefined;
/**
* [[Mesh]] used for rendering.
*/
private m_mesh: BoxBufferMesh | undefined;
private m_size: number = 0;
/**
* Creates a new `BoxBuffer`.
*
* @param m_material - Material to be used for [[Mesh]] of this `BoxBuffer`.
* @param m_renderOrder - Optional renderOrder of this buffer.
* @param startElementCount - Initial number of elements this `BoxBuffer` can hold.
* @param m_maxElementCount - Maximum number of elements this `BoxBuffer` can hold.
*/
constructor(
private readonly m_material: THREE.Material | THREE.Material[],
private readonly m_renderOrder: number = 0,
startElementCount = START_BOX_BUFFER_SIZE,
private readonly m_maxElementCount = MAX_BOX_BUFFER_SIZE
) {
this.resizeBuffer(startElementCount);
this.m_pickInfos = new Array();
}
/**
* Duplicate this `BoxBuffer` with same material and renderOrder.
*
* @returns A clone of this `BoxBuffer`.
*/
clone(): BoxBuffer {
return new BoxBuffer(this.m_material, this.m_renderOrder);
}
/**
* Dispose of the geometry.
*/
dispose() {
if (this.m_geometry !== undefined) {
this.m_geometry.dispose();
this.m_geometry = undefined;
}
this.m_mesh = undefined;
}
/**
* Return the current number of elements the buffer can hold.
*/
get size(): number {
return this.m_size;
}
/**
* Clear's the `BoxBuffer` attribute buffers.
*/
reset() {
if (this.m_positionAttribute !== undefined) {
this.m_positionAttribute.count = 0;
this.m_colorAttribute!.count = 0;
this.m_uvAttribute!.count = 0;
this.m_indexAttribute!.count = 0;
this.m_pickInfos!.length = 0;
}
}
/**
* Returns `true` if this `BoxBuffer` can hold the specified amount of glyphs. If the buffer
* can only add the glyph by increasing the buffer size, the resize() method is called, which
* will then create a new geometry for the mesh.
*
* @param glyphCount - Number of glyphs to be added to the buffer.
* @returns `true` if the element (box or glyph) can be added to the buffer, `false` otherwise.
*/
canAddElements(glyphCount = 1): boolean {
const indexAttribute = this.m_indexAttribute!;
if (
indexAttribute.count + glyphCount * NUM_INDICES_PER_ELEMENT >=
indexAttribute.array.length
) {
// Too many elements for the current buffer, check if we can resize the buffer.
if (indexAttribute.array.length >= this.m_maxElementCount * NUM_INDICES_PER_ELEMENT) {
return false;
}
const newSize = Math.min(this.m_maxElementCount, this.size === 0 ? 256 : this.size * 2);
this.resize(newSize);
}
return true;
}
/**
* Returns this `BoxBuffer`'s attribute [[State]].
*/
saveState(): State {
const state: State = {
positionAttributeCount: this.m_positionAttribute!.count,
colorAttributeCount: this.m_colorAttribute!.count,
uvAttributeCount: this.m_uvAttribute!.count,
indexAttributeCount: this.m_indexAttribute!.count,
pickInfoCount: this.m_pickInfos!.length
};
return state;
}
/**
* Store this `BoxBuffer`'s attribute [[State]] to a previously stored one.
*
* @param state - [[State]] struct describing a previous attribute state.
*/
restoreState(state: State) {
this.m_positionAttribute!.count = state.positionAttributeCount;
this.m_colorAttribute!.count = state.colorAttributeCount;
this.m_uvAttribute!.count = state.uvAttributeCount;
this.m_indexAttribute!.count = state.indexAttributeCount;
this.m_pickInfos!.length = state.pickInfoCount;
}
/**
* Adds a new box to this `BoxBuffer`.
*
* @param screenBox - [[Math2D.Box]] holding screen coordinates for this box.
* @param uvBox - [[Math2D.UvBox]] holding uv coordinates for this box.
* @param color - Box's color.
* @param opacity - Box's opacity.
* @param distance - Box's distance to camera.
* @param pickInfo - Box's picking information.
*/
addBox(
screenBox: Math2D.Box,
uvBox: Math2D.UvBox,
color: THREE.Color,
opacity: number,
distance: number,
pickInfo?: any
): boolean {
if (!this.canAddElements()) {
return false;
}
const { s0, t0, s1, t1 } = uvBox;
const { x, y, w, h } = screenBox;
// Premultiply alpha into vertex colors
const r = Math.round(color.r * opacity * 255);
const g = Math.round(color.g * opacity * 255);
const b = Math.round(color.b * opacity * 255);
const a = Math.round(opacity * 255);
const positionAttribute = this.m_positionAttribute!;
const colorAttribute = this.m_colorAttribute!;
const uvAttribute = this.m_uvAttribute!;
const indexAttribute = this.m_indexAttribute!;
const baseVertex = positionAttribute.count;
const baseIndex = indexAttribute.count;
positionAttribute.setXYZ(baseVertex, x, y, distance);
positionAttribute.setXYZ(baseVertex + 1, x + w, y, distance);
positionAttribute.setXYZ(baseVertex + 2, x, y + h, distance);
positionAttribute.setXYZ(baseVertex + 3, x + w, y + h, distance);
colorAttribute.setXYZW(baseVertex, r, g, b, a);
colorAttribute.setXYZW(baseVertex + 1, r, g, b, a);
colorAttribute.setXYZW(baseVertex + 2, r, g, b, a);
colorAttribute.setXYZW(baseVertex + 3, r, g, b, a);
uvAttribute.setXY(baseVertex, s0, t0);
uvAttribute.setXY(baseVertex + 1, s1, t0);
uvAttribute.setXY(baseVertex + 2, s0, t1);
uvAttribute.setXY(baseVertex + 3, s1, t1);
indexAttribute.setX(baseIndex, baseVertex);
indexAttribute.setX(baseIndex + 1, baseVertex + 1);
indexAttribute.setX(baseIndex + 2, baseVertex + 2);
indexAttribute.setX(baseIndex + 3, baseVertex + 2);
indexAttribute.setX(baseIndex + 4, baseVertex + 1);
indexAttribute.setX(baseIndex + 5, baseVertex + 3);
positionAttribute.count += NUM_VERTICES_PER_ELEMENT;
colorAttribute.count += NUM_VERTICES_PER_ELEMENT;
uvAttribute.count += NUM_VERTICES_PER_ELEMENT;
indexAttribute.count += NUM_INDICES_PER_ELEMENT;
this.m_pickInfos.push(pickInfo);
return true;
}
/**
* Updates a [[BufferGeometry]] object to reflect the changes in this `TextBuffer`'s attribute
* data.
*/
updateBufferGeometry() {
const positionAttribute = this.m_positionAttribute!;
const colorAttribute = this.m_colorAttribute!;
const uvAttribute = this.m_uvAttribute!;
const indexAttribute = this.m_indexAttribute!;
if (positionAttribute.count > 0) {
positionAttribute.needsUpdate = true;
positionAttribute.updateRange.offset = 0;
positionAttribute.updateRange.count =
positionAttribute.count * NUM_VERTICES_PER_ELEMENT;
}
if (colorAttribute.count > 0) {
colorAttribute.needsUpdate = true;
colorAttribute.updateRange.offset = 0;
colorAttribute.updateRange.count = colorAttribute.count * NUM_VERTICES_PER_ELEMENT;
}
if (uvAttribute.count > 0) {
uvAttribute.needsUpdate = true;
uvAttribute.updateRange.offset = 0;
uvAttribute.updateRange.count = uvAttribute.count * NUM_VERTICES_PER_ELEMENT;
}
if (indexAttribute.count > 0) {
indexAttribute.needsUpdate = true;
indexAttribute.updateRange.offset = 0;
indexAttribute.updateRange.count = indexAttribute.count;
}
if (this.m_geometry !== undefined) {
this.m_geometry.clearGroups();
this.m_geometry.addGroup(0, this.m_indexAttribute!.count);
}
}
/**
* Check if the buffer is empty. If it is empty, the memory usage is minimized to reduce
* footprint.
*/
cleanUp() {
// If there is nothing in this buffer, resize it, it may never be used again.
if (this.m_indexAttribute!.count === 0 && this.size > START_BOX_BUFFER_SIZE) {
this.clearAttributes();
}
}
/**
* Determine if the mesh is empty.
*/
get isEmpty(): boolean {
return this.m_mesh!.isEmpty;
}
/**
* Get the [[Mesh]] object. The geometry instance of the mesh may change if the buffers are
* resized. The mesh, once created, will not change, so it can always be added to the scene.
*/
get mesh(): BoxBufferMesh {
if (this.m_mesh === undefined) {
this.resize();
}
return this.m_mesh!;
}
/**
* Fill the picking results for the pixel with the given screen coordinate. If multiple
* boxes are found, the order of the results is unspecified.
*
* @param screenPosition - Screen coordinate of picking position.
* @param pickCallback - Callback to be called for every picked element.
* @param image - Image to test if the pixel is transparent
*/
pickBoxes(
screenPosition: THREE.Vector2,
pickCallback: (pickData: any | undefined) => void,
image?: CanvasImageSource | ImageData
) {
const n = this.m_pickInfos.length;
const pickInfos = this.m_pickInfos;
const positions = this.m_positionAttribute!;
const screenX = screenPosition.x;
const screenY = screenPosition.y;
for (let pickInfoIndex = 0; pickInfoIndex < n; pickInfoIndex++) {
const positionIndex = pickInfoIndex * NUM_VERTICES_PER_ELEMENT;
const minX = positions.getX(positionIndex);
if (screenX < minX) {
continue;
}
const maxX = positions.getX(positionIndex + 1);
if (screenX > maxX) {
continue;
}
const minY = positions.getY(positionIndex);
if (screenY < minY) {
continue;
}
const maxY = positions.getY(positionIndex + 2);
if (screenY > maxY) {
continue;
}
const box = new Math2D.Box(minX, minY, maxX - minX, maxY - minY);
if (
image !== undefined &&
pickInfos[pickInfoIndex].poiInfo !== undefined &&
pickInfos[pickInfoIndex].poiInfo.uvBox !== undefined &&
this.isPixelTransparent(
image,
screenX,
screenY,
box,
pickInfos[pickInfoIndex].poiInfo.uvBox,
document.createElement("canvas")
)
) {
continue;
}
if (pickInfos[pickInfoIndex] !== undefined) {
pickCallback(pickInfos[pickInfoIndex]);
}
}
}
/**
* Creates a new {@link @here/harp-datasource-protocol#Geometry} object
* from all the attribute data stored in this `BoxBuffer`.
*
* @remarks
* The [[Mesh]] object may be created if it is not initialized already.
*
* @param newSize - Optional number of elements to resize the buffer to.
* @param forceResize - Optional flag to force a resize even if new size is smaller than before.
*/
resize(newSize?: number, forceResize?: boolean): BoxBufferMesh {
if (this.m_geometry !== undefined) {
this.m_geometry.dispose();
}
this.m_geometry = new THREE.BufferGeometry();
if (newSize !== undefined && (forceResize === true || newSize > this.size)) {
this.resizeBuffer(newSize);
}
this.m_geometry.setAttribute("position", this.m_positionAttribute!);
this.m_geometry.setAttribute("color", this.m_colorAttribute!);
this.m_geometry.setAttribute("uv", this.m_uvAttribute!);
this.m_geometry.setIndex(this.m_indexAttribute!);
this.m_geometry.addGroup(0, this.m_indexAttribute!.count);
if (this.m_mesh === undefined) {
this.m_mesh = new BoxBufferMesh(this.m_geometry, this.m_material);
this.m_mesh.renderOrder = this.m_renderOrder;
} else {
this.m_mesh.geometry = this.m_geometry;
}
return this.m_mesh;
}
/**
* Update the info with the memory footprint caused by objects owned by the `BoxBuffer`.
*
* @param info - The info object to increment with the values from this `BoxBuffer`.
*/
updateMemoryUsage(info: MemoryUsage) {
const numBytes =
this.m_positionAttribute!.count * NUM_POSITION_VALUES_PER_VERTEX * NUM_BYTES_PER_FLOAT +
this.m_colorAttribute!.count * NUM_COLOR_VALUES_PER_VERTEX +
this.m_uvAttribute!.count * NUM_UV_VALUES_PER_VERTEX * NUM_BYTES_PER_FLOAT +
this.m_indexAttribute!.count * NUM_BYTES_PER_INT32; // May be UInt16, so we overestimate
info.heapSize += numBytes;
info.gpuSize += numBytes;
}
/**
* Check if a pixel is transparent or not.
*
* @param image - Image source.
* @param xScreenPos - X position of the pixel.
* @param yScreenPos - Y position of the pixel.
* @param box - Bounding box of the image in screen coordinates.
* @param uvBox - Uv box referred to the given bounding box.
* @param canvas - Canvas element to draw the image if it's not a `ImageData` object.
*/
private isPixelTransparent(
image: CanvasImageSource | ImageData,
xScreenPos: number,
yScreenPos: number,
box: Math2D.Box,
uvBox: Math2D.UvBox,
canvas?: HTMLCanvasElement
): boolean {
const { u, v } = screenToUvCoordinates(xScreenPos, yScreenPos, box, uvBox);
const { width, height } = image instanceof SVGImageElement ? image.getBBox() : image;
const x = width * u;
const y = height * v;
const pixel = getPixelFromImage(x, y, image, canvas);
return pixel !== undefined && pixel[3] === 0;
}
/**
* Remove current attributes and arrays. Minimizes memory footprint.
*/
private clearAttributes() {
this.m_positionAttribute = undefined;
this.m_colorAttribute = undefined;
this.m_uvAttribute = undefined;
this.m_indexAttribute = undefined;
this.resize(START_BOX_BUFFER_SIZE, true);
}
/**
* Resize the attribute buffers. New value must be larger than the previous one.
*
* @param newSize - New number of elements in the buffer. Number has to be larger than the
* previous size.
*/
private resizeBuffer(newSize: number) {
const newPositionArray = new Float32Array(
newSize * NUM_VERTICES_PER_ELEMENT * NUM_POSITION_VALUES_PER_VERTEX
);
if (this.m_positionAttribute !== undefined && this.m_positionAttribute.array.length > 0) {
const positionAttributeCount = this.m_positionAttribute.count;
newPositionArray.set(this.m_positionAttribute.array);
this.m_positionAttribute.array = newPositionArray;
this.m_positionAttribute.count = positionAttributeCount;
} else {
this.m_positionAttribute = new THREE.BufferAttribute(
newPositionArray,
NUM_POSITION_VALUES_PER_VERTEX
);
this.m_positionAttribute.count = 0;
this.m_positionAttribute.setUsage(THREE.DynamicDrawUsage);
}
const newColorArray = new Uint8Array(
newSize * NUM_VERTICES_PER_ELEMENT * NUM_COLOR_VALUES_PER_VERTEX
);
if (this.m_colorAttribute !== undefined) {
const colorAttributeCount = this.m_colorAttribute.count;
newColorArray.set(this.m_colorAttribute.array);
this.m_colorAttribute.array = newColorArray;
this.m_colorAttribute.count = colorAttributeCount;
} else {
this.m_colorAttribute = new THREE.BufferAttribute(
newColorArray,
NUM_COLOR_VALUES_PER_VERTEX,
true
);
this.m_colorAttribute.count = 0;
this.m_colorAttribute.setUsage(THREE.DynamicDrawUsage);
}
const newUvArray = new Float32Array(
newSize * NUM_VERTICES_PER_ELEMENT * NUM_UV_VALUES_PER_VERTEX
);
if (this.m_uvAttribute !== undefined) {
const uvAttributeCount = this.m_uvAttribute.count;
newUvArray.set(this.m_uvAttribute.array);
this.m_uvAttribute.array = newUvArray;
this.m_uvAttribute.count = uvAttributeCount;
} else {
this.m_uvAttribute = new THREE.BufferAttribute(newUvArray, NUM_UV_VALUES_PER_VERTEX);
this.m_uvAttribute.count = 0;
this.m_uvAttribute.setUsage(THREE.DynamicDrawUsage);
}
const numIndexValues = newSize * NUM_INDICES_PER_ELEMENT * NUM_INDEX_VALUES_PER_VERTEX;
const newIndexArray =
numIndexValues > 65535
? new Uint32Array(numIndexValues)
: new Uint16Array(numIndexValues);
if (this.m_indexAttribute !== undefined) {
const indexAttributeCount = this.m_indexAttribute.count;
newIndexArray.set(this.m_indexAttribute.array);
this.m_indexAttribute.array = newIndexArray;
this.m_indexAttribute.count = indexAttributeCount;
} else {
this.m_indexAttribute = new THREE.BufferAttribute(
newIndexArray,
NUM_INDEX_VALUES_PER_VERTEX
);
this.m_indexAttribute.count = 0;
this.m_indexAttribute.setUsage(THREE.DynamicDrawUsage);
}
this.m_size = newSize;
}
} | the_stack |
import * as acm from '@aws-cdk/aws-certificatemanager';
import * as lambda from '@aws-cdk/aws-lambda';
import * as s3 from '@aws-cdk/aws-s3';
import { ArnFormat, IResource, Lazy, Resource, Stack, Token, Duration, Names, FeatureFlags } from '@aws-cdk/core';
import { CLOUDFRONT_DEFAULT_SECURITY_POLICY_TLS_V1_2_2021 } from '@aws-cdk/cx-api';
import { Construct } from 'constructs';
import { ICachePolicy } from './cache-policy';
import { CfnDistribution } from './cloudfront.generated';
import { FunctionAssociation } from './function';
import { GeoRestriction } from './geo-restriction';
import { IKeyGroup } from './key-group';
import { IOrigin, OriginBindConfig, OriginBindOptions } from './origin';
import { IOriginRequestPolicy } from './origin-request-policy';
import { CacheBehavior } from './private/cache-behavior';
import { IResponseHeadersPolicy } from './response-headers-policy';
/**
* Interface for CloudFront distributions
*/
export interface IDistribution extends IResource {
/**
* The domain name of the Distribution, such as d111111abcdef8.cloudfront.net.
*
* @attribute
* @deprecated - Use `distributionDomainName` instead.
*/
readonly domainName: string;
/**
* The domain name of the Distribution, such as d111111abcdef8.cloudfront.net.
*
* @attribute
*/
readonly distributionDomainName: string;
/**
* The distribution ID for this distribution.
*
* @attribute
*/
readonly distributionId: string;
}
/**
* Attributes used to import a Distribution.
*/
export interface DistributionAttributes {
/**
* The generated domain name of the Distribution, such as d111111abcdef8.cloudfront.net.
*
* @attribute
*/
readonly domainName: string;
/**
* The distribution ID for this distribution.
*
* @attribute
*/
readonly distributionId: string;
}
interface BoundOrigin extends OriginBindOptions, OriginBindConfig {
readonly origin: IOrigin;
readonly originGroupId?: string;
}
/**
* Properties for a Distribution
*/
export interface DistributionProps {
/**
* The default behavior for the distribution.
*/
readonly defaultBehavior: BehaviorOptions;
/**
* Additional behaviors for the distribution, mapped by the pathPattern that specifies which requests to apply the behavior to.
*
* @default - no additional behaviors are added.
*/
readonly additionalBehaviors?: Record<string, BehaviorOptions>;
/**
* A certificate to associate with the distribution. The certificate must be located in N. Virginia (us-east-1).
*
* @default - the CloudFront wildcard certificate (*.cloudfront.net) will be used.
*/
readonly certificate?: acm.ICertificate;
/**
* Any comments you want to include about the distribution.
*
* @default - no comment
*/
readonly comment?: string;
/**
* The object that you want CloudFront to request from your origin (for example, index.html)
* when a viewer requests the root URL for your distribution. If no default object is set, the
* request goes to the origin's root (e.g., example.com/).
*
* @default - no default root object
*/
readonly defaultRootObject?: string;
/**
* Alternative domain names for this distribution.
*
* If you want to use your own domain name, such as www.example.com, instead of the cloudfront.net domain name,
* you can add an alternate domain name to your distribution. If you attach a certificate to the distribution,
* you must add (at least one of) the domain names of the certificate to this list.
*
* @default - The distribution will only support the default generated name (e.g., d111111abcdef8.cloudfront.net)
*/
readonly domainNames?: string[];
/**
* Enable or disable the distribution.
*
* @default true
*/
readonly enabled?: boolean;
/**
* Whether CloudFront will respond to IPv6 DNS requests with an IPv6 address.
*
* If you specify false, CloudFront responds to IPv6 DNS requests with the DNS response code NOERROR and with no IP addresses.
* This allows viewers to submit a second request, for an IPv4 address for your distribution.
*
* @default true
*/
readonly enableIpv6?: boolean;
/**
* Enable access logging for the distribution.
*
* @default - false, unless `logBucket` is specified.
*/
readonly enableLogging?: boolean;
/**
* Controls the countries in which your content is distributed.
*
* @default - No geographic restrictions
*/
readonly geoRestriction?: GeoRestriction;
/**
* Specify the maximum HTTP version that you want viewers to use to communicate with CloudFront.
*
* For viewers and CloudFront to use HTTP/2, viewers must support TLS 1.2 or later, and must support server name identification (SNI).
*
* @default HttpVersion.HTTP2
*/
readonly httpVersion?: HttpVersion;
/**
* The Amazon S3 bucket to store the access logs in.
*
* @default - A bucket is created if `enableLogging` is true
*/
readonly logBucket?: s3.IBucket;
/**
* Specifies whether you want CloudFront to include cookies in access logs
*
* @default false
*/
readonly logIncludesCookies?: boolean;
/**
* An optional string that you want CloudFront to prefix to the access log filenames for this distribution.
*
* @default - no prefix
*/
readonly logFilePrefix?: string;
/**
* The price class that corresponds with the maximum price that you want to pay for CloudFront service.
* If you specify PriceClass_All, CloudFront responds to requests for your objects from all CloudFront edge locations.
* If you specify a price class other than PriceClass_All, CloudFront serves your objects from the CloudFront edge location
* that has the lowest latency among the edge locations in your price class.
*
* @default PriceClass.PRICE_CLASS_ALL
*/
readonly priceClass?: PriceClass;
/**
* Unique identifier that specifies the AWS WAF web ACL to associate with this CloudFront distribution.
*
* To specify a web ACL created using the latest version of AWS WAF, use the ACL ARN, for example
* `arn:aws:wafv2:us-east-1:123456789012:global/webacl/ExampleWebACL/473e64fd-f30b-4765-81a0-62ad96dd167a`.
* To specify a web ACL created using AWS WAF Classic, use the ACL ID, for example `473e64fd-f30b-4765-81a0-62ad96dd167a`.
*
* @see https://docs.aws.amazon.com/waf/latest/developerguide/what-is-aws-waf.html
* @see https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateDistribution.html#API_CreateDistribution_RequestParameters.
*
* @default - No AWS Web Application Firewall web access control list (web ACL).
*/
readonly webAclId?: string;
/**
* How CloudFront should handle requests that are not successful (e.g., PageNotFound).
*
* @default - No custom error responses.
*/
readonly errorResponses?: ErrorResponse[];
/**
* The minimum version of the SSL protocol that you want CloudFront to use for HTTPS connections.
*
* CloudFront serves your objects only to browsers or devices that support at
* least the SSL version that you specify.
*
* @default - SecurityPolicyProtocol.TLS_V1_2_2021 if the '@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021' feature flag is set; otherwise, SecurityPolicyProtocol.TLS_V1_2_2019.
*/
readonly minimumProtocolVersion?: SecurityPolicyProtocol;
/**
* The SSL method CloudFront will use for your distribution.
*
* Server Name Indication (SNI) - is an extension to the TLS computer networking protocol by which a client indicates
* which hostname it is attempting to connect to at the start of the handshaking process. This allows a server to present
* multiple certificates on the same IP address and TCP port number and hence allows multiple secure (HTTPS) websites
* (or any other service over TLS) to be served by the same IP address without requiring all those sites to use the same certificate.
*
* CloudFront can use SNI to host multiple distributions on the same IP - which a large majority of clients will support.
*
* If your clients cannot support SNI however - CloudFront can use dedicated IPs for your distribution - but there is a prorated monthly charge for
* using this feature. By default, we use SNI - but you can optionally enable dedicated IPs (VIP).
*
* See the CloudFront SSL for more details about pricing : https://aws.amazon.com/cloudfront/custom-ssl-domains/
*
* @default SSLMethod.SNI
*/
readonly sslSupportMethod?: SSLMethod;
}
/**
* A CloudFront distribution with associated origin(s) and caching behavior(s).
*/
export class Distribution extends Resource implements IDistribution {
/**
* Creates a Distribution construct that represents an external (imported) distribution.
*/
public static fromDistributionAttributes(scope: Construct, id: string, attrs: DistributionAttributes): IDistribution {
return new class extends Resource implements IDistribution {
public readonly domainName: string;
public readonly distributionDomainName: string;
public readonly distributionId: string;
constructor() {
super(scope, id);
this.domainName = attrs.domainName;
this.distributionDomainName = attrs.domainName;
this.distributionId = attrs.distributionId;
}
}();
}
public readonly domainName: string;
public readonly distributionDomainName: string;
public readonly distributionId: string;
private readonly defaultBehavior: CacheBehavior;
private readonly additionalBehaviors: CacheBehavior[] = [];
private readonly boundOrigins: BoundOrigin[] = [];
private readonly originGroups: CfnDistribution.OriginGroupProperty[] = [];
private readonly errorResponses: ErrorResponse[];
private readonly certificate?: acm.ICertificate;
constructor(scope: Construct, id: string, props: DistributionProps) {
super(scope, id);
if (props.certificate) {
const certificateRegion = Stack.of(this).splitArn(props.certificate.certificateArn, ArnFormat.SLASH_RESOURCE_NAME).region;
if (!Token.isUnresolved(certificateRegion) && certificateRegion !== 'us-east-1') {
throw new Error(`Distribution certificates must be in the us-east-1 region and the certificate you provided is in ${certificateRegion}.`);
}
if ((props.domainNames ?? []).length === 0) {
throw new Error('Must specify at least one domain name to use a certificate with a distribution');
}
}
const originId = this.addOrigin(props.defaultBehavior.origin);
this.defaultBehavior = new CacheBehavior(originId, { pathPattern: '*', ...props.defaultBehavior });
if (props.additionalBehaviors) {
Object.entries(props.additionalBehaviors).forEach(([pathPattern, behaviorOptions]) => {
this.addBehavior(pathPattern, behaviorOptions.origin, behaviorOptions);
});
}
this.certificate = props.certificate;
this.errorResponses = props.errorResponses ?? [];
// Comments have an undocumented limit of 128 characters
const trimmedComment =
props.comment && props.comment.length > 128
? `${props.comment.slice(0, 128 - 3)}...`
: props.comment;
const distribution = new CfnDistribution(this, 'Resource', {
distributionConfig: {
enabled: props.enabled ?? true,
origins: Lazy.any({ produce: () => this.renderOrigins() }),
originGroups: Lazy.any({ produce: () => this.renderOriginGroups() }),
defaultCacheBehavior: this.defaultBehavior._renderBehavior(),
aliases: props.domainNames,
cacheBehaviors: Lazy.any({ produce: () => this.renderCacheBehaviors() }),
comment: trimmedComment,
customErrorResponses: this.renderErrorResponses(),
defaultRootObject: props.defaultRootObject,
httpVersion: props.httpVersion ?? HttpVersion.HTTP2,
ipv6Enabled: props.enableIpv6 ?? true,
logging: this.renderLogging(props),
priceClass: props.priceClass ?? undefined,
restrictions: this.renderRestrictions(props.geoRestriction),
viewerCertificate: this.certificate ? this.renderViewerCertificate(this.certificate,
props.minimumProtocolVersion, props.sslSupportMethod) : undefined,
webAclId: props.webAclId,
},
});
this.domainName = distribution.attrDomainName;
this.distributionDomainName = distribution.attrDomainName;
this.distributionId = distribution.ref;
}
/**
* Adds a new behavior to this distribution for the given pathPattern.
*
* @param pathPattern the path pattern (e.g., 'images/*') that specifies which requests to apply the behavior to.
* @param origin the origin to use for this behavior
* @param behaviorOptions the options for the behavior at this path.
*/
public addBehavior(pathPattern: string, origin: IOrigin, behaviorOptions: AddBehaviorOptions = {}) {
if (pathPattern === '*') {
throw new Error('Only the default behavior can have a path pattern of \'*\'');
}
const originId = this.addOrigin(origin);
this.additionalBehaviors.push(new CacheBehavior(originId, { pathPattern, ...behaviorOptions }));
}
private addOrigin(origin: IOrigin, isFailoverOrigin: boolean = false): string {
const ORIGIN_ID_MAX_LENGTH = 128;
const existingOrigin = this.boundOrigins.find(boundOrigin => boundOrigin.origin === origin);
if (existingOrigin) {
return existingOrigin.originGroupId ?? existingOrigin.originId;
} else {
const originIndex = this.boundOrigins.length + 1;
const scope = new Construct(this, `Origin${originIndex}`);
const originId = Names.uniqueId(scope).slice(-ORIGIN_ID_MAX_LENGTH);
const originBindConfig = origin.bind(scope, { originId });
if (!originBindConfig.failoverConfig) {
this.boundOrigins.push({ origin, originId, ...originBindConfig });
} else {
if (isFailoverOrigin) {
throw new Error('An Origin cannot use an Origin with its own failover configuration as its fallback origin!');
}
const groupIndex = this.originGroups.length + 1;
const originGroupId = Names.uniqueId(new Construct(this, `OriginGroup${groupIndex}`)).slice(-ORIGIN_ID_MAX_LENGTH);
this.boundOrigins.push({ origin, originId, originGroupId, ...originBindConfig });
const failoverOriginId = this.addOrigin(originBindConfig.failoverConfig.failoverOrigin, true);
this.addOriginGroup(originGroupId, originBindConfig.failoverConfig.statusCodes, originId, failoverOriginId);
return originGroupId;
}
return originId;
}
}
private addOriginGroup(originGroupId: string, statusCodes: number[] | undefined, originId: string, failoverOriginId: string): void {
statusCodes = statusCodes ?? [500, 502, 503, 504];
if (statusCodes.length === 0) {
throw new Error('fallbackStatusCodes cannot be empty');
}
this.originGroups.push({
failoverCriteria: {
statusCodes: {
items: statusCodes,
quantity: statusCodes.length,
},
},
id: originGroupId,
members: {
items: [
{ originId },
{ originId: failoverOriginId },
],
quantity: 2,
},
});
}
private renderOrigins(): CfnDistribution.OriginProperty[] {
const renderedOrigins: CfnDistribution.OriginProperty[] = [];
this.boundOrigins.forEach(boundOrigin => {
if (boundOrigin.originProperty) {
renderedOrigins.push(boundOrigin.originProperty);
}
});
return renderedOrigins;
}
private renderOriginGroups(): CfnDistribution.OriginGroupsProperty | undefined {
return this.originGroups.length === 0
? undefined
: {
items: this.originGroups,
quantity: this.originGroups.length,
};
}
private renderCacheBehaviors(): CfnDistribution.CacheBehaviorProperty[] | undefined {
if (this.additionalBehaviors.length === 0) { return undefined; }
return this.additionalBehaviors.map(behavior => behavior._renderBehavior());
}
private renderErrorResponses(): CfnDistribution.CustomErrorResponseProperty[] | undefined {
if (this.errorResponses.length === 0) { return undefined; }
return this.errorResponses.map(errorConfig => {
if (!errorConfig.responseHttpStatus && !errorConfig.ttl && !errorConfig.responsePagePath) {
throw new Error('A custom error response without either a \'responseHttpStatus\', \'ttl\' or \'responsePagePath\' is not valid.');
}
return {
errorCachingMinTtl: errorConfig.ttl?.toSeconds(),
errorCode: errorConfig.httpStatus,
responseCode: errorConfig.responsePagePath
? errorConfig.responseHttpStatus ?? errorConfig.httpStatus
: errorConfig.responseHttpStatus,
responsePagePath: errorConfig.responsePagePath,
};
});
}
private renderLogging(props: DistributionProps): CfnDistribution.LoggingProperty | undefined {
if (!props.enableLogging && !props.logBucket) { return undefined; }
if (props.enableLogging === false && props.logBucket) {
throw new Error('Explicitly disabled logging but provided a logging bucket.');
}
const bucket = props.logBucket ?? new s3.Bucket(this, 'LoggingBucket', {
encryption: s3.BucketEncryption.S3_MANAGED,
});
return {
bucket: bucket.bucketRegionalDomainName,
includeCookies: props.logIncludesCookies,
prefix: props.logFilePrefix,
};
}
private renderRestrictions(geoRestriction?: GeoRestriction) {
return geoRestriction ? {
geoRestriction: {
restrictionType: geoRestriction.restrictionType,
locations: geoRestriction.locations,
},
} : undefined;
}
private renderViewerCertificate(certificate: acm.ICertificate,
minimumProtocolVersionProp?: SecurityPolicyProtocol, sslSupportMethodProp?: SSLMethod): CfnDistribution.ViewerCertificateProperty {
const defaultVersion = FeatureFlags.of(this).isEnabled(CLOUDFRONT_DEFAULT_SECURITY_POLICY_TLS_V1_2_2021)
? SecurityPolicyProtocol.TLS_V1_2_2021 : SecurityPolicyProtocol.TLS_V1_2_2019;
const minimumProtocolVersion = minimumProtocolVersionProp ?? defaultVersion;
const sslSupportMethod = sslSupportMethodProp ?? SSLMethod.SNI;
return {
acmCertificateArn: certificate.certificateArn,
minimumProtocolVersion: minimumProtocolVersion,
sslSupportMethod: sslSupportMethod,
};
}
}
/** Maximum HTTP version to support */
export enum HttpVersion {
/** HTTP 1.1 */
HTTP1_1 = 'http1.1',
/** HTTP 2 */
HTTP2 = 'http2'
}
/**
* The price class determines how many edge locations CloudFront will use for your distribution.
* See https://aws.amazon.com/cloudfront/pricing/ for full list of supported regions.
*/
export enum PriceClass {
/** USA, Canada, Europe, & Israel */
PRICE_CLASS_100 = 'PriceClass_100',
/** PRICE_CLASS_100 + South Africa, Kenya, Middle East, Japan, Singapore, South Korea, Taiwan, Hong Kong, & Philippines */
PRICE_CLASS_200 = 'PriceClass_200',
/** All locations */
PRICE_CLASS_ALL = 'PriceClass_All'
}
/**
* How HTTPs should be handled with your distribution.
*/
export enum ViewerProtocolPolicy {
/** HTTPS only */
HTTPS_ONLY = 'https-only',
/** Will redirect HTTP requests to HTTPS */
REDIRECT_TO_HTTPS = 'redirect-to-https',
/** Both HTTP and HTTPS supported */
ALLOW_ALL = 'allow-all'
}
/**
* Defines what protocols CloudFront will use to connect to an origin.
*/
export enum OriginProtocolPolicy {
/** Connect on HTTP only */
HTTP_ONLY = 'http-only',
/** Connect with the same protocol as the viewer */
MATCH_VIEWER = 'match-viewer',
/** Connect on HTTPS only */
HTTPS_ONLY = 'https-only',
}
/**
* The SSL method CloudFront will use for your distribution.
*
* Server Name Indication (SNI) - is an extension to the TLS computer networking protocol by which a client indicates
* which hostname it is attempting to connect to at the start of the handshaking process. This allows a server to present
* multiple certificates on the same IP address and TCP port number and hence allows multiple secure (HTTPS) websites
* (or any other service over TLS) to be served by the same IP address without requiring all those sites to use the same certificate.
*
* CloudFront can use SNI to host multiple distributions on the same IP - which a large majority of clients will support.
*
* If your clients cannot support SNI however - CloudFront can use dedicated IPs for your distribution - but there is a prorated monthly charge for
* using this feature. By default, we use SNI - but you can optionally enable dedicated IPs (VIP).
*
* See the CloudFront SSL for more details about pricing : https://aws.amazon.com/cloudfront/custom-ssl-domains/
*
*/
export enum SSLMethod {
SNI = 'sni-only',
VIP = 'vip'
}
/**
* The minimum version of the SSL protocol that you want CloudFront to use for HTTPS connections.
* CloudFront serves your objects only to browsers or devices that support at least the SSL version that you specify.
*/
export enum SecurityPolicyProtocol {
SSL_V3 = 'SSLv3',
TLS_V1 = 'TLSv1',
TLS_V1_2016 = 'TLSv1_2016',
TLS_V1_1_2016 = 'TLSv1.1_2016',
TLS_V1_2_2018 = 'TLSv1.2_2018',
TLS_V1_2_2019 = 'TLSv1.2_2019',
TLS_V1_2_2021 = 'TLSv1.2_2021'
}
/**
* The HTTP methods that the Behavior will accept requests on.
*/
export class AllowedMethods {
/** HEAD and GET */
public static readonly ALLOW_GET_HEAD = new AllowedMethods(['GET', 'HEAD']);
/** HEAD, GET, and OPTIONS */
public static readonly ALLOW_GET_HEAD_OPTIONS = new AllowedMethods(['GET', 'HEAD', 'OPTIONS']);
/** All supported HTTP methods */
public static readonly ALLOW_ALL = new AllowedMethods(['GET', 'HEAD', 'OPTIONS', 'PUT', 'PATCH', 'POST', 'DELETE']);
/** HTTP methods supported */
public readonly methods: string[];
private constructor(methods: string[]) { this.methods = methods; }
}
/**
* The HTTP methods that the Behavior will cache requests on.
*/
export class CachedMethods {
/** HEAD and GET */
public static readonly CACHE_GET_HEAD = new CachedMethods(['GET', 'HEAD']);
/** HEAD, GET, and OPTIONS */
public static readonly CACHE_GET_HEAD_OPTIONS = new CachedMethods(['GET', 'HEAD', 'OPTIONS']);
/** HTTP methods supported */
public readonly methods: string[];
private constructor(methods: string[]) { this.methods = methods; }
}
/**
* Options for configuring custom error responses.
*/
export interface ErrorResponse {
/**
* The minimum amount of time, in seconds, that you want CloudFront to cache the HTTP status code specified in ErrorCode.
*
* @default - the default caching TTL behavior applies
*/
readonly ttl?: Duration;
/**
* The HTTP status code for which you want to specify a custom error page and/or a caching duration.
*/
readonly httpStatus: number;
/**
* The HTTP status code that you want CloudFront to return to the viewer along with the custom error page.
*
* If you specify a value for `responseHttpStatus`, you must also specify a value for `responsePagePath`.
*
* @default - the error code will be returned as the response code.
*/
readonly responseHttpStatus?: number;
/**
* The path to the custom error page that you want CloudFront to return to a viewer when your origin returns the
* `httpStatus`, for example, /4xx-errors/403-forbidden.html
*
* @default - the default CloudFront response is shown.
*/
readonly responsePagePath?: string;
}
/**
* The type of events that a Lambda@Edge function can be invoked in response to.
*/
export enum LambdaEdgeEventType {
/**
* The origin-request specifies the request to the
* origin location (e.g. S3)
*/
ORIGIN_REQUEST = 'origin-request',
/**
* The origin-response specifies the response from the
* origin location (e.g. S3)
*/
ORIGIN_RESPONSE = 'origin-response',
/**
* The viewer-request specifies the incoming request
*/
VIEWER_REQUEST = 'viewer-request',
/**
* The viewer-response specifies the outgoing response
*/
VIEWER_RESPONSE = 'viewer-response',
}
/**
* Represents a Lambda function version and event type when using Lambda@Edge.
* The type of the {@link AddBehaviorOptions.edgeLambdas} property.
*/
export interface EdgeLambda {
/**
* The version of the Lambda function that will be invoked.
*
* **Note**: it's not possible to use the '$LATEST' function version for Lambda@Edge!
*/
readonly functionVersion: lambda.IVersion;
/** The type of event in response to which should the function be invoked. */
readonly eventType: LambdaEdgeEventType;
/**
* Allows a Lambda function to have read access to the body content.
* Only valid for "request" event types (`ORIGIN_REQUEST` or `VIEWER_REQUEST`).
* See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-include-body-access.html
*
* @default false
*/
readonly includeBody?: boolean;
}
/**
* Options for adding a new behavior to a Distribution.
*/
export interface AddBehaviorOptions {
/**
* HTTP methods to allow for this behavior.
*
* @default AllowedMethods.ALLOW_GET_HEAD
*/
readonly allowedMethods?: AllowedMethods;
/**
* HTTP methods to cache for this behavior.
*
* @default CachedMethods.CACHE_GET_HEAD
*/
readonly cachedMethods?: CachedMethods;
/**
* The cache policy for this behavior. The cache policy determines what values are included in the cache key,
* and the time-to-live (TTL) values for the cache.
*
* @see https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html.
* @default CachePolicy.CACHING_OPTIMIZED
*/
readonly cachePolicy?: ICachePolicy;
/**
* Whether you want CloudFront to automatically compress certain files for this cache behavior.
* See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html#compressed-content-cloudfront-file-types
* for file types CloudFront will compress.
*
* @default true
*/
readonly compress?: boolean;
/**
* The origin request policy for this behavior. The origin request policy determines which values (e.g., headers, cookies)
* are included in requests that CloudFront sends to the origin.
*
* @default - none
*/
readonly originRequestPolicy?: IOriginRequestPolicy;
/**
* The response headers policy for this behavior. The response headers policy determines which headers are included in responses
*
* @default - none
*/
readonly responseHeadersPolicy?: IResponseHeadersPolicy;
/**
* Set this to true to indicate you want to distribute media files in the Microsoft Smooth Streaming format using this behavior.
*
* @default false
*/
readonly smoothStreaming?: boolean;
/**
* The protocol that viewers can use to access the files controlled by this behavior.
*
* @default ViewerProtocolPolicy.ALLOW_ALL
*/
readonly viewerProtocolPolicy?: ViewerProtocolPolicy;
/**
* The CloudFront functions to invoke before serving the contents.
*
* @default - no functions will be invoked
*/
readonly functionAssociations?: FunctionAssociation[];
/**
* The Lambda@Edge functions to invoke before serving the contents.
*
* @default - no Lambda functions will be invoked
* @see https://aws.amazon.com/lambda/edge
*/
readonly edgeLambdas?: EdgeLambda[];
/**
* A list of Key Groups that CloudFront can use to validate signed URLs or signed cookies.
*
* @default - no KeyGroups are associated with cache behavior
* @see https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html
*/
readonly trustedKeyGroups?: IKeyGroup[];
}
/**
* Options for creating a new behavior.
*/
export interface BehaviorOptions extends AddBehaviorOptions {
/**
* The origin that you want CloudFront to route requests to when they match this behavior.
*/
readonly origin: IOrigin;
} | the_stack |
'use strict';
import * as fs from 'fs';
import * as os from 'os';
import { assert, expect } from 'chai';
import { Container, Scope } from 'typescript-ioc';
import * as component from '../../common/component';
import { Database, DataStore } from '../../common/datastore';
import { Manager, ExperimentProfile} from '../../common/manager';
import { ExperimentManager } from '../../common/experimentManager';
import { TrainingService } from '../../common/trainingService';
import { cleanupUnitTest, prepareUnitTest } from '../../common/utils';
import { NNIExperimentsManager } from '../../core/nniExperimentsManager';
import { NNIManager } from '../../core/nnimanager';
import { SqlDB } from '../../core/sqlDatabase';
import { MockedTrainingService } from '../mock/trainingService';
import { MockedDataStore } from '../mock/datastore';
import { TensorboardManager } from '../../common/tensorboardManager';
import { NNITensorboardManager } from '../../core/nniTensorboardManager';
import * as path from 'path';
async function initContainer(): Promise<void> {
prepareUnitTest();
Container.bind(Manager).to(NNIManager).scope(Scope.Singleton);
Container.bind(Database).to(SqlDB).scope(Scope.Singleton);
Container.bind(DataStore).to(MockedDataStore).scope(Scope.Singleton);
Container.bind(ExperimentManager).to(NNIExperimentsManager).scope(Scope.Singleton);
Container.bind(TensorboardManager).to(NNITensorboardManager).scope(Scope.Singleton);
await component.get<DataStore>(DataStore).init();
}
// FIXME: timeout on macOS
describe('Unit test for nnimanager', function () {
let nniManager: NNIManager;
let ClusterMetadataKey = 'mockedMetadataKey';
let experimentParams: any = {
experimentName: 'naive_experiment',
trialConcurrency: 3,
maxExperimentDuration: '5s',
maxTrialNumber: 3,
trainingService: {
platform: 'local'
},
searchSpace: {'lr': {'_type': 'choice', '_value': [0.01,0.001]}},
tuner: {
name: 'TPE',
classArgs: {
optimize_mode: 'maximize'
}
},
assessor: {
name: 'Medianstop'
},
trialCommand: 'sleep 2',
trialCodeDirectory: '',
debug: true
}
let updateExperimentParams = {
experimentName: 'another_experiment',
trialConcurrency: 2,
maxExperimentDuration: '6s',
maxTrialNumber: 2,
trainingService: {
platform: 'local'
},
searchSpace: '{"lr": {"_type": "choice", "_value": [0.01,0.001]}}',
tuner: {
name: 'TPE',
classArgs: {
optimize_mode: 'maximize'
}
},
assessor: {
name: 'Medianstop'
},
trialCommand: 'sleep 2',
trialCodeDirectory: '',
debug: true
}
let experimentProfile: any = {
params: updateExperimentParams,
id: 'test',
execDuration: 0,
logDir: '',
startTime: 0,
nextSequenceId: 0,
revision: 0
}
let mockedInfo = {
"unittest": {
"port": 8080,
"startTime": 1605246730756,
"endTime": "N/A",
"status": "INITIALIZED",
"platform": "local",
"experimentName": "testExp",
"tag": [], "pid": 11111,
"webuiUrl": [],
"logDir": null
}
}
before(async () => {
await initContainer();
fs.writeFileSync('.experiment.test', JSON.stringify(mockedInfo));
const experimentsManager: ExperimentManager = component.get(ExperimentManager);
experimentsManager.setExperimentPath('.experiment.test');
nniManager = component.get(Manager);
const expId: string = await nniManager.startExperiment(experimentParams);
assert.strictEqual(expId, 'unittest');
// TODO:
// In current architecture we cannot prevent NNI manager from creating a training service.
// The training service must be manually stopped here or its callbacks will block exit.
// I'm planning on a custom training service register system similar to custom tuner,
// and when that is done we can let NNI manager to use MockedTrainingService through config.
const manager = nniManager as any;
manager.trainingService.removeTrialJobMetricListener(manager.trialJobMetricListener);
manager.trainingService.cleanUp();
manager.trainingService = new MockedTrainingService();
})
after(async () => {
// FIXME
await nniManager.stopExperimentTopHalf();
cleanupUnitTest();
})
it('test addCustomizedTrialJob', () => {
return nniManager.addCustomizedTrialJob('"hyperParams"').then(() => {
}).catch((error) => {
assert.fail(error);
})
})
it('test listTrialJobs', () => {
return nniManager.listTrialJobs().then(function (trialjobdetails) {
expect(trialjobdetails.length).to.be.equal(2);
}).catch((error) => {
assert.fail(error);
})
})
it('test getTrialJob valid', () => {
//query a exist id
return nniManager.getTrialJob('1234').then(function (trialJobDetail) {
expect(trialJobDetail.trialJobId).to.be.equal('1234');
}).catch((error) => {
assert.fail(error);
})
})
it('test getTrialJob with invalid id', () => {
//query a not exist id, and the function should throw error, and should not process then() method
return nniManager.getTrialJob('4567').then((_jobid) => {
assert.fail();
}).catch((_error) => {
assert.isTrue(true);
})
})
it('test cancelTrialJobByUser', () => {
return nniManager.cancelTrialJobByUser('1234').then(() => {
}).catch((error) => {
console.log(error);
assert.fail(error);
})
})
it('test getExperimentProfile', () => {
return nniManager.getExperimentProfile().then((experimentProfile) => {
expect(experimentProfile.id).to.be.equal('unittest');
expect(experimentProfile.logDir).to.be.equal(path.join(os.homedir(),'nni-experiments','unittest'));
}).catch((error) => {
assert.fail(error);
})
})
it('test updateExperimentProfile TRIAL_CONCURRENCY', () => {
return nniManager.updateExperimentProfile(experimentProfile, 'TRIAL_CONCURRENCY').then(() => {
nniManager.getExperimentProfile().then((updateProfile) => {
expect(updateProfile.params.trialConcurrency).to.be.equal(2);
});
}).catch((error) => {
assert.fail(error);
})
})
it('test updateExperimentProfile MAX_EXEC_DURATION', () => {
return nniManager.updateExperimentProfile(experimentProfile, 'MAX_EXEC_DURATION').then(() => {
nniManager.getExperimentProfile().then((updateProfile) => {
expect(updateProfile.params.maxExperimentDuration).to.be.equal('6s');
});
}).catch((error) => {
assert.fail(error);
})
})
it('test updateExperimentProfile SEARCH_SPACE', () => {
return nniManager.updateExperimentProfile(experimentProfile, 'SEARCH_SPACE').then(() => {
nniManager.getExperimentProfile().then((updateProfile) => {
expect(updateProfile.params.searchSpace).to.be.equal('{"lr": {"_type": "choice", "_value": [0.01,0.001]}}');
});
}).catch((error) => {
assert.fail(error);
})
})
it('test updateExperimentProfile MAX_TRIAL_NUM', () => {
return nniManager.updateExperimentProfile(experimentProfile, 'MAX_TRIAL_NUM').then(() => {
nniManager.getExperimentProfile().then((updateProfile) => {
expect(updateProfile.params.maxTrialNumber).to.be.equal(2);
});
}).catch((error: any) => {
assert.fail(error);
})
})
it('test getStatus', () => {
assert.strictEqual(nniManager.getStatus().status,'RUNNING');
})
it('test getMetricData with trialJobId', () => {
//query a exist trialJobId
return nniManager.getMetricData('4321', 'CUSTOM').then((metricData) => {
expect(metricData.length).to.be.equal(1);
expect(metricData[0].trialJobId).to.be.equal('4321');
expect(metricData[0].parameterId).to.be.equal('param1');
}).catch((error) => {
assert.fail(error);
})
})
it('test getMetricData with invalid trialJobId', () => {
//query an invalid trialJobId
return nniManager.getMetricData('43210', 'CUSTOM').then((_metricData) => {
assert.fail();
}).catch((_error) => {
})
})
it('test getTrialJobStatistics', () => {
// get 3 trial jobs (init, addCustomizedTrialJob, cancelTrialJobByUser)
return nniManager.getTrialJobStatistics().then(function (trialJobStatistics) {
expect(trialJobStatistics.length).to.be.equal(2);
if (trialJobStatistics[0].trialJobStatus === 'WAITING') {
expect(trialJobStatistics[0].trialJobNumber).to.be.equal(2);
expect(trialJobStatistics[1].trialJobNumber).to.be.equal(1);
}
else {
expect(trialJobStatistics[1].trialJobNumber).to.be.equal(2);
expect(trialJobStatistics[0].trialJobNumber).to.be.equal(1);
}
}).catch((error) => {
assert.fail(error);
})
})
it('test addCustomizedTrialJob reach maxTrialNumber', () => {
// test currSubmittedTrialNum reach maxTrialNumber
return nniManager.addCustomizedTrialJob('"hyperParam"').then(() => {
nniManager.getTrialJobStatistics().then(function (trialJobStatistics) {
if (trialJobStatistics[0].trialJobStatus === 'WAITING')
expect(trialJobStatistics[0].trialJobNumber).to.be.equal(2);
else
expect(trialJobStatistics[1].trialJobNumber).to.be.equal(2);
})
}).catch((error) => {
assert.fail(error);
})
})
//it('test resumeExperiment', async () => {
//TODO: add resume experiment unit test
//})
}) | the_stack |
import React, { Component } from 'react'
import {
Form,
Upload,
Icon,
Modal,
Input,
Select,
Switch,
Button,
InputNumber,
Row,
Col
} from 'antd'
import { FormComponentProps } from 'antd/lib/form'
import axios from 'axios'
import { getUploadUrl } from '../../../../api/constants'
import Category from '../../../../class/Category'
import {
Spec,
SPEC_TYPE_BASE,
SPEC_TYPE_MODIFY
} from '../../../../class/goodsTypes'
import './GoodsForm.less'
const FormItem = Form.Item
const Option = Select.Option
const TAG = 'GoodsForm'
type PicturesWallProps = {
onChange?: Function
}
// note
// 自定义或第三方的表单控件,也可以与 Form 组件一起使用。只要该组件遵循以下的约定:
// 提供受控属性 value 或其它与 valuePropName 的值同名的属性。
// 提供 onChange 事件或 trigger 的值同名的事件。
// 不能是函数式组件。
export class PicturesWall extends React.Component<PicturesWallProps, any> {
static getDerivedStateFromProps(nextProps) {
// Should be a controlled component.
if ('value' in nextProps) {
return {
fileList: nextProps.value
}
}
return null
}
constructor(props) {
super(props)
const value = props.value || []
this.state = {
fileList: value,
previewVisible: false,
previewImage: ''
}
}
handleCancel = () => this.setState({ previewVisible: false })
handlePreview = file => {
this.setState({
previewImage: file.url || file.thumbUrl,
previewVisible: true
})
}
handleChange = ({ fileList }) => {
console.log(fileList)
this.setState({ fileList })
this.props.onChange(
fileList.map(item => {
if (item.originFileObj && item.originFileObj.response) {
return {
name: item.originFileObj.response.data.name,
objectId: item.originFileObj.response.data.objectId,
uid: item.originFileObj.response.data.objectId,
url: item.originFileObj.response.data.url,
status: 'done'
}
}
return item
})
)
}
render() {
const { previewVisible, previewImage, fileList } = this.state
const uploadButton = (
<div>
<Icon type="plus" />
<div className="ant-upload-text">Upload</div>
</div>
)
return (
<div className="clearfix">
<Upload
listType="picture-card"
fileList={fileList}
onPreview={this.handlePreview}
supportServerRender
customRequest={({ file, onSuccess, onError }) => {
let formData = new FormData()
formData.append('file', file)
axios
.post(getUploadUrl(file.name), formData, {
headers: {
'X-LC-Id': 'DpnvHL3ttpjzk5UvHnSEedNo-gzGzoHsz',
'X-LC-Key': 'vGLWcKIk9nh1udRwF44o1AsS'
}
})
.then(data => {
file.response = data
onSuccess(null, file)
})
.catch(() => onError())
}}
onChange={this.handleChange}
>
{fileList.length >= 3 ? null : uploadButton}
</Upload>
<Modal
visible={previewVisible}
footer={null}
onCancel={this.handleCancel}
>
<img alt="example" style={{ width: '100%' }} src={previewImage} />
</Modal>
</div>
)
}
}
interface GoodsFormProps extends FormComponentProps {
categoryList: Array<Category>
visible: boolean
onCancel(): void
onOK(category: Category): void
}
const VALIDATE_MSG = '规格中存在空的名称、价格或者存在没有子规格,请检查'
const initialState = {
specValidateStatus: true
}
type GoodsFormState = Readonly<typeof initialState>
const CollectionCreateForm = Form.create()(
class GoodsForm extends Component<GoodsFormProps, {}> {
state: GoodsFormState = initialState
remove = (k: string) => {
const { form } = this.props
let spec = form.getFieldValue('spec') as Array<Spec>
spec = spec.filter(item => item.objectId !== k)
form.setFieldsValue({
spec
})
}
add = () => {
const { form } = this.props
form.getFieldDecorator(`spec`, { initialValue: [] })
const spec = form.getFieldValue('spec') as Array<Spec>
let id = 0
while (this.getID(id.toString(), true)) {
id++
}
spec.push({
objectId: id.toString()
})
form.setFieldsValue({
spec
})
}
getID = (id: string, isMain: boolean): boolean => {
const { form } = this.props
form.getFieldDecorator(`spec`, { initialValue: [] })
const spec = form.getFieldValue('spec') as Array<Spec>
let hasExisted = false
spec.map(item => {
if (isMain) {
// 检查父规格
if (item.objectId === id) {
hasExisted = true
}
} else {
// 检查子规格
if (item.subSpecs) {
item.subSpecs.map(subItem => {
if (subItem.objectId === id) {
hasExisted = true
}
})
}
}
})
return hasExisted
}
addSubSpec = (k: string) => {
const { form } = this.props
const spec = form.getFieldValue(`spec`) as Array<Spec>
const thisSpec = _getSpec(spec, k)
const subSpecs = thisSpec.subSpecs ? thisSpec.subSpecs : []
let subID = 0
while (this.getID(subID.toString(), false)) {
subID++
}
subSpecs.push({
objectId: subID.toString(),
type: SPEC_TYPE_MODIFY
})
let nextSpec = spec.map(item => {
if (item.objectId === k) {
return {
...item,
subSpecs
}
}
return item
})
form.setFieldsValue({
spec: nextSpec
})
}
removeSubSpec = (k: string, sk: string) => {
const { form } = this.props
const spec = form.getFieldValue(`spec`) as Array<Spec>
const thisSpec = _getSpec(spec, k)
if (!thisSpec || !thisSpec.subSpecs) {
return
}
let nextSpecs = spec.map(item => {
if (item.objectId === k) {
item.subSpecs = item.subSpecs.filter(item => item.objectId !== sk)
}
return item
})
form.setFieldsValue({
spec: nextSpecs
})
}
getSubSpec = (k: string) => {
const { form } = this.props
const { getFieldValue } = form
let spec = getFieldValue(`spec`) as Array<Spec>
const thisSpec = _getSpec(spec, k)
if (!thisSpec.subSpecs) {
return null
}
const subKeys = thisSpec.subSpecs
const subFormItems = subKeys.map(sk => (
<Row gutter={8} key={`${k}${sk.objectId}`}>
<Col span={8}>
<Input
placeholder="子规格名称"
onChange={e => {
this.handleValueChanged('name', e.target.value, k, sk.objectId)
}}
onBlur={this.handleBlurChanged}
value={sk.name}
/>
</Col>
<Col span={8}>
<InputNumber
style={{ width: '100%' }}
placeholder="子规格价格"
onChange={e => {
this.handleValueChanged('price', e, k, sk.objectId)
}}
onBlur={this.handleBlurChanged}
value={sk.price}
/>
</Col>
<Col span={8}>
<Switch
checkedChildren="基准价"
unCheckedChildren="修饰价"
onChange={e => {
this.handleValueChanged(
'type',
e ? SPEC_TYPE_BASE : SPEC_TYPE_MODIFY,
k,
sk.objectId
)
}}
checked={sk.type === SPEC_TYPE_BASE}
/>
<Icon
style={{ marginLeft: '8px' }}
className="dynamic-delete-button"
type="minus-circle-o"
onClick={() => this.removeSubSpec(k, sk.objectId)}
/>
</Col>
</Row>
))
return subFormItems
}
handleValueChanged = (
key: string,
value: any,
id: string,
subID?: string
) => {
const { form } = this.props
const { getFieldValue } = form
const spec = getFieldValue('spec') as Array<Spec>
const nextSpec = spec.map(item => {
if (item.objectId === id) {
if (!subID) {
// 更新父规格
item[key] = value
} else {
// 更新子规格
item.subSpecs = item.subSpecs.map(subItem => {
if (subItem.objectId === subID) {
subItem[key] = value
}
return subItem
})
}
}
return item
})
form.setFieldsValue({
spec: nextSpec
})
}
handleBlurChanged = () => {
const { form } = this.props
const { getFieldValue } = form
const spec = getFieldValue('spec') as Array<Spec>
let passed = true
spec.map(item => {
if (item.subSpecs && item.subSpecs.length > 0) {
item.subSpecs.map(subItem => {
if (!subItem.name || isNaN(subItem.price)) {
passed = false
}
})
} else {
passed = false
}
if (!item.name) {
passed = false
}
return item
})
this.setState({
specValidateStatus: passed
} as GoodsFormState)
return passed
}
render() {
const { categoryList, visible, onCancel, onOK, form } = this.props
const { getFieldDecorator, getFieldValue } = form
getFieldDecorator('spec', { initialValue: [] })
const spec = getFieldValue('spec') as Array<Spec>
const formItems = spec.map(k => {
const subFormItem = this.getSubSpec(k.objectId)
return (
<FormItem
label="规格"
required={false}
key={k.objectId}
validateStatus={this.state.specValidateStatus ? 'success' : 'error'}
help={this.state.specValidateStatus ? '' : VALIDATE_MSG}
>
<Row gutter={8} key={`specRow${k.objectId}`}>
<Col span={12}>
<Input
placeholder="规格名称"
onChange={e => {
this.handleValueChanged('name', e.target.value, k.objectId)
}}
onBlur={this.handleBlurChanged}
value={k.name}
/>
</Col>
<Col span={12}>
<Icon
className="dynamic-delete-button"
type="minus-circle-o"
onClick={() => this.remove(k.objectId)}
/>
<Button
type="primary"
onClick={() => this.addSubSpec(k.objectId)}
style={{ marginLeft: '8px' }}
>
添加子规格
</Button>
</Col>
</Row>
{subFormItem}
</FormItem>
)
})
return (
<Modal
visible={visible}
onCancel={onCancel}
onOk={() => {
if (this.handleBlurChanged()) {
let category = this._rebuildFormValues()
onOK(category)
}
}}
>
<Form>
<FormItem label="商品图片">
{getFieldDecorator('images', {
initialValue: [],
rules: [
{
required: true,
message: '至少上传一张商品图片'
}
]
})(<PicturesWall />)}
</FormItem>
<FormItem label="商品名称">
{getFieldDecorator('title', {
rules: [
{
required: true,
message: '名称为必填项目'
}
]
})(<Input />)}
</FormItem>
{formItems.length === 0 ? (
<FormItem label="商品价格">
{getFieldDecorator('price', {
validateTrigger: ['onChange', 'onBlur'],
rules: [
{
required: true,
whitespace: true,
message: '请输入价格'
}
]
})(
<InputNumber
style={{ width: '100%' }}
placeholder="商品价格"
/>
)}
</FormItem>
) : null}
{formItems}
<FormItem>
<Button type="dashed" onClick={this.add} style={{ width: '60%' }}>
<Icon type="plus" /> 添加规格
</Button>
</FormItem>
<FormItem label="商品描述">
{getFieldDecorator('desc', {
rules: [
{
required: true,
message: '描述为必填项目'
}
]
})(<Input />)}
</FormItem>
<FormItem label="商品分类">
{getFieldDecorator('category', {
rules: [{ required: true, message: '选商品分类啊' }]
})(
<Select placeholder="商品分类">
{function() {
return categoryList.map(item => {
return (
<Option key={item.objectId} value={item.objectId}>
{item.name}
</Option>
)
})
}.call(this)}
</Select>
)}
</FormItem>
<FormItem label="立即上架">
{getFieldDecorator('display', {
initialValue: true
})(<Switch defaultChecked />)}
</FormItem>
</Form>
</Modal>
)
}
private _rebuildFormValues = (): Category => {
const { categoryList, form } = this.props
const { getFieldValue } = form
let cid = getFieldValue('category')
let result = categoryList.filter(item => cid === item.objectId)
if (result.length > 0) {
return result[0]
}
return null
}
}
)
function _getSpec(array: Array<Spec>, id: string): Spec {
let result = array.filter(item => item.objectId === id)
return result.length > 0 ? result[0] : null
}
export default CollectionCreateForm | the_stack |
import {ApiResult, ObjectWithEtag} from "helpers/api_request_builder";
import _ from "lodash";
import m from "mithril";
import {PipelineGroup} from "models/admin_pipelines/admin_pipelines";
import {PipelineGroupCRUD} from "models/admin_pipelines/pipeline_groups_crud";
import {pipelineGroupJSON} from "models/admin_pipelines/specs/admin_pipelines_spec";
import {ModalManager} from "views/components/modal/modal_manager";
import {TestHelper} from "views/pages/spec/test_helper";
import {EditPipelineGroupModal} from "../edit_pipeline_group_modal";
describe('EditPipelineGroupModal', () => {
let modal: EditPipelineGroupModal;
let testHelper: TestHelper;
function mount(containsPipelinesRemotely: boolean = false) {
const pipelineGroup = PipelineGroup.fromJSON(pipelineGroupJSON());
modal = new EditPipelineGroupModal(pipelineGroup, "etag", [], [], _.noop, containsPipelinesRemotely);
modal.render();
m.redraw.sync();
testHelper = new TestHelper().forModal();
}
afterEach(() => {
ModalManager.closeAll();
});
it('should render text field and label for pipeline group name', () => {
mount();
expect(testHelper.byTestId("form-field-label-pipeline-group-name")).toBeInDOM();
expect(testHelper.byTestId("form-field-label-pipeline-group-name")).toHaveText("Pipeline group name");
expect(testHelper.byTestId("form-field-input-pipeline-group-name")).toBeInDOM();
expect(testHelper.byTestId("form-field-input-pipeline-group-name")).toHaveValue("pipeline-group");
expect(testHelper.byTestId("form-field-input-pipeline-group-name")).not.toBeDisabled();
});
it('should render pipeline disabled group name with tooltip', () => {
mount(true);
expect(testHelper.byTestId("info-tooltip")).toBeInDOM();
expect(testHelper.byTestId("info-tooltip")).toHaveText("Cannot rename pipeline group as it contains remotely defined pipelines");
expect(testHelper.byTestId("form-field-input-pipeline-group-name")).toBeDisabled();
});
describe('userPermissions', () => {
beforeEach(() => {
mount();
});
it('should render open collapsible panel', () => {
expect(testHelper.byTestId("collapse-header", testHelper.byTestId("users-permissions-collapse"))).toContainText("User permissions");
expect(testHelper.byTestId("add-user-permission", testHelper.byTestId("users-permissions-collapse"))).toBeInDOM();
expect(testHelper.byTestId("add-user-permission", testHelper.byTestId("users-permissions-collapse"))).toHaveText("Add");
expect(testHelper.byTestId("collapse-body", testHelper.byTestId("users-permissions-collapse"))).toBeInDOM();
});
it('should render collapsible panel with user permissions table', () => {
expect(testHelper.byTestId("users-permissions")).toBeInDOM();
expect(testHelper.byTestId("users-permissions")).toContainHeaderCells(["Name", "View", "Operate", "Admin", ""]);
const permissions = testHelper.allByTestId("table-row", testHelper.byTestId("users-permissions"));
const row1 = permissions[0] as HTMLElement;
expect((testHelper.byTestId("user-name", row1) as HTMLInputElement).value).toBe("user1");
expect((testHelper.byTestId("view-permission", row1) as HTMLInputElement)).toBeChecked();
expect((testHelper.byTestId("operate-permission", row1) as HTMLInputElement)).not.toBeChecked();
expect((testHelper.byTestId("admin-permission", row1) as HTMLInputElement)).not.toBeChecked();
const row2 = permissions[1] as HTMLElement;
expect((testHelper.byTestId("user-name", row2) as HTMLInputElement).value).toBe("superUser");
expect((testHelper.byTestId("view-permission", row2) as HTMLInputElement)).toBeChecked();
expect((testHelper.byTestId("view-permission", row2) as HTMLInputElement)).toBeDisabled();
expect((testHelper.byTestId("operate-permission", row2) as HTMLInputElement)).toBeChecked();
expect((testHelper.byTestId("admin-permission", row2) as HTMLInputElement)).not.toBeChecked();
const row3 = permissions[2] as HTMLElement;
expect((testHelper.byTestId("user-name", row3) as HTMLInputElement).value).toBe("admin");
expect((testHelper.byTestId("view-permission", row3) as HTMLInputElement)).toBeChecked();
expect((testHelper.byTestId("view-permission", row3) as HTMLInputElement)).toBeDisabled();
expect((testHelper.byTestId("operate-permission", row3) as HTMLInputElement)).toBeChecked();
expect((testHelper.byTestId("operate-permission", row3) as HTMLInputElement)).toBeDisabled();
expect((testHelper.byTestId("admin-permission", row3) as HTMLInputElement)).toBeChecked();
});
it('should remove user on click of remove button', () => {
expect(testHelper.byTestId("user-permission-delete")).toBeInDOM();
expect(testHelper.allByTestId("user-permission-delete").length).toBe(3);
const userPermission = testHelper.allByTestId("user-permission-delete")[0];
testHelper.click(userPermission);
expect(testHelper.allByTestId("table-row", testHelper.byTestId("users-permissions")).length).toBe(2);
expect(testHelper.allByTestId("table-row", userPermission)).not.toBeInDOM();
});
it('should add user on click of add button', () => {
testHelper.click(testHelper.byTestId("add-user-permission"));
expect(testHelper.allByTestId("table-row", testHelper.byTestId("users-permissions")).length).toBe(4);
const newRolePermission = testHelper.allByTestId("table-row", testHelper.byTestId("users-permissions"))[3];
expect((testHelper.byTestId("user-name", newRolePermission) as HTMLInputElement).value).toBe("");
expect((testHelper.byTestId("view-permission", newRolePermission) as HTMLInputElement)).toBeChecked();
expect((testHelper.byTestId("operate-permission", newRolePermission) as HTMLInputElement)).not.toBeChecked();
expect((testHelper.byTestId("admin-permission", newRolePermission) as HTMLInputElement)).not.toBeChecked();
});
it('should open collapse click of add button', () => {
const collapsibleForUserPermissions = testHelper.byTestId("collapse-header", testHelper.byTestId("users-permissions-collapse"));
testHelper.click(collapsibleForUserPermissions);
expect(testHelper.byTestId("collapse-body", testHelper.byTestId("users-permissions-collapse"))).toBeHidden();
testHelper.click(testHelper.byTestId("add-user-permission"));
expect(testHelper.byTestId("collapse-body", testHelper.byTestId("users-permissions-collapse"))).not.toBeHidden();
});
it('should disable checkboxes for view permissions on enable of operate permission', () => {
testHelper.clickByTestId("add-user-permission");
const operateUserPermissions = testHelper.allByTestId("table-row", testHelper.byTestId("users-permissions"))[3] as HTMLElement;
expect(testHelper.byTestId("view-permission", operateUserPermissions)).not.toBeDisabled();
expect(testHelper.byTestId("view-permission", operateUserPermissions)).toBeChecked();
expect(testHelper.byTestId("operate-permission", operateUserPermissions)).not.toBeDisabled();
expect(testHelper.byTestId("operate-permission", operateUserPermissions)).not.toBeChecked();
testHelper.click(testHelper.byTestId("operate-permission", operateUserPermissions));
expect(testHelper.byTestId("view-permission", operateUserPermissions)).toBeDisabled();
expect(testHelper.byTestId("view-permission", operateUserPermissions)).toBeChecked();
expect(testHelper.byTestId("operate-permission", operateUserPermissions)).toBeChecked();
});
it('should disable checkboxes for view and operate permissions on enable of admin permission', () => {
testHelper.clickByTestId("add-user-permission");
const operateUserPermissions = testHelper.allByTestId("table-row", testHelper.byTestId("users-permissions"))[3] as HTMLElement;
expect(testHelper.byTestId("view-permission", operateUserPermissions)).not.toBeDisabled();
expect(testHelper.byTestId("view-permission", operateUserPermissions)).toBeChecked();
expect(testHelper.byTestId("operate-permission", operateUserPermissions)).not.toBeDisabled();
expect(testHelper.byTestId("operate-permission", operateUserPermissions)).not.toBeChecked();
expect(testHelper.byTestId("admin-permission", operateUserPermissions)).not.toBeDisabled();
expect(testHelper.byTestId("admin-permission", operateUserPermissions)).not.toBeChecked();
testHelper.click(testHelper.byTestId("admin-permission", operateUserPermissions));
expect(testHelper.byTestId("view-permission", operateUserPermissions)).toBeDisabled();
expect(testHelper.byTestId("view-permission", operateUserPermissions)).toBeChecked();
expect(testHelper.byTestId("operate-permission", operateUserPermissions)).toBeDisabled();
expect(testHelper.byTestId("operate-permission", operateUserPermissions)).toBeChecked();
expect(testHelper.byTestId("admin-permission", operateUserPermissions)).not.toBeDisabled();
expect(testHelper.byTestId("admin-permission", operateUserPermissions)).toBeChecked();
});
it("should keep only view permission on the unchecked of admin permission", () => {
testHelper.clickByTestId("add-user-permission");
const userPermissions = testHelper.allByTestId("table-row", testHelper.byTestId("users-permissions"))[3] as HTMLElement;
//for enabling admin
testHelper.click(testHelper.byTestId("admin-permission", userPermissions));
//for disabling admin
testHelper.click(testHelper.byTestId("admin-permission", userPermissions));
expect(testHelper.byTestId("operate-permission", userPermissions)).not.toBeDisabled();
expect(testHelper.byTestId("operate-permission", userPermissions)).not.toBeChecked();
expect(testHelper.byTestId("view-permission", userPermissions)).not.toBeDisabled();
expect(testHelper.byTestId("view-permission", userPermissions)).toBeChecked();
});
});
describe('rolePermissions', () => {
beforeEach(() => {
mount();
});
it('should render open collapsible panel', () => {
expect(testHelper.byTestId("collapse-header", testHelper.byTestId("roles-permissions-collapse"))).toContainText("Role permissions");
expect(testHelper.byTestId("add-role-permission", testHelper.byTestId("roles-permissions-collapse"))).toBeInDOM();
expect(testHelper.byTestId("add-role-permission", testHelper.byTestId("roles-permissions-collapse"))).toHaveText("Add");
expect(testHelper.byTestId("collapse-body", testHelper.byTestId("roles-permissions-collapse"))).toBeInDOM();
});
it('should render collapsible panel with role permissions table', () => {
expect(testHelper.byTestId("roles-permissions")).toBeInDOM();
expect(testHelper.byTestId("roles-permissions")).toContainHeaderCells(["Name", "View", "Operate", "Admin", ""]);
const permissions = testHelper.allByTestId("table-row", testHelper.byTestId("roles-permissions"));
const row1 = permissions[0] as HTMLElement;
expect((testHelper.byTestId("role-name", row1) as HTMLInputElement).value).toBe("role1");
expect((testHelper.byTestId("view-permission", row1) as HTMLInputElement)).toBeChecked();
expect((testHelper.byTestId("operate-permission", row1) as HTMLInputElement)).not.toBeChecked();
expect((testHelper.byTestId("admin-permission", row1) as HTMLInputElement)).not.toBeChecked();
const row2 = permissions[1] as HTMLElement;
expect((testHelper.byTestId("role-name", row2) as HTMLInputElement).value).toBe("role2");
expect((testHelper.byTestId("view-permission", row2) as HTMLInputElement)).toBeChecked();
expect((testHelper.byTestId("view-permission", row2) as HTMLInputElement)).toBeDisabled();
expect((testHelper.byTestId("operate-permission", row2) as HTMLInputElement)).toBeChecked();
expect((testHelper.byTestId("admin-permission", row2) as HTMLInputElement)).not.toBeChecked();
const row3 = permissions[2] as HTMLElement;
expect((testHelper.byTestId("role-name", row3) as HTMLInputElement).value).toBe("admin");
expect((testHelper.byTestId("view-permission", row3) as HTMLInputElement)).toBeChecked();
expect((testHelper.byTestId("view-permission", row3) as HTMLInputElement)).toBeDisabled();
expect((testHelper.byTestId("operate-permission", row3) as HTMLInputElement)).toBeChecked();
expect((testHelper.byTestId("operate-permission", row3) as HTMLInputElement)).toBeDisabled();
expect((testHelper.byTestId("admin-permission", row3) as HTMLInputElement)).toBeChecked();
});
it('should remove role on click of remove button', () => {
expect(testHelper.byTestId("role-permission-delete")).toBeInDOM();
expect(testHelper.allByTestId("role-permission-delete").length).toBe(3);
const rolePermission = testHelper.allByTestId("role-permission-delete")[0];
testHelper.click(rolePermission);
expect(testHelper.allByTestId("table-row", testHelper.byTestId("roles-permissions")).length).toBe(2);
expect(testHelper.allByTestId("table-row", rolePermission)).not.toBeInDOM();
});
it('should add role on click of add button', () => {
testHelper.click(testHelper.byTestId("add-role-permission"));
expect(testHelper.allByTestId("table-row", testHelper.byTestId("roles-permissions")).length).toBe(4);
const newRolePermission = testHelper.allByTestId("table-row", testHelper.byTestId("roles-permissions"))[3];
expect((testHelper.byTestId("role-name", newRolePermission) as HTMLInputElement).value).toBe("");
expect((testHelper.byTestId("view-permission", newRolePermission) as HTMLInputElement)).toBeChecked();
expect((testHelper.byTestId("operate-permission", newRolePermission) as HTMLInputElement)).not.toBeChecked();
expect((testHelper.byTestId("admin-permission", newRolePermission) as HTMLInputElement)).not.toBeChecked();
});
it('should open role collapsible panel click of add button', () => {
const collapsibleForRolePermissions = testHelper.byTestId("collapse-header", testHelper.byTestId("roles-permissions-collapse"));
testHelper.click(collapsibleForRolePermissions);
expect(testHelper.byTestId("collapse-body", testHelper.byTestId("roles-permissions-collapse"))).toBeHidden();
testHelper.click(testHelper.byTestId("add-role-permission"));
expect(testHelper.byTestId("collapse-body", testHelper.byTestId("roles-permissions-collapse"))).not.toBeHidden();
});
it('should disable checkboxes for view permissions on enable of operate permission', () => {
testHelper.clickByTestId("add-role-permission");
const operateRolePermissions = testHelper.allByTestId("table-row", testHelper.byTestId("roles-permissions"))[3] as HTMLElement;
expect(testHelper.byTestId("view-permission", operateRolePermissions)).not.toBeDisabled();
expect(testHelper.byTestId("view-permission", operateRolePermissions)).toBeChecked();
expect(testHelper.byTestId("operate-permission", operateRolePermissions)).not.toBeDisabled();
expect(testHelper.byTestId("operate-permission", operateRolePermissions)).not.toBeChecked();
testHelper.click(testHelper.byTestId("operate-permission", operateRolePermissions));
expect(testHelper.byTestId("view-permission", operateRolePermissions)).toBeDisabled();
expect(testHelper.byTestId("view-permission", operateRolePermissions)).toBeChecked();
expect(testHelper.byTestId("operate-permission", operateRolePermissions)).toBeChecked();
});
it('should disable checkboxes for view and operate permissions on enable of admin permission', () => {
testHelper.clickByTestId("add-role-permission");
const operateRolePermissions = testHelper.allByTestId("table-row", testHelper.byTestId("roles-permissions"))[3] as HTMLElement;
expect(testHelper.byTestId("view-permission", operateRolePermissions)).not.toBeDisabled();
expect(testHelper.byTestId("view-permission", operateRolePermissions)).toBeChecked();
expect(testHelper.byTestId("operate-permission", operateRolePermissions)).not.toBeDisabled();
expect(testHelper.byTestId("operate-permission", operateRolePermissions)).not.toBeChecked();
expect(testHelper.byTestId("admin-permission", operateRolePermissions)).not.toBeDisabled();
expect(testHelper.byTestId("admin-permission", operateRolePermissions)).not.toBeChecked();
testHelper.click(testHelper.byTestId("admin-permission", operateRolePermissions));
expect(testHelper.byTestId("view-permission", operateRolePermissions)).toBeDisabled();
expect(testHelper.byTestId("view-permission", operateRolePermissions)).toBeChecked();
expect(testHelper.byTestId("operate-permission", operateRolePermissions)).toBeDisabled();
expect(testHelper.byTestId("operate-permission", operateRolePermissions)).toBeChecked();
expect(testHelper.byTestId("admin-permission", operateRolePermissions)).not.toBeDisabled();
expect(testHelper.byTestId("admin-permission", operateRolePermissions)).toBeChecked();
});
it("should keep only view permission on the unchecked of admin permission", () => {
testHelper.clickByTestId("add-role-permission");
const rolePermissions = testHelper.allByTestId("table-row", testHelper.byTestId("roles-permissions"))[3] as HTMLElement;
//for enabling admin
testHelper.click(testHelper.byTestId("admin-permission", rolePermissions));
//for disabling admin
testHelper.click(testHelper.byTestId("admin-permission", rolePermissions));
expect(testHelper.byTestId("operate-permission", rolePermissions)).not.toBeDisabled();
expect(testHelper.byTestId("operate-permission", rolePermissions)).not.toBeChecked();
expect(testHelper.byTestId("view-permission", rolePermissions)).not.toBeDisabled();
expect(testHelper.byTestId("view-permission", rolePermissions)).toBeChecked();
});
});
it("should update pipeline group on click of save button", () => {
mount();
spyOn(PipelineGroupCRUD, "update").and.returnValue(new Promise<ApiResult<ObjectWithEtag<PipelineGroup>>>((resolve) => {
resolve(ApiResult.success("", 200, new Map()).map<ObjectWithEtag<PipelineGroup>>(
() => {
return {
object: PipelineGroup.fromJSON(pipelineGroupJSON()),
etag: "some-etag"
} as ObjectWithEtag<PipelineGroup>;
}
));
}));
testHelper.click(testHelper.byTestId("save-pipeline-group"));
expect(PipelineGroupCRUD.update).toHaveBeenCalled();
});
it('should have save and cancel buttons', () => {
mount();
expect(testHelper.byTestId("cancel-button")).toBeInDOM();
expect(testHelper.byTestId("save-pipeline-group")).toBeInDOM();
});
it('should render errors on roles if any', () => {
const pipelineGroup = PipelineGroup.fromJSON(pipelineGroupJSON());
pipelineGroup.authorization().admin().errors().add('roles', 'Some roles are invalid');
modal = new EditPipelineGroupModal(pipelineGroup, "etag", [], [], _.noop, false);
modal.render();
m.redraw.sync();
testHelper = new TestHelper().forModal();
const element = testHelper.byTestId('errors-on-roles');
expect(element).toBeInDOM();
expect(testHelper.qa('li', element).length).toBe(1);
expect(testHelper.qa('li', element)[0].innerText).toBe('Some roles are invalid');
});
it('should render errors on users if any', () => {
const pipelineGroup = PipelineGroup.fromJSON(pipelineGroupJSON());
pipelineGroup.authorization().admin().errors().add('users', 'Some users are invalid');
modal = new EditPipelineGroupModal(pipelineGroup, "etag", [], [], _.noop, false);
modal.render();
m.redraw.sync();
testHelper = new TestHelper().forModal();
const element = testHelper.byTestId('errors-on-users');
expect(element).toBeInDOM();
expect(testHelper.qa('li', element).length).toBe(1);
expect(testHelper.qa('li', element)[0].innerText).toBe('Some users are invalid');
});
}); | the_stack |
import * as fse from 'fs-extra';
import * as path from 'path';
import { runWithTestActionContext, TestInput } from 'vscode-azureextensiondev';
import { FuncVersion, getRandomHexString, initProjectForVSCode, ProjectLanguage } from '../../extension.bundle';
import { cleanTestWorkspace, testFolderPath } from '../global.test';
import { getCSharpValidateOptions, getCustomValidateOptions, getFSharpValidateOptions, getJavaScriptValidateOptions, getJavaValidateOptions, getPowerShellValidateOptions, getPythonValidateOptions, getTypeScriptValidateOptions, IValidateProjectOptions, validateProject } from './validateProject';
suite('Init Project For VS Code', function (this: Mocha.Suite): void {
this.timeout(30 * 1000);
suiteSetup(async () => {
await cleanTestWorkspace();
});
test('JavaScript', async () => {
await initAndValidateProject({ ...getJavaScriptValidateOptions(), mockFiles: [['HttpTriggerJs', 'index.js']] });
});
test('JavaScript with package.json', async () => {
await initAndValidateProject({ ...getJavaScriptValidateOptions(true /* hasPackageJson */), mockFiles: [['HttpTriggerJs', 'index.js'], 'package.json'] });
});
test('JavaScript with extensions.csproj', async () => {
const options: IValidateProjectOptions = getJavaScriptValidateOptions(true /* hasPackageJson */);
options.expectedSettings['files.exclude'] = { obj: true, bin: true };
await initAndValidateProject({ ...options, mockFiles: [['HttpTriggerJs', 'index.js'], 'package.json', 'extensions.csproj'] });
});
test('TypeScript', async () => {
await initAndValidateProject({ ...getTypeScriptValidateOptions(), mockFiles: [['HttpTrigger', 'index.ts'], 'tsconfig.json', 'package.json'] });
});
test('TypeScript with extensions.csproj', async () => {
const options: IValidateProjectOptions = getTypeScriptValidateOptions();
options.expectedSettings['files.exclude'] = { obj: true, bin: true };
await initAndValidateProject({ ...options, mockFiles: [['HttpTrigger', 'index.ts'], 'tsconfig.json', 'package.json', 'extensions.csproj'] });
});
test('C#', async () => {
const mockFiles: MockFile[] = [{ fsPath: 'test.csproj', contents: '<TargetFramework>netstandard2.0<\/TargetFramework><AzureFunctionsVersion>v2</AzureFunctionsVersion>' }];
await initAndValidateProject({ ...getCSharpValidateOptions('netstandard2.0', FuncVersion.v2), mockFiles });
});
test('C# with extensions.csproj', async () => {
const mockFiles: MockFile[] = ['extensions.csproj', { fsPath: 'test.csproj', contents: '<TargetFramework>netstandard2.0<\/TargetFramework><AzureFunctionsVersion>v2</AzureFunctionsVersion>' }];
await initAndValidateProject({ ...getCSharpValidateOptions('netstandard2.0', FuncVersion.v2, 2), mockFiles });
});
function getMockVenvPath(venvName: string): MockFilePath {
return process.platform === 'win32' ? [venvName, 'Scripts', 'activate'] : [venvName, 'bin', 'activate'];
}
test('Python no venv', async () => {
const mockFiles: MockFile[] = [['HttpTrigger', '__init__.py'], 'requirements.txt'];
await initAndValidateProject({ ...getPythonValidateOptions(undefined), mockFiles, inputs: [/skip/i] });
});
test('Python single venv', async () => {
const venvName: string = 'testEnv';
const mockFiles: MockFile[] = [['HttpTrigger', '__init__.py'], 'requirements.txt', getMockVenvPath(venvName)];
await initAndValidateProject({ ...getPythonValidateOptions(venvName), mockFiles });
});
test('Python multiple venvs', async () => {
const venvName: string = 'world';
const mockFiles: MockFile[] = [['HttpTrigger', '__init__.py'], 'requirements.txt', getMockVenvPath('hello'), getMockVenvPath(venvName)];
await initAndValidateProject({ ...getPythonValidateOptions(venvName), mockFiles, inputs: [venvName] });
});
test('Python with extensions.csproj', async () => {
const venvName: string = 'testEnv';
const options: IValidateProjectOptions = getPythonValidateOptions(venvName);
options.expectedTasks.push('extensions install');
options.expectedSettings['files.exclude'] = { obj: true, bin: true };
options.expectedSettings['azureFunctions.preDeployTask'] = 'func: extensions install';
const mockFiles: MockFile[] = [['HttpTrigger', '__init__.py'], 'requirements.txt', getMockVenvPath(venvName), 'extensions.csproj'];
await initAndValidateProject({ ...options, mockFiles });
});
test('F#', async () => {
const mockFiles: MockFile[] = [{ fsPath: 'test.fsproj', contents: '<TargetFramework>netstandard2.0<\/TargetFramework><AzureFunctionsVersion>v2</AzureFunctionsVersion>' }];
await initAndValidateProject({ ...getFSharpValidateOptions('netstandard2.0', FuncVersion.v2), mockFiles });
});
test('Java', async () => {
const appName: string = 'javaApp1';
const mockFiles: MockFile[] = [
{
fsPath: 'pom.xml',
contents: `<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<properties>
<functionAppName>${appName}</functionAppName>
</properties>
</project>`
},
{ fsPath: 'src', isDir: true }
];
await initAndValidateProject({ ...getJavaValidateOptions(appName), mockFiles });
});
test('PowerShell', async () => {
await initAndValidateProject({ ...getPowerShellValidateOptions(), mockFiles: [['HttpTriggerPS', 'run.ps1'], 'profile.ps1', 'requirements.psd1'] });
});
test('PowerShell with extensions.csproj', async () => {
const options: IValidateProjectOptions = getPowerShellValidateOptions();
options.expectedSettings['files.exclude'] = { obj: true, bin: true };
options.expectedSettings['azureFunctions.preDeployTask'] = 'func: extensions install';
await initAndValidateProject({ ...options, mockFiles: [['HttpTriggerPS', 'run.ps1'], 'profile.ps1', 'requirements.psd1', 'extensions.csproj'] });
});
test('Custom', async () => {
const mockFiles: MockFile[] = [{
fsPath: 'local.settings.json',
contents: {
IsEncrypted: false,
Values: {
FUNCTIONS_WORKER_RUNTIME: "custom",
AzureWebJobsStorage: ""
}
}
}];
await initAndValidateProject({ ...getCustomValidateOptions(), mockFiles });
});
test('Multi-language', async () => {
await initAndValidateProject({ ...getJavaScriptValidateOptions(), mockFiles: [['HttpTriggerTS', 'index.ts'], ['HttpTriggerCSX', 'run.csx']], inputs: [ProjectLanguage.JavaScript] });
});
test('Multi-function', async () => {
await initAndValidateProject({ ...getJavaScriptValidateOptions(), mockFiles: [['HttpTriggerJS1', 'index.js'], ['HttpTriggerJS2', 'index.js']] });
});
test('Existing extensions.json', async () => {
const mockFiles: MockFile[] = [{ fsPath: ['.vscode', 'extensions.json'], contents: { recommendations: ["testid"] } }];
const options: IInitProjectTestOptions = { ...getJavaScriptValidateOptions(), mockFiles, inputs: [ProjectLanguage.JavaScript] };
options.expectedExtensionRecs.push('testid');
await initAndValidateProject(options);
});
test('Invalid extensions.json', async () => {
const mockFiles: MockFile[] = [{ fsPath: ['.vscode', 'extensions.json'], contents: '{' }];
await initAndValidateProject({ ...getJavaScriptValidateOptions(), mockFiles, inputs: [ProjectLanguage.JavaScript, 'Yes'] });
});
test('Existing settings.json', async () => {
const mockFiles: MockFile[] = [{ fsPath: ['.vscode', 'settings.json'], contents: { "azureFunctions.testSetting": "testValue" } }];
const options: IInitProjectTestOptions = { ...getJavaScriptValidateOptions(), mockFiles, inputs: [ProjectLanguage.JavaScript] };
options.expectedSettings['azureFunctions.testSetting'] = 'testValue';
await initAndValidateProject(options);
});
test('Invalid settings.json', async () => {
const mockFiles: MockFile[] = [{ fsPath: ['.vscode', 'settings.json'], contents: '{' }];
await initAndValidateProject({ ...getJavaScriptValidateOptions(), mockFiles, inputs: [ProjectLanguage.JavaScript, 'Yes'] });
});
test('Existing tasks.json', async () => {
const mockFiles: MockFile[] = [{
fsPath: ['.vscode', 'tasks.json'],
contents: {
version: "2.0.0",
tasks: [
{
label: "hello world",
command: "echo 'hello world'",
type: "shell"
}
]
}
}];
const options: IInitProjectTestOptions = { ...getJavaScriptValidateOptions(), mockFiles, inputs: [ProjectLanguage.JavaScript] };
options.expectedTasks.push('hello world');
await initAndValidateProject(options);
});
test('Invalid tasks.json', async () => {
const mockFiles: MockFile[] = [{ fsPath: ['.vscode', 'tasks.json'], contents: '{' }];
await initAndValidateProject({ ...getJavaScriptValidateOptions(), mockFiles, inputs: [ProjectLanguage.JavaScript, 'Yes'] });
});
test('Overwrite existing task', async () => {
const mockFiles: MockFile[] = [{
fsPath: ['.vscode', 'tasks.json'],
contents: {
version: "2.0.0",
tasks: [
{
type: "func",
command: "host start"
}
]
}
}];
await initAndValidateProject({ ...getJavaScriptValidateOptions(), mockFiles, inputs: [ProjectLanguage.JavaScript, 'Overwrite'] });
});
test('Does not prompt to overwrite existing, identical task', async () => {
const mockFiles: MockFile[] = [{
fsPath: ['.vscode', 'tasks.json'],
contents: {
version: "2.0.0",
tasks: [
{
type: "func",
command: "host start",
problemMatcher: "$func-node-watch",
isBackground: true
}
]
}
}];
await initAndValidateProject({ ...getJavaScriptValidateOptions(), mockFiles, inputs: [ProjectLanguage.JavaScript] });
});
test('Overwrite multiple tasks', async () => {
const mockFiles: MockFile[] = ['package.json', {
fsPath: ['.vscode', 'tasks.json'],
contents: {
version: "2.0.0",
tasks: [
{
type: "func",
command: "host start"
},
{
type: "shell",
label: "npm install (functions)",
command: "whoops"
}
]
}
}];
await initAndValidateProject({ ...getJavaScriptValidateOptions(true /* hasPackageJson */), mockFiles, inputs: [ProjectLanguage.JavaScript, 'Overwrite'] });
});
test('Old tasks.json', async () => {
const mockFiles: MockFile[] = [{
fsPath: ['.vscode', 'tasks.json'],
contents: {
version: "1.0.0",
tasks: [
{
label: "hello world",
command: "echo 'hello world'",
type: "shell"
}
]
}
}];
await initAndValidateProject({ ...getJavaScriptValidateOptions(), mockFiles, inputs: [ProjectLanguage.JavaScript, 'Yes'] });
});
test('Existing launch.json', async () => {
const mockFiles: MockFile[] = [{
fsPath: ['.vscode', 'launch.json'],
contents: {
version: "0.2.0",
configurations: [
{
name: "Launch 1",
request: "attach",
type: "node"
}
]
}
}];
const options: IInitProjectTestOptions = { ...getJavaScriptValidateOptions(), mockFiles, inputs: [ProjectLanguage.JavaScript] };
options.expectedDebugConfigs.push('Launch 1');
await initAndValidateProject(options);
});
test('Invalid launch.json', async () => {
const mockFiles: MockFile[] = [{ fsPath: ['.vscode', 'launch.json'], contents: '{' }];
await initAndValidateProject({ ...getJavaScriptValidateOptions(), mockFiles, inputs: [ProjectLanguage.JavaScript, 'Yes'] });
});
test('Overwrite existing debug config', async () => {
const mockFiles: MockFile[] = [{
fsPath: ['.vscode', 'launch.json'],
contents: {
version: "0.2.0",
configurations: [
{
name: "Attach to Node Functions",
type: "node",
request: "attach"
}
]
}
}];
await initAndValidateProject({ ...getJavaScriptValidateOptions(), mockFiles, inputs: [ProjectLanguage.JavaScript] });
});
test('Old launch.json', async () => {
const mockFiles: MockFile[] = [{
fsPath: ['.vscode', 'launch.json'],
contents: {
version: "0.1.0",
configurations: [
{
name: "Launch 1",
request: "attach",
type: "node"
}
]
}
}];
await initAndValidateProject({ ...getJavaScriptValidateOptions(), mockFiles, inputs: [ProjectLanguage.JavaScript, 'Yes'] });
});
test('Invalid gitignore', async () => {
const mockFiles: MockFile[] = [{ fsPath: '.gitignore', contents: '.vscode' }];
await initAndValidateProject({ ...getJavaScriptValidateOptions(), mockFiles, inputs: [ProjectLanguage.JavaScript] });
});
});
type MockFilePath = string | string[];
type MockFile = MockFilePath | { fsPath: MockFilePath; contents?: string | object; isDir?: boolean };
interface IInitProjectTestOptions extends IValidateProjectOptions {
mockFiles?: MockFile[];
inputs?: (string | RegExp | TestInput)[];
}
async function initAndValidateProject(options: IInitProjectTestOptions): Promise<void> {
const projectPath: string = path.join(testFolderPath, getRandomHexString());
const mockFiles: MockFile[] = options.mockFiles || [];
mockFiles.push('local.settings.json', 'host.json', '.funcignore', '.gitignore', { fsPath: '.git', isDir: true });
await Promise.all(mockFiles.map(async mockFile => {
mockFile = typeof mockFile === 'string' || Array.isArray(mockFile) ? { fsPath: mockFile } : mockFile;
const subPaths: string[] = typeof mockFile.fsPath === 'string' ? [mockFile.fsPath] : mockFile.fsPath;
const fullPath: string = path.join(projectPath, ...subPaths);
mockFile.isDir ? await fse.ensureDir(fullPath) : await fse.ensureFile(fullPath);
if (typeof mockFile.contents === 'object') {
await fse.writeJSON(fullPath, mockFile.contents);
} else if (mockFile.contents) {
await fse.writeFile(fullPath, mockFile.contents);
}
}));
await runWithTestActionContext('initProject', async context => {
await context.ui.runWithInputs(options.inputs || [], async () => {
await initProjectForVSCode(context, projectPath);
});
});
await validateProject(projectPath, options);
} | the_stack |
'use strict';
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as upath from 'upath';
import * as dateFns from 'date-fns';
import * as nls from 'vscode-nls';
import { items, memoConfigure } from './memoConfigure';
const localize = nls.config({ messageFormat: nls.MessageFormat.file })();
export class memoEdit extends memoConfigure {
public memoListChannel: vscode.OutputChannel;
constructor() {
super();
this.memoListChannel = vscode.window.createOutputChannel("Memo List");
}
/**
* Edit
*/
public async Edit() {
this.readConfig();
let items: items[] = [];
let memodir = upath.normalizeTrim(this.memodir);
let list: string[] = [];
let dirlist: string[] = [];
let openMarkdownPreview: boolean = this.memoEditOpenMarkdown;
let listMarkdownPreview: boolean = this.memoEditPreviewMarkdown;
let openMarkdownPreviewUseMPE: boolean = this.openMarkdownPreviewUseMPE;
let isEnabled: boolean = false; // Flag: opened Markdown Preview (Markdown Enhance Preview)
let listDisplayExtname: string[] = this.memoListDisplayExtname;
// console.log("memodir = ", memodir)
this.memoListChannel.clear();
//
// Markdown Preview Enhanced のチェック
//
if (listMarkdownPreview) {
try {
vscode.extensions.getExtension('shd101wyy.markdown-preview-enhanced').id;
} catch (err) {
listMarkdownPreview = false;
}
}
try {
list = readdirRecursively(memodir);
} catch(err) {
console.log('err =', err);
}
// let listDisplayExtname: string[] = ["md", "txt"];
// listDisplayExtname = [];
// listDisplayExtname が空の場合は、強制的に .md のみ対象にする
if (listDisplayExtname.length == 0 ) {
listDisplayExtname = ["md"];
}
// 取得したファイル一覧を整形
list = list.filter((v) => {
for (const value of listDisplayExtname){
// console.log(value);
if (upath.extname(v).match("." + value)) {
// console.log(v);
return v;
}
}
}).map((v) => { // .map で配列の中身を操作してから新しい配列を作成する
// memodir を削除したパス名を返す
return (v.split(upath.sep).splice(memodir.split(upath.sep).length, v.split(upath.sep).length).join(upath.sep));
});
// console.log(listDisplayExtname);
// メニューアイテムの作成
for (let index = 0; index < list.length; index++) {
if (list[index] == '') {
break;
}
let filename: string = upath.normalize(upath.join(memodir, list[index]));
let fileStat: fs.Stats = fs.statSync(filename);
let statBirthtime = this.memoEditDispBtime ? (typeof fileStat === 'string') ? "" : dateFns.format(fileStat.birthtime, 'MMM dd HH:mm, yyyy ') : "";
let statMtime = this.memoEditDispBtime ? (typeof fileStat === 'string') ? "" : dateFns.format(fileStat.mtime, 'MMM dd HH:mm, yyyy ') : "";
let array = fs.readFileSync(filename).toString().split('\n');
// 先頭一行目だけなので、readline で代替してみたが、遅い...
// let readFirstLine = async (file) => {
// let firstLine: string;
// const stream = fs.createReadStream(file, { highWaterMark : 5 });
// const rl = readline.createInterface({ input: stream });
// for await (const line of rl) {
// rl.pause();
// firstLine = line;
// break;
// }
// // rl.close();
// // stream.destroy();
// return firstLine;
// };
// let array = await readFirstLine(filename);
// console.log("firstLine = ", array);
items.push({
"label": `$(calendar) ` + list[index],
"description": `$(three-bars) ` + array[0],
"detail": this.memoEditDispBtime ? localize('editBirthTime', '$(heart) Create Time: {0} $(clock) Modified Time: {1} ', statBirthtime, statMtime) : "",
"ln": null,
"col": null,
"index": index,
"filename": upath.normalize(upath.join(memodir, list[index])),
"isDirectory": false,
"birthtime": fileStat.birthtime,
"mtime": fileStat.mtime
});
// 出力タブへの出力を生成
this.memoListChannel.appendLine('file://' + upath.normalize(upath.join(memodir, list[index])) + `\t` + array[0]);
this.memoListChannel.appendLine('');
}
// "memo-life-for-you.listSortOrder" で sort 対象の項目を指定
// sort 結果は常に新しいものが上位にくる降順
switch (this.memoListSortOrder) {
case "filename":
// console.log('filename');
items = items.sort(function(a, b) {
return (a.filename < b.filename ? 1 : -1);
});
break;
case "birthtime":
// console.log('birthtime');
items = items.sort(function(a, b) {
return (a.birthtime.getTime() < b.birthtime.getTime() ? 1 : -1);
});
break;
case "mtime":
// console.log('mtime');
items = items.sort(function(a, b) {
return (a.mtime.getTime() < b.mtime.getTime() ? 1 : -1);
});
break;
}
// console.log("items =", items)
vscode.window.showQuickPick<items>(items, {
ignoreFocusOut: true,
matchOnDescription: true,
matchOnDetail: true,
placeHolder: localize('enterSelectOrFilename', 'Please select or enter a filename...(All items: {0}) ...Today\'s: {1}', items.length, dateFns.format(new Date(), 'MMM dd HH:mm, yyyy ')),
onDidSelectItem: async (selected:items) => {
if (selected == undefined || selected == null) {
return void 0;
}
// console.log(selected.label);
// console.log(isEnabled);
if (listMarkdownPreview) {
if (isEnabled) {
vscode.commands.executeCommand('workbench.action.focusPreviousGroup').then(async () =>{
// Markdown-enhance
return vscode.commands.executeCommand('markdown-preview-enhanced.syncPreview');
// Original
// await vscode.commands.executeCommand('markdown.refreshPreview');
});
isEnabled = false;
}
}
if (listMarkdownPreview) {
// 選択時に markdown preview を開く場合。要 Markdown Preview Enhance 拡張機能
await vscode.workspace.openTextDocument(selected.filename).then(async document => {
await vscode.window.showTextDocument(document, {
viewColumn: 1,
preserveFocus: true,
preview: true
})
}).then(async() => {
await vscode.commands.executeCommand('markdown-preview-enhanced.openPreview').then(async () => {
// await vscode.commands.executeCommand('markdown.showPreviewToSide').then(async () => {
// markdown preview を open すると focus が移動するので、focus を quickopen に戻す作業 1 回目
vscode.commands.executeCommand('workbench.action.focusQuickOpen');
});
// さらにもう一度実行して focus を維持する (なんでだろ? bug?)
await vscode.commands.executeCommand('workbench.action.focusQuickOpen');
});
// もう一回! (bug?)
await vscode.commands.executeCommand('workbench.action.focusQuickOpen');
isEnabled = true;
} else {
// 選択時に markdown preview を開かない設定の場合
await vscode.workspace.openTextDocument(selected.filename).then(async document =>{
vscode.window.showTextDocument(document, {
viewColumn: 1,
preserveFocus: true,
preview: true
})
})
}
}
}).then(async function (selected) { // When selected with the mouse
if (selected == undefined || selected == null) {
if (listMarkdownPreview) {
//キャンセルした時の close 処理
await vscode.commands.executeCommand('workbench.action.closeActiveEditor').then(() => {
vscode.commands.executeCommand('workbench.action.focusPreviousGroup').then(() => {
// vscode.commands.executeCommand('workbench.action.closeActiveEditor');
});
});
}
// Markdown preview を閉じる
await vscode.commands.executeCommand('workbench.action.closeActiveEditor');
return void 0;
}
await vscode.workspace.openTextDocument(upath.normalize(selected.filename)).then(async document => {
await vscode.window.showTextDocument(document, {
viewColumn: 1,
preserveFocus: true,
preview: true
}).then(async editor => {
if (listMarkdownPreview) {
if (openMarkdownPreview) {
if (openMarkdownPreviewUseMPE) {
// vscode.window.showTextDocument(document, vscode.ViewColumn.One, false).then(editor => {
// Markdown-Enhance
// await vscode.commands.executeCommand('markdown.showPreviewToSide').then(() =>{
await vscode.commands.executeCommand('markdown-preview-enhanced.openPreview').then(() =>{
vscode.commands.executeCommand('workbench.action.focusPreviousGroup');
});
// });
} else {
// MPE preview を close してから built-in preview を開く
await vscode.commands.executeCommand('workbench.action.closeActiveEditor');
await vscode.commands.executeCommand('markdown.showPreviewToSide').then(() => {
vscode.commands.executeCommand('workbench.action.focusPreviousGroup');
});
}
} else {
await vscode.commands.executeCommand('workbench.action.closeActiveEditor');
}
} else if (openMarkdownPreview) {
if (openMarkdownPreviewUseMPE) {
await vscode.commands.executeCommand('markdown-preview-enhanced.openPreview').then(() =>{
vscode.commands.executeCommand('workbench.action.focusPreviousGroup');
});
} else {
await vscode.commands.executeCommand('markdown.showPreviewToSide').then(() => {
vscode.commands.executeCommand('workbench.action.focusPreviousGroup');
});
}
}
});
});
});
}
}
// memodir 配下のファイルとディレクトリ一覧を取得
// https://blog.araya.dev/posts/2019-05-09/node-recursive-readdir.html
const readdirRecursively = (dir, files = []) => {
const dirents = fs.readdirSync(dir, { withFileTypes: true });
const dirs = [];
for (const dirent of dirents) {
if (dirent.isDirectory()) dirs.push(upath.normalize(upath.join(`${dir}`, `${dirent.name}`)));
if (dirent.isFile()) files.push(upath.normalize(upath.join(`${dir}`, `${dirent.name}`)));
}
for (const d of dirs) {
files = readdirRecursively(d, files);
}
return files;
}; | the_stack |
describe('Choices - select one', () => {
beforeEach(() => {
cy.visit('/select-one');
});
describe('scenarios', () => {
describe('basic', () => {
describe('focusing on container', () => {
describe('pressing enter key', () => {
it('toggles the dropdown', () => {
cy.get('[data-test-hook=basic]')
.find('.choices')
.focus()
.type('{enter}');
cy.get('[data-test-hook=basic]')
.find('.choices__list--dropdown')
.should('be.visible');
cy.get('[data-test-hook=basic]')
.find('.choices')
.focus()
.type('{enter}');
cy.get('[data-test-hook=basic]')
.find('.choices__list--dropdown')
.should('not.be.visible');
});
});
describe('pressing an alpha-numeric key', () => {
it('opens the dropdown and the input value', () => {
const inputValue = 'test';
cy.get('[data-test-hook=basic]')
.find('.choices')
.focus()
.type(inputValue);
cy.get('[data-test-hook=basic]')
.find('.choices__list--dropdown')
.should('be.visible');
cy.get('[data-test-hook=basic]')
.find('.choices__input--cloned')
.should('have.value', inputValue);
});
});
});
describe('selecting choices', () => {
beforeEach(() => {
// open dropdown
cy.get('[data-test-hook=basic]')
.find('.choices')
.click();
});
const selectedChoiceText = 'Choice 1';
it('allows selecting choices from dropdown', () => {
cy.get('[data-test-hook=basic]')
.find('.choices__list--dropdown .choices__list')
.children()
.first()
.click();
cy.get('[data-test-hook=basic]')
.find('.choices__list--single .choices__item')
.last()
.should($item => {
expect($item).to.contain(selectedChoiceText);
});
});
it('does not remove selected choice from dropdown list', () => {
cy.get('[data-test-hook=basic]')
.find('.choices__list--dropdown .choices__list')
.children()
.first()
.click();
cy.get('[data-test-hook=basic]')
.find('.choices__list--dropdown .choices__list')
.children()
.first()
.should($item => {
expect($item).to.contain(selectedChoiceText);
});
});
});
describe('searching choices', () => {
beforeEach(() => {
// open dropdown
cy.get('[data-test-hook=basic]')
.find('.choices')
.click();
});
describe('on input', () => {
describe('searching by label', () => {
it('displays choices filtered by inputted value', () => {
cy.get('[data-test-hook=basic]')
.find('.choices__input--cloned')
.type('item 2');
cy.get('[data-test-hook=basic]')
.find('.choices__list--dropdown .choices__list')
.children()
.first()
.should($choice => {
expect($choice.text().trim()).to.equal('Choice 2');
});
});
});
describe('searching by value', () => {
it('displays choices filtered by inputted value', () => {
cy.get('[data-test-hook=basic]')
.find('.choices__input--cloned')
.type('find me');
cy.get('[data-test-hook=basic]')
.find('.choices__list--dropdown .choices__list')
.children()
.first()
.should($choice => {
expect($choice.text().trim()).to.equal('Choice 3');
});
});
});
describe('no results found', () => {
it('displays "no results found" prompt', () => {
cy.get('[data-test-hook=basic]')
.find('.choices__input--cloned')
.type('faergge');
cy.get('[data-test-hook=basic]')
.find('.choices__list--dropdown')
.should('be.visible')
.should($dropdown => {
const dropdownText = $dropdown.text().trim();
expect(dropdownText).to.equal('No results found');
});
});
});
});
});
describe('disabling', () => {
describe('on disable', () => {
it('disables the search input', () => {
cy.get('[data-test-hook=basic]')
.find('button.disable')
.focus()
.click();
cy.get('[data-test-hook=basic]')
.find('.choices__input--cloned')
.should('be.disabled');
});
});
});
describe('enabling', () => {
describe('on enable', () => {
it('enables the search input', () => {
cy.get('[data-test-hook=basic]')
.find('button.enable')
.focus()
.click();
cy.get('[data-test-hook=basic]')
.find('.choices__input--cloned')
.should('not.be.disabled');
});
});
});
});
describe('remove button', () => {
/*
{
removeItemButton: true,
}
*/
beforeEach(() => {
cy.get('[data-test-hook=remove-button]')
.find('.choices__input--cloned')
.focus();
cy.get('[data-test-hook=remove-button]')
.find('.choices__list--dropdown .choices__list')
.children()
.last()
.click();
});
describe('remove button', () => {
describe('on click', () => {
let removedChoiceText;
beforeEach(() => {
cy.get('[data-test-hook=remove-button]')
.find('.choices__list--single .choices__item')
.last()
.then($choice => {
removedChoiceText = $choice.text().trim();
})
.click();
cy.get('[data-test-hook=remove-button]')
.find('.choices__list--single .choices__item')
.last()
.find('.choices__button')
.focus()
.click();
});
it('removes selected choice', () => {
cy.get('[data-test-hook=remove-button]')
.find('.choices__list--single')
.children()
.should('have.length', 0);
});
it('updates the value of the original input', () => {
cy.get('[data-test-hook=remove-button]')
.find('.choices__input[hidden]')
.should($select => {
const val = $select.val() || [];
expect(val).to.not.contain(removedChoiceText);
});
});
});
});
});
describe('disabled choice', () => {
describe('selecting a disabled choice', () => {
let selectedChoiceText;
beforeEach(() => {
cy.get('[data-test-hook=disabled-choice]').click();
cy.get('[data-test-hook=disabled-choice]')
.find('.choices__list--dropdown .choices__item--disabled')
.then($choice => {
selectedChoiceText = $choice.text().trim();
})
.click();
});
it('does not change selected choice', () => {
cy.get('[data-test-hook=prepend-append]')
.find('.choices__list--single .choices__item')
.last()
.should($choice => {
expect($choice.text()).to.not.contain(selectedChoiceText);
});
});
it('closes the dropdown list', () => {
cy.get('[data-test-hook=disabled-choice]')
.find('.choices__list--dropdown')
.should('not.be.visible');
});
});
});
describe('adding items disabled', () => {
/*
{
addItems: false,
}
*/
it('disables the search input', () => {
cy.get('[data-test-hook=add-items-disabled]')
.find('.choices__input--cloned')
.should('be.disabled');
});
describe('on click', () => {
it('does not open choice dropdown', () => {
cy.get('[data-test-hook=add-items-disabled]')
.find('.choices')
.click();
cy.get('[data-test-hook=add-items-disabled]')
.find('.choices__list--dropdown')
.should('not.have.class', 'is-active');
});
});
});
describe('disabled via attribute', () => {
it('disables the search input', () => {
cy.get('[data-test-hook=disabled-via-attr]')
.find('.choices__input--cloned')
.should('be.disabled');
});
describe('on click', () => {
it('does not open choice dropdown', () => {
cy.get('[data-test-hook=disabled-via-attr]')
.find('.choices')
.click();
cy.get('[data-test-hook=disabled-via-attr]')
.find('.choices__list--dropdown')
.should('not.have.class', 'is-active');
});
});
});
describe('prepend/append', () => {
/*
{
prependValue: 'before-',
appendValue: '-after',
};
*/
let selectedChoiceText;
beforeEach(() => {
cy.get('[data-test-hook=prepend-append]')
.find('.choices__input--cloned')
.focus();
cy.get('[data-test-hook=prepend-append]')
.find('.choices__list--dropdown .choices__list')
.children()
.last()
.then($choice => {
selectedChoiceText = $choice.text().trim();
})
.click();
});
it('prepends and appends value to inputted value', () => {
cy.get('[data-test-hook=prepend-append]')
.find('.choices__list--single .choices__item')
.last()
.should($choice => {
expect($choice.data('value')).to.equal(
`before-${selectedChoiceText}-after`,
);
});
});
it('displays just the inputted value to the user', () => {
cy.get('[data-test-hook=prepend-append]')
.find('.choices__list--single .choices__item')
.last()
.should($choice => {
expect($choice.text()).to.not.contain(
`before-${selectedChoiceText}-after`,
);
expect($choice.text()).to.contain(selectedChoiceText);
});
});
});
describe('render choice limit', () => {
/*
{
renderChoiceLimit: 1
}
*/
it('only displays given number of choices in the dropdown', () => {
cy.get('[data-test-hook=render-choice-limit]')
.find('.choices__list--dropdown .choices__list')
.children()
.should('have.length', 1);
});
});
describe('search disabled', () => {
/*
{
searchEnabled: false
}
*/
const selectedChoiceText = 'Choice 3';
beforeEach(() => {
cy.get('[data-test-hook=search-disabled]')
.find('.choices')
.click();
});
it('does not display a search input', () => {
cy.get('[data-test-hook=search-disabled]')
.find('.choices__input--cloned')
.should('not.exist');
});
it('allows selecting choices from dropdown', () => {
cy.get('[data-test-hook=search-disabled]')
.find('.choices__list--dropdown .choices__list')
.children()
.last()
.click();
cy.get('[data-test-hook=search-disabled]')
.find('.choices__list--single .choices__item')
.last()
.should($item => {
expect($item).to.contain(selectedChoiceText);
});
});
});
describe('search floor', () => {
/*
{
searchFloor: 10,
};
*/
describe('on input', () => {
beforeEach(() => {
cy.get('[data-test-hook=search-floor]')
.find('.choices__input--cloned')
.focus();
});
describe('search floor not reached', () => {
it('displays choices not filtered by inputted value', () => {
const searchTerm = 'item 2';
cy.get('[data-test-hook=search-floor]')
.find('.choices__input--cloned')
.type(searchTerm);
cy.get('[data-test-hook=search-floor]')
.find('.choices__list--dropdown .choices__list')
.children()
.first()
.should($choice => {
expect($choice.text().trim()).to.not.contain(searchTerm);
});
});
});
describe('search floor reached', () => {
it('displays choices filtered by inputted value', () => {
const searchTerm = 'Choice 2';
cy.get('[data-test-hook=search-floor]')
.find('.choices__input--cloned')
.type(searchTerm);
cy.get('[data-test-hook=search-floor]')
.find('.choices__list--dropdown .choices__list')
.children()
.first()
.should($choice => {
expect($choice.text().trim()).to.contain(searchTerm);
});
});
});
});
});
describe('placeholder via empty option value', () => {
describe('when no choice has been selected', () => {
it('displays a placeholder', () => {
cy.get('[data-test-hook=placeholder-via-option-value]')
.find('.choices__list--single')
.children()
.first()
.should('have.class', 'choices__placeholder')
.and($placeholder => {
expect($placeholder).to.contain('I am a placeholder');
});
});
});
describe('when a choice has been selected', () => {
it('does not display a placeholder', () => {
cy.get('[data-test-hook=placeholder-via-option-value]')
.find('.choices__input--cloned')
.focus();
cy.get('[data-test-hook=placeholder-via-option-value]')
.find('.choices__list--dropdown .choices__list')
.children()
.first()
.click();
cy.get('[data-test-hook=placeholder-via-option-value]')
.find('.choices__input--cloned')
.should('not.have.value', 'I am a placeholder');
});
});
describe('when choice list is open', () => {
it('displays the placeholder choice first', () => {
cy.get('[data-test-hook=placeholder-via-option-value]')
.find('.choices__input--cloned')
.focus();
cy.get('[data-test-hook=placeholder-via-option-value]')
.find('.choices__list--dropdown .choices__list')
.children()
.first()
.should('have.class', 'choices__placeholder')
.should('have.text', 'I am a placeholder');
});
});
});
describe('placeholder via option attribute', () => {
describe('when no choice has been selected', () => {
it('displays a placeholder', () => {
cy.get('[data-test-hook=placeholder-via-option-attr]')
.find('.choices__list--single')
.children()
.first()
.should('have.class', 'choices__placeholder')
.and($placeholder => {
expect($placeholder).to.contain('I am a placeholder');
});
});
});
describe('when a choice has been selected', () => {
it('does not display a placeholder', () => {
cy.get('[data-test-hook=placeholder-via-option-attr]')
.find('.choices__input--cloned')
.focus();
cy.get('[data-test-hook=placeholder-via-option-attr]')
.find('.choices__list--dropdown .choices__list')
.children()
.first()
.click();
cy.get('[data-test-hook=placeholder-via-option-attr]')
.find('.choices__input--cloned')
.should('not.have.value', 'I am a placeholder');
});
});
describe('when choice list is open', () => {
it('displays the placeholder choice first', () => {
cy.get('[data-test-hook=placeholder-via-option-attr]')
.find('.choices__input--cloned')
.focus();
cy.get('[data-test-hook=placeholder-via-option-attr]')
.find('.choices__list--dropdown .choices__list')
.children()
.first()
.should('have.class', 'choices__placeholder')
.should('have.text', 'I am a placeholder');
});
});
});
describe('remote data', () => {
beforeEach(() => {
cy.reload(true);
});
describe('when loading data', () => {
it('shows a loading message as a placeholder', () => {
cy.get('[data-test-hook=remote-data]')
.find('.choices__list--single')
.children()
.should('have.length', 1)
.first()
.should('have.class', 'choices__placeholder')
.and($placeholder => {
expect($placeholder).to.contain('Loading...');
});
});
describe('on click', () => {
it('does not open choice dropdown', () => {
cy.get('[data-test-hook=remote-data]')
.find('.choices')
.click()
.find('.choices__list--dropdown')
.should('not.have.class', 'is-active');
});
});
});
describe('when data has loaded', () => {
describe('opening the dropdown', () => {
it('displays the loaded data', () => {
cy.wait(1000);
cy.get('[data-test-hook=remote-data]')
.find('.choices__list--dropdown .choices__list')
.children()
.should('have.length', 51) // 50 choices + 1 placeholder choice
.each(($choice, index) => {
if (index === 0) {
expect($choice.text().trim()).to.equal('I am a placeholder');
} else {
expect($choice.text().trim()).to.equal(`Label ${index}`);
expect($choice.data('value')).to.equal(`Value ${index}`);
}
});
});
});
});
});
describe('scrolling dropdown', () => {
let choicesCount;
beforeEach(() => {
cy.get('[data-test-hook=scrolling-dropdown]')
.find('.choices__list--dropdown .choices__list .choices__item')
.then($choices => {
choicesCount = $choices.length;
});
cy.get('[data-test-hook=scrolling-dropdown]')
.find('.choices')
.click();
});
it('highlights first choice on dropdown open', () => {
cy.get('[data-test-hook=scrolling-dropdown]')
.find('.choices__list--dropdown .choices__list .is-highlighted')
.should($choice => {
expect($choice.text().trim()).to.equal('Choice 1');
});
});
it('scrolls to next choice on down arrow', () => {
for (let index = 0; index < choicesCount; index++) {
cy.get('[data-test-hook=scrolling-dropdown]')
.find('.choices__list--dropdown .choices__list .is-highlighted')
.should($choice => {
expect($choice.text().trim()).to.equal(`Choice ${index + 1}`);
});
cy.get('[data-test-hook=scrolling-dropdown]')
.find('.choices__input--cloned')
.type('{downarrow}');
}
});
it('scrolls up to previous choice on up arrow', () => {
// scroll to last choice
for (let index = 0; index < choicesCount; index++) {
cy.get('[data-test-hook=scrolling-dropdown]')
.find('.choices__input--cloned')
.type('{downarrow}');
}
// scroll up to first choice
for (let index = choicesCount; index > 0; index--) {
cy.wait(100); // allow for dropdown animation to finish
cy.get('[data-test-hook=scrolling-dropdown]')
.find('.choices__list--dropdown .choices__list .is-highlighted')
.should($choice => {
expect($choice.text().trim()).to.equal(`Choice ${index}`);
});
cy.get('[data-test-hook=scrolling-dropdown]')
.find('.choices__input--cloned')
.type('{uparrow}');
}
});
});
describe('choice groups', () => {
const choicesInGroup = 3;
let groupValue;
beforeEach(() => {
cy.get('[data-test-hook=groups]')
.find('.choices__list--dropdown .choices__list .choices__group')
.first()
.then($group => {
groupValue = $group.text().trim();
});
});
describe('selecting all choices in group', () => {
it('removes group from dropdown', () => {
for (let index = 0; index < choicesInGroup; index++) {
cy.get('[data-test-hook=groups]')
.find('.choices__input--cloned')
.focus();
cy.get('[data-test-hook=groups]')
.find('.choices__list--dropdown .choices__list .choices__item')
.first()
.click();
}
cy.get('[data-test-hook=groups]')
.find('.choices__list--dropdown .choices__list .choices__group')
.first()
.should($group => {
expect($group.text().trim()).to.not.equal(groupValue);
});
});
});
describe('deselecting all choices in group', () => {
beforeEach(() => {
for (let index = 0; index < choicesInGroup; index++) {
cy.get('[data-test-hook=groups]')
.find('.choices__input--cloned')
.focus();
cy.get('[data-test-hook=groups]')
.find('.choices__list--dropdown .choices__list .choices__item')
.first()
.click();
}
});
it('shows group in dropdown', () => {
for (let index = 0; index < choicesInGroup; index++) {
cy.get('[data-test-hook=groups]')
.find('.choices__input--cloned')
.focus()
.type('{backspace}');
}
cy.get('[data-test-hook=groups]')
.find('.choices__list--dropdown .choices__list .choices__group')
.first()
.should($group => {
expect($group.text().trim()).to.equal(groupValue);
});
});
});
});
describe('parent/child', () => {
describe('selecting "Parent choice 2"', () => {
it('enables the child Choices instance', () => {
cy.get('[data-test-hook=parent-child]')
.find('.choices')
.eq(1)
.should('have.class', 'is-disabled');
cy.get('[data-test-hook=parent-child]')
.find('.choices')
.eq(0)
.click();
cy.get('[data-test-hook=parent-child]')
.find('.choices__list--dropdown .choices__list')
.children()
.eq(1)
.click();
cy.get('[data-test-hook=parent-child]')
.find('.choices')
.eq(1)
.should('not.have.class', 'is-disabled');
});
});
describe('changing selection from "Parent choice 2" to something else', () => {
it('disables the child Choices instance', () => {
// open parent instance and select second choice
cy.get('[data-test-hook=parent-child]')
.find('.choices')
.eq(0)
.click()
.find('.choices__list--dropdown .choices__list')
.children()
.eq(1)
.click();
cy.get('[data-test-hook=parent-child]')
.find('.choices')
.eq(1)
.should('not.have.class', 'is-disabled');
// open parent instance and select third choice
cy.get('[data-test-hook=parent-child]')
.find('.choices')
.eq(0)
.click()
.find('.choices__list--dropdown .choices__list')
.children()
.eq(2)
.click();
cy.get('[data-test-hook=parent-child]')
.find('.choices')
.eq(1)
.should('have.class', 'is-disabled');
});
});
});
describe('custom properties', () => {
beforeEach(() => {
cy.get('[data-test-hook=custom-properties]')
.find('.choices')
.click();
});
describe('on input', () => {
it('filters choices based on custom property', () => {
const data = [
{
country: 'Germany',
city: 'Berlin',
},
{
country: 'United Kingdom',
city: 'London',
},
{
country: 'Portugal',
city: 'Lisbon',
},
];
data.forEach(({ country, city }) => {
cy.get('[data-test-hook=custom-properties]')
.find('.choices__input--cloned')
.type(country);
cy.get('[data-test-hook=custom-properties]')
.find('.choices__list--dropdown .choices__list')
.children()
.first()
.should($choice => {
expect($choice.text().trim()).to.equal(city);
});
cy.get('[data-test-hook=custom-properties]')
.find('.choices__input--cloned')
.type('{selectall}{del}');
});
});
});
});
describe('non-string values', () => {
beforeEach(() => {
cy.get('[data-test-hook=non-string-values]')
.find('.choices')
.click();
});
it('displays expected amount of choices in dropdown', () => {
cy.get('[data-test-hook=non-string-values]')
.find('.choices__list--dropdown .choices__list')
.children()
.should('have.length', 4);
});
it('allows selecting choices from dropdown', () => {
let $selectedChoice;
cy.get('[data-test-hook=non-string-values]')
.find('.choices__list--dropdown .choices__list')
.children()
.first()
.then($choice => {
$selectedChoice = $choice;
})
.click();
cy.get('[data-test-hook=non-string-values]')
.find('.choices__list--single .choices__item')
.last()
.should($item => {
expect($item.text().trim()).to.equal($selectedChoice.text().trim());
});
});
});
describe('within form', () => {
describe('selecting choice', () => {
describe('on enter key', () => {
it('does not submit form', () => {
cy.get('[data-test-hook=within-form] form').then($form => {
$form.submit(() => {
// this will fail the test if the form submits
throw new Error('Form submitted');
});
});
cy.get('[data-test-hook=within-form]')
.find('.choices')
.click()
.find('.choices__input--cloned')
.type('{enter}');
cy.get('[data-test-hook=within-form]')
.find('.choices')
.click();
cy.get('[data-test-hook=within-form]')
.find('.choices__list--single .choices__item')
.last()
.should($item => {
expect($item).to.contain('Choice 1');
});
});
});
});
});
describe('dynamically setting choice by value', () => {
const dynamicallySelectedChoiceValue = 'Choice 2';
it('selects choice', () => {
cy.get('[data-test-hook=set-choice-by-value]')
.find('.choices__list--single .choices__item')
.last()
.should($choice => {
expect($choice.text().trim()).to.equal(
dynamicallySelectedChoiceValue,
);
});
});
it('does not remove choice from dropdown list', () => {
cy.get('[data-test-hook=set-choice-by-value]')
.find('.choices__list--dropdown .choices__list')
.then($choicesList => {
expect($choicesList).to.contain(dynamicallySelectedChoiceValue);
});
});
it('updates the value of the original input', () => {
cy.get('[data-test-hook=set-choice-by-value]')
.find('.choices__input[hidden]')
.should($select => {
const val = $select.val() || [];
expect(val).to.contain(dynamicallySelectedChoiceValue);
});
});
});
describe('searching by label only', () => {
beforeEach(() => {
cy.get('[data-test-hook=search-by-label]')
.find('.choices')
.click();
});
it('gets zero results when searching by value', () => {
cy.get('[data-test-hook=search-by-label]')
.find('.choices__input--cloned')
.type('value1');
cy.get('[data-test-hook=search-by-label]')
.find('.choices__list--dropdown .choices__list')
.children()
.first()
.should($choice => {
expect($choice.text().trim()).to.equal('No results found');
});
});
it('gets a result when searching by label', () => {
cy.get('[data-test-hook=search-by-label]')
.find('.choices__input--cloned')
.type('label1');
cy.get('[data-test-hook=search-by-label]')
.find('.choices__list--dropdown .choices__list')
.children()
.first()
.should($choice => {
expect($choice.text().trim()).to.equal('label1');
});
});
});
describe('disabling first choice via options', () => {
beforeEach(() => {
cy.get('[data-test-hook=disabled-first-choice-via-options]')
.find('.choices')
.click();
});
let disabledValue;
it('disables the first choice', () => {
cy.get('[data-test-hook=disabled-first-choice-via-options]')
.find('.choices__list--dropdown .choices__list')
.children()
.first()
.should('have.class', 'choices__item--disabled')
.then($choice => {
disabledValue = $choice.val();
});
});
it('selects the first enabled choice', () => {
cy.get('[data-test-hook=disabled-first-choice-via-options]')
.find('.choices__input[hidden]')
.then($option => {
expect($option.text().trim()).to.not.equal(disabledValue);
});
cy.get('[data-test-hook=disabled-first-choice-via-options]')
.find('.choices__item.choices__item--selectable')
.first()
.should($choice => {
expect($choice.text().trim()).to.not.equal(disabledValue);
});
});
});
describe('re-initialising a choices instance', () => {
it('preserves the choices list', () => {
cy.get('[data-test-hook=new-destroy-init]')
.find('.choices__list--dropdown .choices__list')
.children()
.should('have.length', 3);
cy.get('[data-test-hook=new-destroy-init]')
.find('button.destroy')
.click();
cy.get('[data-test-hook=new-destroy-init]')
.find('button.init')
.click();
cy.get('[data-test-hook=new-destroy-init]')
.find('.choices__list--dropdown .choices__list')
.children()
.should('have.length', 3);
});
});
describe('destroying the choices instance', () => {
it('preserves the original select element', () => {
cy.get('[data-test-hook=new-destroy-init]')
.find('button.destroy')
.click();
cy.get('[data-test-hook=new-destroy-init]')
.find('select')
.children()
.should('have.length', 3);
});
});
});
}); | the_stack |
// tslint:disable:max-func-body-length object-literal-key-quotes no-invalid-template-strings
import * as assert from "assert";
import { Completion, getVSCodePositionFromPosition, toVsCodeCompletionItem } from '../extension.bundle';
import { assertEx } from './support/assertEx';
import { IPartialDeploymentTemplate } from './support/diagnostics';
import { parseTemplateWithMarkers } from './support/parseTemplate';
import { allTestDataExpectedCompletions } from "./TestData";
suite("dependsOn completions", () => {
type PartialCompletionItem = Partial<Completion.Item & { replaceSpanStart: number; replaceSpanText: string }>;
// <!replaceStart!> marks the start of the replace span
// <!cursor!> marks the cursor
function createDependsOnCompletionsTest(
testName: string,
options: {
template: IPartialDeploymentTemplate | string;
expected: PartialCompletionItem[];
triggerCharacter?: string;
}
): void {
test(testName, async () => {
const { dt, markers: { cursor, replaceStart } } = parseTemplateWithMarkers(options.template);
assert(cursor, "Missing <!cursor!> in testcase template");
const pc = dt.getContextFromDocumentCharacterIndex(cursor.index, undefined);
const { items: completions } = await pc.getCompletionItems(options.triggerCharacter, 4);
// Run toVsCodeCompletionItem on the items - this will run some additional validation
const vscodeItems = completions.map(item =>
toVsCodeCompletionItem(dt, item, getVSCodePositionFromPosition(pc.documentPosition))
);
assert.strictEqual(vscodeItems.length, completions.length);
const actual: PartialCompletionItem[] = completions.map(filterActual);
assertEx.deepEqual(
actual,
options.expected,
{
ignorePropertiesNotInExpected: true
});
function filterActual(item: Completion.Item): PartialCompletionItem {
// tslint:disable-next-line: strict-boolean-expressions
if (!!replaceStart) {
return {
...item,
replaceSpanStart: replaceStart.index,
replaceSpanText: dt.getDocumentText(item.span)
};
} else {
return item;
}
}
});
}
suite("completionKinds", () => {
createDependsOnCompletionsTest(
"completionKinds",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "microsoft.abc/def",
name: "name1",
copy: {
name: "copy"
}
},
{
type: "microsoft.ghi/jkl",
name: "name2",
copy: {
name: "[concat(parameters('p1'), '/', variables('v1'))]"
}
}
]
},
expected: [
{
"label": "name1",
"kind": Completion.CompletionKind.dependsOnResourceId
},
{
"label": "Loop copy",
"kind": Completion.CompletionKind.dependsOnResourceCopyLoop
},
{
"label": "name2",
"kind": Completion.CompletionKind.dependsOnResourceId
},
{
"label": "Loop ${p1}/${v1}",
"kind": Completion.CompletionKind.dependsOnResourceCopyLoop
}
]
}
);
});
suite("detail", () => {
createDependsOnCompletionsTest(
"detail matches friendy type name",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "Microsoft.abc/def",
name: "name1a"
},
{
type: "microsoft.123/456/789",
name: "name1b"
},
{
type: "singlesegment",
name: "name1c"
}
]
},
expected: [
{
"label": "name1a",
"insertText": `"[resourceId('Microsoft.abc/def', 'name1a')]"`,
"detail": "def"
},
{
"label": "name1b",
"insertText": `"[resourceId('microsoft.123/456/789', 'name1b')]"`,
"detail": "789"
},
{
"label": "name1c",
"insertText": `"[resourceId('singlesegment', 'name1c')]"`,
"detail": "singlesegment"
}
]
});
createDependsOnCompletionsTest(
"detail for copy loop is friendly type name",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "Microsoft.abc/def",
name: "name1",
copy: {
name: "copyname"
}
}
]
},
expected: [
{
"label": "name1"
},
{
"label": "Loop copyname",
"detail": "def"
}
]
});
});
suite("documentation", () => {
createDependsOnCompletionsTest(
"documentation",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "microsoft.abc/def",
name: "name1a",
copy: {
name: "copyname"
}
}
]
},
expected: [
{
// tslint:disable-next-line: no-any
"documention": <any>{
value:
// tslint:disable-next-line: prefer-template
"Inserts this resourceId reference:\n" +
"```arm-template\n" +
"\"[resourceId('microsoft.abc/def', 'name1a')]\"\n" +
"```\n<br/>"
}
},
{
// tslint:disable-next-line: no-any
"documention": <any>{
value:
`Inserts this COPY element reference:
\`\`\`arm-template
"copyname"
\`\`\`
from resource \`name1a\` of type \`def\``
}
}
]
}
);
});
suite("label", () => {
createDependsOnCompletionsTest(
"label is the last segment of the name - single segment",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "microsoft.abc/def",
name: "name1a"
}
]
},
expected: [
{
"label": `name1a`,
"insertText": `"[resourceId('microsoft.abc/def', 'name1a')]"`,
// tslint:disable-next-line: no-any
"documention": <any>{
value:
// tslint:disable-next-line: prefer-template
`Inserts this resourceId reference:\n` +
"```arm-template\n" +
`"[resourceId('microsoft.abc/def', 'name1a')]"\n` +
"```\n<br/>"
}
}
]
}
);
createDependsOnCompletionsTest(
"label is the last segment of the name - multiple segments",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "microsoft.abc/def/ghi",
name: "name1a/name1b"
}
]
},
expected: [
{
"label": `name1b`
}
]
}
);
createDependsOnCompletionsTest(
"label for copy loop",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "microsoft.abc/def",
name: "name1",
copy: {
name: "copynameliteral"
}
},
{
type: "microsoft.abc/def",
name: "name2",
copy: {
name: "[concat('copy', 'name1')]"
}
}
]
},
expected: [
{
"label": `name1`
},
{
"label": `Loop copynameliteral`
},
{
"label": `name2`
},
{
"label": `Loop copyname1`
}
]
}
);
});
suite("expressions", () => {
createDependsOnCompletionsTest(
"type is expression",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "[variables('microsoft.abc/def')]",
name: "name1a"
}
]
},
expected: [
{
"label": "name1a",
"insertText": `"[resourceId(variables('microsoft.abc/def'), 'name1a')]"`
}
]
}
);
createDependsOnCompletionsTest(
"name is expression that can't be separated",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "microsoft.abc/def",
name: "[add(parameters('name1a'), 'foo')]"
}
]
},
expected: [
{
"label": "[add(${name1a}, 'foo')]",
"insertText": `"[resourceId('microsoft.abc/def', add(parameters('name1a'), 'foo'))]"`
}
]
}
);
});
createDependsOnCompletionsTest(
"name is expressions that can be separated 1`",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "microsoft.abc/def",
name: "[concat(parameters('name1a'), '/foo')]"
}
]
},
expected: [
{
"label": "foo",
"insertText": `"[resourceId('microsoft.abc/def', parameters('name1a'), 'foo')]"`
}
]
}
);
createDependsOnCompletionsTest(
"name is expressions that can be separated 2`",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "microsoft.abc/def",
name: "[concat(parameters('name1a'), '/', 'foo')]"
}
]
},
expected: [
{
"label": "foo",
"insertText": `"[resourceId('microsoft.abc/def', parameters('name1a'), 'foo')]"`
}
]
}
);
createDependsOnCompletionsTest(
"insertionText for copy loop",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "microsoft.abc/def",
name: "name1",
copy: {
name: "copynameliteral"
}
},
{
type: "microsoft.abc/def",
name: "name2",
copy: {
name: "[concat('copy', 'name1')]"
}
}
]
},
expected: [
{
"label": `name1`
},
{
"insertText": `"copynameliteral"`
},
{
"label": `name2`
},
{
"insertText": `"[concat('copy', 'name1')]"`
}
]
}
);
createDependsOnCompletionsTest(
"name is expression",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "microsoft.abc/def",
name: "[sum(parameters('name1a'), 1)]"
}
]
},
expected: [
{
"label": "[sum(${name1a}, 1)]",
"insertText": `"[resourceId('microsoft.abc/def', sum(parameters('name1a'), 1))]"`
}
]
}
);
suite("nested templates", () => {
createDependsOnCompletionsTest(
"Top level shouldn't find resources in nested scope",
{
template: {
"resources": [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
"type": "Microsoft.Storage/storageAccounts",
"apiVersion": "2019-06-01",
"name": "[concat(parameters('projectName'), 'stgdiag')]"
},
{
"type": "Microsoft.Resources/deployments",
"name": "[concat(parameters('projectName'),'dnsupdate')]",
"dependsOn": [
"[concat(parameters('projectName'),'lbwebgwpip')]"
],
"properties": {
"template": {
"resources": [
{
"name": "[parameters('DNSZone')]",
"type": "Microsoft.Network/dnsZones"
}
]
}
}
}
]
},
"expected": [
{
"insertText": `"[resourceId('Microsoft.Storage/storageAccounts', concat(parameters('projectName'), 'stgdiag'))]"`
},
{
"insertText": `"[resourceId('Microsoft.Resources/deployments', concat(parameters('projectName'),'dnsupdate'))]"`
}
]
});
createDependsOnCompletionsTest(
"Inside nested scope shouldn't find top-level resources",
{
template: {
"resources": [
{
"type": "Microsoft.Storage/storageAccounts",
"apiVersion": "2019-06-01",
"name": "[concat(parameters('projectName'), 'stgdiag')]"
},
{
"type": "Microsoft.Resources/deployments",
"name": "[concat(parameters('projectName'),'dnsupdate')]",
"dependsOn": [
"[concat(parameters('projectName'),'lbwebgwpip')]"
],
"properties": {
"template": {
"resources": [
{
"name": "[parameters('DNSZone')]",
"type": "Microsoft.Network/dnsZones"
},
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
}
]
}
}
}
]
},
"expected": [
{
"insertText": `"[resourceId('Microsoft.Network/dnsZones', parameters('DNSZone'))]"`
}
]
});
});
suite("completion triggering", () => {
createDependsOnCompletionsTest(
"ctrl+space without any quotes",
{
template: `{
"resources": [
{
"dependsOn": [
<!replaceStart!><!cursor!>
]
},
{
"type": "microsoft.abc/def",
"name": "name1a"
}
]
}`,
expected: [
{
"label": "name1a",
"insertText": `"[resourceId('microsoft.abc/def', 'name1a')]"`,
replaceSpanText: ``
}
]
}
);
createDependsOnCompletionsTest(
"ctrl+space just inside existing quotes",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "microsoft.abc/def",
name: "name1a"
}
]
},
expected: [
{
"label": "name1a",
"insertText": `"[resourceId('microsoft.abc/def', 'name1a')]"`,
replaceSpanText: `""`
}
]
}
);
createDependsOnCompletionsTest(
"typing double quote to string new string",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "microsoft.abc/def",
name: "name1a"
}
]
},
expected: [
{
"label": "name1a",
"insertText": `"[resourceId('microsoft.abc/def', 'name1a')]"`,
replaceSpanText: `""`
}
],
triggerCharacter: '"'
}
);
createDependsOnCompletionsTest(
"replacement includes entire string",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>name2a"
]
},
{
type: "microsoft.abc/def",
name: "name1a"
}
]
},
expected: [
{
"label": "name1a",
"insertText": `"[resourceId('microsoft.abc/def', 'name1a')]"`,
replaceSpanText: `"name2a"`
}
]
}
);
createDependsOnCompletionsTest(
"no dependsOn completions inside an expression (#1008/1033)",
{
template: {
resources: [
{
dependsOn: [
"[<!replaceStart!>name<!cursor!>2a"
]
},
{
type: "microsoft.abc/def",
name: "name1a"
}
]
},
expected: [
...allTestDataExpectedCompletions(0, Number.MAX_SAFE_INTEGER).map(c => ({ label: c.label }))
]
}
);
});
createDependsOnCompletionsTest(
"case insensitive dependsOn",
{
template: {
resources: [
{
DEPENDSON: [
"<!replaceStart!><!cursor!>name2a"
]
},
{
type: "microsoft.abc/def",
name: "name1a"
}
]
},
expected: [
{
"label": "name1a",
"insertText": `"[resourceId('microsoft.abc/def', 'name1a')]"`,
replaceSpanText: `"name2a"`
}
]
}
);
createDependsOnCompletionsTest(
"multiple resources",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "microsoft.abc/def",
name: "name1a"
},
{
type: "microsoft.abc/def",
name: "name1b"
},
{
type: "type2",
name: "name2"
}
]
},
expected: [
{
"label": "name1a",
"insertText": `"[resourceId('microsoft.abc/def', 'name1a')]"`,
replaceSpanText: `""`
},
{
"label": "name1b",
"insertText": `"[resourceId('microsoft.abc/def', 'name1b')]"`,
replaceSpanText: `""`
},
{
"label": "name2",
"insertText": `"[resourceId('type2', 'name2')]"`,
replaceSpanText: `""`
}
]
}
);
createDependsOnCompletionsTest(
"No dependsOn completion for the resource to itself",
{
template: {
"resources": [
{
"name": "[variables('sqlServer')]",
"type": "Microsoft.Sql/servers",
"dependsOn": [
"<!cursor!>'"
]
}
]
},
expected: [
]
}
);
suite("Child resources", () => {
suite("Decoupled parent/child", () => {
createDependsOnCompletionsTest(
"multiple segments in name as string literal",
{
template: {
resources: [
{
dependsOn: [
"<!replaceStart!><!cursor!>"
]
},
{
type: "microsoft.abc/def/ghi",
name: "name1a/name1b"
}
]
},
expected: [
{
"insertText": `"[resourceId('microsoft.abc/def/ghi', 'name1a', 'name1b')]"`
}
]
}
);
createDependsOnCompletionsTest(
"Reference parent from child",
{
template: {
"resources": [
{
// Parent
"name": "[variables('sqlServer')]",
"type": "Microsoft.Sql/servers"
},
{
// Child (decoupled). Requires the parent as part of the name
"name": "[concat(variables('sqlServer'), '/' , variables('firewallRuleName'))]",
"type": "Microsoft.Sql/servers/firewallRules",
"dependsOn": [
"<!cursor!>'"
]
}
]
},
expected: [
{
label: "Parent (${sqlServer})",
detail: "servers",
insertText: `"[resourceId('Microsoft.Sql/servers', variables('sqlServer'))]"`
}
]
}
);
// tslint:disable-next-line: no-suspicious-comment
/* TODO: recognized decoupled children (https://github.com/microsoft/vscode-azurearmtools/issues/492)
createDependsOnCompletionsTest(
"Don't show completion to reference descendents from parent",
{
template: {
"resources": [
{
// Sibling
"name": "[concat(variables('sqlServer'), '/' , variables('firewallRuleName2'))]",
"type": "Microsoft.Sql/servers/firewallRules",
"resources": [
{
"name": "siblingchild",
"type": "Microsoft.Sql/servers/firewallRules/whatever"
}
]
},
{
// Parent
"name": "[variables('sqlServer')]",
"type": "Microsoft.Sql/servers",
"dependsOn": [
"<!cursor!>'"
]
},
{
// Child (decoupled). Requires the parent as part of the name
"name": "[concat(variables('sqlServer'), '/' , variables('firewallRuleName'))]",
"type": "Microsoft.Sql/servers/firewallRules",
"resources": [
{
"name": "grandchild",
"type": "Microsoft.Sql/servers/firewallRules/whatever"
}
]
}
]
},
expected: [
{
label: "variables('firewallRuleName2')"
},
{
label: "siblingchild"
}
]
}
);*/
});
suite("nested parent/child", () => {
createDependsOnCompletionsTest(
"Two ways to name nested children",
{
template: {
"resources": [
{
// sibling
name: "sibling",
type: "a.b/c",
"dependsOn": [
"<!cursor!>"
]
},
{
// Parent
"name": "[variables('sqlServer')]",
"type": "Microsoft.Sql/servers",
"resources": [
{
// Child (nested) - Name/type don't include parent name/type (this is the normal and documented case)
"name": "[variables('firewallRuleName')]",
"type": "firewallRules"
},
{
// Child (nested) - But name/type *can* include parent name/type (as long as both name and type do)
"name": "[concat(variables('sqlServer'), '/', variables('firewallRuleName2'))]",
"type": "Microsoft.Sql/servers/firewallRules"
}
]
}
]
},
expected: [
{
label: "${sqlServer}"
},
{
label: "${firewallRuleName}",
insertText: `"[resourceId('Microsoft.Sql/servers/firewallRules', variables('sqlServer'), variables('firewallRuleName'))]"`
},
{
label: "${firewallRuleName2}",
insertText: `"[resourceId('Microsoft.Sql/servers/firewallRules', variables('sqlServer'), variables('firewallRuleName2'))]"`
}
]
}
);
createDependsOnCompletionsTest(
"Reference parent and siblings from nested child",
{
template: {
"resources": [
{
// sibling
name: "sibling",
type: "a.b/c"
},
{
// Parent
"name": "[variables('sqlServer')]",
"type": "Microsoft.Sql/servers",
"resources": [
{
// Child (nested) - Name/type don't include parent name/type (this is the normal and documented case)
"name": "[variables('firewallRuleName')]",
"type": "firewallRules",
"dependsOn": [
"<!cursor!>"
]
},
{
// Child (nested) - But name/type *can* include parent name/type (as long as both name and type do)
"name": "[concat(variables('sqlServer'), '/', variables('firewallRuleName2'))]",
"type": "Microsoft.Sql/servers/firewallRules"
}
]
}
]
},
expected: [
{
// another top-level resource
label: "sibling"
},
{
// parent
label: "Parent (${sqlServer})"
},
{
// sibling child
label: "${firewallRuleName2}"
}
]
}
);
createDependsOnCompletionsTest(
"Don't reference nested child or descendents from parent",
{
template: {
"resources": [
{
// Parent
"name": "[variables('sqlServer')]",
"type": "Microsoft.Sql/servers",
"resources": [
{
// Child (nested) - Name must not include parent name
"name": "[variables('firewallRuleName')]",
"type": "firewallRules",
"resources": [
{
"name": "grandchild",
"type": "subrule"
}
]
}
],
"dependsOn": [
"<!cursor!>"
]
},
{
"name": "sibling",
"type": "abc.def/ghi"
}
]
},
expected: [
{
insertText: `"[resourceId('abc.def/ghi', 'sibling')]"`
}
]
}
);
});
suite("nested vnet", () => {
createDependsOnCompletionsTest(
"Don't reference child subnet from parent vnet",
{
template: {
"resources": [
{
"type": "Microsoft.Network/virtualNetworks",
"name": "vnet1",
"properties": {
"subnets": [
// These are considered children, with type Microsoft.Network/virtualNetworks/subnets
{
"name": "subnet1",
"type": "subnets"
}
]
},
"dependsOn": [
"<!cursor!>"
]
}
]
},
expected: [
]
}
);
createDependsOnCompletionsTest(
"Reference parent vnet from child subnet",
{
template: {
"resources": [
{
"type": "Microsoft.Network/virtualNetworks",
"name": "vnet1",
"properties": {
"subnets": [
// These are considered children, with type Microsoft.Network/virtualNetworks/subnets
{
"name": "subnet1",
"type": "subnets",
"dependsOn": [
"<!cursor!>"
]
}
]
}
}
]
},
expected: [
{
insertText: `"[resourceId('Microsoft.Network/virtualNetworks', 'vnet1')]"`
}
]
}
);
});
});
suite("Multiple levels of children", () => {
createDependsOnCompletionsTest(
"Reference any resource's children except for direct descendents",
{
template: {
"resources": [
{
// Parent1
"name": "[variables('parent1')]",
"type": "Microsoft.Sql/servers",
"resources": [
{
// Child1a (nested) - should not be in completions
"name": "[variables('child1a')]",
"type": "firewallRules",
"dependsOn": [
"<!cursor!>"
],
"resources": [
{
// grandchild1 (nested) - should not be in completions
"name": "grandchild1",
"type": "rulechild"
}
]
}
]
},
{
// Child1b (decoupled)
"name": "parent1/child1b",
"type": "Microsoft.Sql/servers/firewallRules"
},
{
// Sibling1
"name": "sibling1",
"type": "Microsoft.Sql/servers",
"resources": [
{
// Child2a (nested)
"name": "child2a",
"type": "firewallRules",
"resources": [
{
// grandchild2 (nested)
"name": "grandchild2",
"type": "rulechild"
}
]
}
]
},
{
// Child2b of sibling1 (decoupled)
"name": "[concat('sibling1', '/', variables('child2b'))]",
"type": "Microsoft.Sql/servers/firewallRules"
}
]
},
expected: [
{
label: "Parent (${parent1})"
},
{
label: "child1b"
},
{
label: "sibling1"
},
{
label: "child2a"
},
{
label: "grandchild2"
},
{
label: "${child2b}"
}
]
}
);
});
suite("Regression", () => {
createDependsOnCompletionsTest(
"#974 simple",
{
template: {
"resources": [
{
"type": "Microsoft.Compute/virtualMachines/extensions",
"apiVersion": "2019-12-01",
"name": "[concat(parameters('vmName'),copyIndex(1),'/dscext')]",
"dependsOn": [
// >>> CURSOR ON FOLLOWING LINE inside "resourceId"
"[reso<!cursor!>urceId('Microsoft.Compute/virtualMachines/extensions', concat(parameters('vmName'),copyIndex(1),'/dscext'))]"
]
}
]
},
expected: [
// Just the built-in function names, nothing else (and don't assert)
...allTestDataExpectedCompletions(0, Number.MAX_SAFE_INTEGER).map(c => ({ label: c.label }))
]
}
);
createDependsOnCompletionsTest(
"#974",
{
template: {
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {},
"functions": [],
"variables": {},
"resources": [
{
"type": "Microsoft.Compute/virtualMachines/extensions",
"apiVersion": "2019-12-01",
"name": "[concat(parameters('vmName'),copyIndex(1),'/dscext')]",
"location": "[resourceGroup().location]",
"condition": "[not(empty(parameters('dscFunction')))]",
"dependsOn": [
// >>> CURSOR ON FOLLOWING LINE inside "resourceId"
"[reso<!cursor!>urceId('Microsoft.Compute/virtualMachines/extensions', concat(parameters('vmName'),copyIndex(1),'/dscext'))]"
],
"properties": {
"publisher": "Microsoft.Powershell",
"type": "DSC",
"typeHandlerVersion": "2.11",
"autoUpgradeMinorVersion": true,
"settings": {
"ModulesUrl": "[concat(parameters('dscLocation'),'DSC/DeployRDSLab.zip')]",
"ConfigurationFunction": "[parameters('dscFunction')]",
"Properties": {
"AdminCreds": {
"UserName": "[parameters('adminUser')]",
"Password": "PrivateSettingsRef:AdminPassword"
},
"RDSParameters": [
{
"TimeZoneID": "[parameters('TimeZoneID')]",
"DomainName": "[parameters('adDomainName')]",
"DNSServer": "[parameters('firstDcIP')]",
"MainConnectionBroker": "[parameters('MainConnectionBroker')]",
"WebAccessServer": "[concat(parameters('WebAccessServerName'),'1')]",
"SessionHost": "[concat(parameters('SessionHostName'),'1')]",
"LicenseServer": "[concat(parameters('LicenseServerName'),'1')]",
"ExternalFqdn": "[parameters('ExternalFqdn')]",
"ExternalDnsDomain": "[parameters('ExternalDnsDomain')]",
"IntBrokerLBIP": "[parameters('intLbBrokerIP')]",
"IntWebGWLBIP": "[parameters('intLbWebGWIP')]",
"WebGWDNS": "[parameters('webGwName')]"
}
]
}
},
"protectedSettings": {
"Items": {
"AdminPassword": "[parameters('adminPasswd')]"
}
}
}
}
],
"outputs": {}
},
expected: [
// Just the built-in function names, nothing else (and don't assert)
...allTestDataExpectedCompletions(0, Number.MAX_SAFE_INTEGER).map(c => ({ label: c.label }))
]
}
);
});
}); | the_stack |
/// <reference types='node'/>
/**
* A function that must be called with either an error or a value, but not both.
* @param error - Error object.
* @param value - passed value to any callback function.
*/
type Callback<T> = ((error: Error, value?: undefined) => void) & ((error: null, value: T) => void);
/**
* Represents a timestamp based on the UNIX epoch (1970 Jan 1).
* See also: http://wiki.ros.org/roscpp/Overview/Time
*/
interface Time {
// whole seconds
sec: number;
// additional nanoseconds past the sec value
nsec: number;
}
interface Filelike {
/**
* Reads buffer at specified offset and length then pass it on to callback function.
* @param offset - The location in the buffer at which to start.
* @param length - The number of bytes to read.
* @param callback - Callback function accepting Buffer object.
*/
read(offset: number, length: number, callback: Callback<Buffer>): void;
/**
* Getter method to retrieve file size.
*/
size(): number;
}
interface RosMsgField {
type: string;
name: string;
isComplex?: boolean;
// For arrays
isArray?: boolean;
arrayLength?: number;
// For constants
isConstant?: boolean;
value?: any;
}
/**
* Represents ros message definition data.
*/
interface RosMsgDefinition {
name?: string;
definitions: RosMsgField[];
}
/**
* Extracts key/value pair of information out of a buffer
* @param buffer - The buffer to extract key/value piece of information from.
*/
declare function extractFields(buffer: Buffer): { [key: string]: Buffer };
/**
* Reads a Time object out of a buffer at the given offset
* @param buffer - Buffer
* @param offset - Offset
*/
declare function extractTime(buffer: Buffer, offset: number): Time;
type rosType =
| 'string'
| 'bool'
| 'int8'
| 'uint8'
| 'int16'
| 'uint16'
| 'int32'
| 'uint32'
| 'float32'
| 'float64'
| 'int64'
| 'uint64'
| 'time'
| 'duration'
| 'json';
type rosPrimitiveTypes = Set<rosType>;
/**
* Given a raw message definition string, parse it into an object representation.
* @param messageDefinition - ROSBAG message definition string.
*/
declare function parseMessageDefinition(messageDefinition: string): RosMsgDefinition[];
declare class MessageReader {
reader: (buffer: Buffer) => any;
/**
* takes an object message definition and returns
* a message reader which can be used to read messages based
* on the message definition.
* @param definitions
* @param options
*/
constructor(definitions: RosMsgDefinition[], options: { freeze?: boolean });
readMessage(buffer: Buffer): any;
}
declare class MessageWriter {
writer: (message: any, bufferToWrite: Buffer) => Buffer;
bufferSizeCalculator: (message: any) => number;
/**
* takes an object string message definition and returns
* a message writer which can be used to write messages based
* on the message definition.
* @param definitions
*/
constructor(definitions: RosMsgDefinition[]);
/**
* Calculates the buffer size needed to write this message in bytes.
* @param message
*/
calculateBufferSize(message: any): number;
/**
* @param message
* @param bufferToWrite - bufferToWrite is optional - if it is not provided, a buffer will be generated.
*/
writeMessage(message: any, bufferToWrite?: Buffer): Buffer;
}
/**
* Opens a bag file and return a bag readable object
* @param filename - File path or Blob depening on evironment (either node or web)
*/
declare function open(filename: File | string | Blob): Promise<Bag>;
declare namespace TimeUtil {
/**
* Converts Date object to ROS digestable Time format
* @param date - Date object
*/
function fromDate(date: Date): Time;
/**
* Converts Time from ROSBAG to Date object
* @param time
*/
function toDate(time: Time): Date;
/**
* Compares two times, returning a negative value if the right is greater
* or a positive value if the left is greater or 0 if the times are equal
* useful to supply to Array.prototype.sort.
* @param left
* @param right
*/
function compare(left: Time, right: Time): number;
/**
* Returns true if the left time is less than the right time, otherwise false
* @param left
* @param right
*/
function isLessThan(left: Time, right: Time): boolean;
/**
* Returns true if the left time is greater than the right time, otherwise false
* @param left
* @param right
*/
function isGreaterThan(left: Time, right: Time): boolean;
/**
* Returns true if both times have the same number of seconds and nanoseconds
* @param left
* @param right
*/
function areSame(left: Time, right: Time): boolean;
/**
* Computes the sum of two times or durations and returns a new time
* throws an exception if the resulting time is negative
* @param left
* @param right
*/
function add(left: Time, right: Time): Time;
}
interface ChunkReadResult {
chunk: Chunk;
indices: IndexData[];
}
interface Decompress {
[compression: string]: (buffer: Buffer, size: number) => Buffer;
}
/**
* BagReader is a lower level interface for reading specific sections & chunks
* from a rosbag file - generally it is consumed through the Bag class, but
* can be useful to use directly for efficiently accessing raw pieces from
* within the bag
*/
declare class BagReader {
_lastReadResult: ChunkReadResult;
_file: Filelike;
_lastChunkInfo?: ChunkInfo;
constructor(filelike: Filelike);
verifyBagHeader(callback: Callback<BagHeader>, next: () => void): void;
/**
* reads the header block from the rosbag file
* generally you call this first
* because you need the header information to call readConnectionsAndChunkInfo
* @param callback
*/
readHeader(callback: Callback<BagHeader>): void;
/**
* Promisified version of readHeader
*/
readHeaderAsync(): Promise<BagHeader>;
/**
* reads connection and chunk information from the bag
* you'll generally call this after reading the header so you can get
* connection metadata and chunkInfos which allow you to seek to individual
* chunks & read them
* @param fileOffset
* @param connectionCount
* @param chunkCount
* @param callback
*/
readConnectionsAndChunkInfo(
fileOffset: number,
connectionCount: number,
chunkCount: number,
callback: Callback<{ connections: Connection[]; chunkInfos: ChunkInfo[] }>,
): void;
/**
* Promisified version of readConnectionsAndChunkInfo
* @param fileOffset
* @param connectionCount
* @param chunkCount
*/
readConnectionsAndChunkInfoAsync(
fileOffset: number,
connectionCount: number,
chunkCount: number,
): Promise<{ connections: Connection[]; chunkInfos: ChunkInfo[] }>;
/**
* read individual raw messages from the bag at a given chunk
* filters to a specific set of connection ids, start time, & end time
* generally the records will be of type MessageData
* @param chunkInfo
* @param connections
* @param startTime
* @param endTime
* @param decompress
* @param callback
*/
readChunkMessages(
chunkInfo: ChunkInfo,
connections: number[],
startTime: Time | null,
endTime: Time | null,
decompress: Decompress,
callback: Callback<MessageData[]>,
): void;
/**
* Promisified version of readChunkMessages
* @param chunkInfo
* @param connections
* @param startTime
* @param endTime
* @param decompress
*/
readChunkMessagesAsync(
chunkInfo: ChunkInfo,
connections: number[],
startTime: Time,
endTime: Time,
decompress: Decompress,
): Promise<MessageData[]>;
/**
* Reads a single chunk record && its index records given a chunkInfo
* @param chunkInfo
* @param decompress
* @param callback
*/
readChunk(chunkInfo: ChunkInfo, decompress: Decompress, callback: Callback<ChunkReadResult>): void;
/**
* Reads count records from a buffer starting at fileOffset
* @param buffer
* @param count
* @param fileOffset
* @param cls
*/
readRecordsFromBuffer<T extends Record>(
buffer: Buffer,
count: number,
fileOffset: number,
cls: T & { opcode: number },
): T[];
/**
* Reads an individual record from a buffer
* @param buffer
* @param fileOffset
* @param cls
*/
readRecordFromBuffer<T extends Record>(buffer: Buffer, fileOffset: number, cls: T & { opcode: number }): T;
}
interface ReadOptions {
decompress?: Decompress;
noParse?: boolean;
topics?: string[];
startTime?: Time;
endTime?: Time;
freeze?: boolean;
}
declare class Bag {
reader: BagReader;
header: BagHeader;
connections: { [conn: number]: Connection };
chunkInfos: ChunkInfo[];
startTime: Time | undefined;
endTime: Time | undefined;
/**
* the high level rosbag interface
* create a new bag by calling:
* `const bag = await Bag.open('./path-to-file.bag')` in node or
* `const bag = await Bag.open(files[0])` in the browser
*
* after that you can consume messages by calling
* `await bag.readMessages({ topics: ['/foo'] },
* (result) => console.log(result.topic, result.message))`
*
* you can optionally create a bag manually passing in a bagReader instance
*
* @param bagReader
*/
constructor(bagReader: BagReader);
/**
* This method should have been overridden based on the environment.
* Make sure you are correctly importing the node or web version of Bag.
* @param file
*/
static open(file: File | string | Blob): void;
/**
* if the bag is manually created with the constructor, you must call `await open()` on the bag
* generally this is called for you if you're using `const bag = await Bag.open()`
*/
open(): Promise<void>;
readMessages(opts: ReadOptions, callback: (msg: ReadResult<any>) => void): Promise<void>;
}
declare class ReadResult<T> {
topic: string;
message: T;
timestamp: Time;
data: Buffer;
chunkOffset: number;
totalChunks: number;
constructor(
// string: the topic the message was on
topic: string,
// any: the parsed body of the message based on connection.messageDefinition
message: T,
// time: the timestamp of the message
timestamp: Time,
// buffer: raw buffer data of the message
data: Buffer,
// the offset of the currently read chunk
chunkOffset: number,
// the total number of chunks in the read operation
totalChunks: number,
// freeze
freeze?: boolean,
);
}
declare class Record {
offset: number;
dataOffset: number;
end: number;
length: number;
/**
* Base class that represents a record of information from ROSBAG
* @param _fields
*/
constructor(_fields: { [key: string]: any });
parseData(_buffer: Buffer): void;
}
declare class BagHeader extends Record {
static opcode: number;
indexPosition: number;
connectionCount: number;
chunkCount: number;
constructor(fields: { [key: string]: Buffer });
}
declare class Chunk extends Record {
static opcode: number;
compression: string;
size: number;
data: Buffer;
constructor(fields: { [key: string]: Buffer });
parseData(buffer: Buffer): void;
}
declare class Connection extends Record {
static opcode: number;
conn: number;
topic: string;
type: string | undefined;
md5sum: string | undefined;
messageDefinition: string;
callerid: string | undefined;
latching: boolean | undefined;
reader: MessageReader | undefined;
constructor(fields: { [key: string]: Buffer });
parseData(buffer: Buffer): void;
}
declare class MessageData extends Record {
static opcode: number;
conn: number;
time: Time;
data: Buffer;
constructor(fields: { [key: string]: Buffer });
parseData(buffer: Buffer): void;
}
declare class IndexData extends Record {
static opcode: number;
ver: number;
conn: number;
count: number;
indices: Array<{ time: Time; offset: number }>;
constructor(fields: { [key: string]: Buffer });
parseData(buffer: Buffer): void;
}
declare class ChunkInfo extends Record {
static opcode: number;
ver: number;
chunkPosition: number;
startTime: Time;
endTime: Time;
count: number;
connections: Array<{ conn: number; count: number }>;
nextChunk: ChunkInfo | undefined;
constructor(fields: { [key: string]: Buffer });
parseData(buffer: Buffer): void;
}
export {
Callback,
TimeUtil,
BagReader,
MessageReader,
MessageWriter,
open,
parseMessageDefinition,
rosPrimitiveTypes,
extractFields,
extractTime,
};
export default Bag;
export as namespace rosbag; | the_stack |
const { Interpreter }: { Interpreter: any } = require("../../JS-Interpreter/interpreter");
import * as BT from "../binary_table";
import { Interpreter } from "./interpreter";
import { Content } from "../content";
import { getTrace, getLog } from "../util/trace";
import { Resources } from "../resource";
const domTrace = getTrace("js-interpreter.dom");
const eventTrace = getTrace("js-interpreter.event");
const browserLog = getLog("js-interpreter.browser");
const interpreterTrace = getTrace("js-interpreter");
const LAUNCH_DOCUMENT_CALLED = {};
/*
* Object
* Function
* Array
* String
* Boolean
* Number
* Date
* Math (運用しない)
* CSVTable (運用しない)
* BinaryTable
* browser
* XMLDoc (Class.XMLDocが1であればサポート)
* navigator (運用しない)
*/
import { BML } from "../interface/DOM";
import { BMLCSS2Properties } from "../interface/BMLCSS2Properties";
import { BrowserAPI } from "../browser";
import * as bmlDate from "../date";
import * as bmlNumber from "../number";
import * as bmlString from "../string";
import { EPG } from "../bml_browser";
function initNumber(interpreter: any, globalObject: any) {
var thisInterpreter = interpreter;
var wrapper;
// Number constructor.
wrapper = function Number(this: { data: number }, value: any) {
value = arguments.length ? Math.trunc(Interpreter.nativeGlobal.Number(value)) : 0;
if (thisInterpreter.calledWithNew()) {
// Called as `new Number()`.
this.data = value;
return this;
} else {
// Called as `Number()`.
return value;
}
};
interpreter.NUMBER = interpreter.createNativeFunction(wrapper, true);
interpreter.setProperty(globalObject, 'Number', interpreter.NUMBER,
Interpreter.NONENUMERABLE_DESCRIPTOR);
interpreter.setProperty(interpreter.NUMBER, "MAX_VALUE", bmlNumber.MAX_VALUE, Interpreter.NONCONFIGURABLE_READONLY_NONENUMERABLE_DESCRIPTOR);
interpreter.setProperty(interpreter.NUMBER, "MIN_VALUE", bmlNumber.MIN_VALUE, Interpreter.NONCONFIGURABLE_READONLY_NONENUMERABLE_DESCRIPTOR);
interpreter.setProperty(interpreter.NUMBER, "NaN", Number.NaN, Interpreter.NONCONFIGURABLE_READONLY_NONENUMERABLE_DESCRIPTOR);
wrapper = function toString(this: number, radix: number) {
try {
return Number(this).toString(radix);
} catch (e: any) {
// Throws if radix isn't within 2-36.
thisInterpreter.throwException(thisInterpreter.ERROR, e.message);
}
};
interpreter.setNativeFunctionPrototype(interpreter.NUMBER, 'toString', wrapper);
}
function initString(interpreter: any, globalObject: any) {
var wrapper;
// String constructor.
wrapper = function String(this: { data: string }, value: any) {
value = arguments.length ? globalThis.String(value) : '';
if (interpreter.calledWithNew()) {
// Called as `new String()`.
this.data = value;
return this;
} else {
// Called as `String()`.
return value;
}
};
interpreter.STRING = interpreter.createNativeFunction(wrapper, true);
interpreter.setProperty(globalObject, 'String', interpreter.STRING,
Interpreter.NONENUMERABLE_DESCRIPTOR);
// Static methods on String.
interpreter.setProperty(interpreter.STRING, "fromCharCode", interpreter.createNativeFunction(bmlString.eucJPFromCharCode, false), Interpreter.NONENUMERABLE_DESCRIPTOR);
// Instance methods on String.
// Methods with exclusively primitive arguments.
// toUpperCase/toLowerCaseは全角英字では動かずASCIIの範囲のみかも
var functions = ['charAt', 'indexOf', 'lastIndexOf', 'substring', 'toLowerCase', 'toUpperCase'];
for (var i = 0; i < functions.length; i++) {
interpreter.setNativeFunctionPrototype(interpreter.STRING, functions[i],
String.prototype[functions[i] as any]);
}
interpreter.setNativeFunctionPrototype(interpreter.STRING, "charCodeAt", bmlString.eucJPCharCodeAt);
wrapper = function split(this: string, separator: string) {
var string = String(this);
var jsList = string.split(separator);
return interpreter.arrayNativeToPseudo(jsList);
};
interpreter.setNativeFunctionPrototype(interpreter.STRING, 'split', wrapper);
}
export class JSInterpreter implements Interpreter {
interpreter: any;
nativeProtoToPseudoObject = new Map<any, any>();
domObjectToPseudo(interpreter: any, object: any): any {
const pseudo = this.nativeProtoToPseudoObject.get(Object.getPrototypeOf(object));
if (!pseudo) {
throw new Error("!?");
}
const wrapper = interpreter.createObjectProto(pseudo.properties["prototype"]);
wrapper.data = object;
return wrapper;
}
domClassToPseudo(interpreter: any, prototype: any): any {
const p = this.nativeProtoToPseudoObject.get(prototype);
if (p) {
return p;
}
const pseudo = interpreter.createNativeFunction(function elementWrapper(this: any) {
throw new TypeError("forbidden");
}, true);
const parent = Object.getPrototypeOf(prototype);
if (Object.getPrototypeOf(Object) !== parent) {
const parentPseudo = this.domClassToPseudo(interpreter, parent);
interpreter.setProperty(pseudo, "prototype", interpreter.createObject(parentPseudo), Interpreter.NONENUMERABLE_DESCRIPTOR);
}
const proto = pseudo.properties["prototype"];
interpreter.setProperty(pseudo, "name", prototype.constructor.name === "Function" ? prototype.name : prototype.constructor.name, Interpreter.NONENUMERABLE_DESCRIPTOR);
type PseudoDesc = {
configurable?: boolean;
enumerable?: boolean;
value?: any;
writable?: boolean;
get?: any;
set?: any;
};
const nativeProtoToPseudoObject = this.nativeProtoToPseudoObject;
const domObjectToPseudo = this.domObjectToPseudo.bind(this);
for (const [name, desc] of Object.entries(Object.getOwnPropertyDescriptors(prototype.prototype))) {
if (name === "constructor") {
continue;
}
const pseudoDesc: PseudoDesc = {};
const { get, set, value } = desc;
if (get) {
pseudoDesc.get = interpreter.createNativeFunction(function wrap(this: { data: any }) {
domTrace("get", name, this.data);
const result = get.bind(this.data)();
domTrace("=>", result);
if (result != null && nativeProtoToPseudoObject.has(Object.getPrototypeOf(result))) {
return domObjectToPseudo(interpreter, result);
}
return result;
});
}
if (set) {
pseudoDesc.set = interpreter.createNativeFunction(function wrap(this: { data: any }, value: any) {
domTrace("set", name, value, this.data);
set.bind(this.data)(value);
});
}
if (typeof value === "function") {
pseudoDesc.value = interpreter.createNativeFunction(function wrap(this: { data: any }, ...args: any[]) {
domTrace("call", name, value, this.data, args);
const result = value.bind(this.data)(...args);
domTrace("=>", result);
if (result != null && nativeProtoToPseudoObject.has(Object.getPrototypeOf(result))) {
return domObjectToPseudo(interpreter, result);
}
return result;
});
} else if (typeof value === "undefined") {
} else {
throw new Error("unreachable");
}
if ("enumerable" in desc) {
pseudoDesc.enumerable = desc["enumerable"];
}
if ("configurable" in desc) {
pseudoDesc.configurable = desc["configurable"];
}
if ("writable" in desc) {
pseudoDesc.enumerable = desc["writable"];
}
interpreter.setProperty(proto, name, Interpreter.VALUE_IN_DESCRIPTOR, pseudoDesc);
}
this.nativeProtoToPseudoObject.set(prototype.prototype, pseudo);
return pseudo;
}
registerDOMClasses(interpreter: any, globalObject: any) {
this.nativeProtoToPseudoObject.clear();
interpreter.setProperty(globalObject, "Node", this.domClassToPseudo(interpreter, BML.Node));
interpreter.setProperty(globalObject, "CharacterData", this.domClassToPseudo(interpreter, BML.CharacterData));
interpreter.setProperty(globalObject, "Text", this.domClassToPseudo(interpreter, BML.Text));
interpreter.setProperty(globalObject, "CDATASection", this.domClassToPseudo(interpreter, BML.CDATASection));
interpreter.setProperty(globalObject, "Document", this.domClassToPseudo(interpreter, BML.Document));
interpreter.setProperty(globalObject, "HTMLDocument", this.domClassToPseudo(interpreter, BML.HTMLDocument));
interpreter.setProperty(globalObject, "BMLDocument", this.domClassToPseudo(interpreter, BML.BMLDocument));
interpreter.setProperty(globalObject, "Element", this.domClassToPseudo(interpreter, BML.Element));
interpreter.setProperty(globalObject, "HTMLElement", this.domClassToPseudo(interpreter, BML.HTMLElement));
interpreter.setProperty(globalObject, "HTMLBRElement", this.domClassToPseudo(interpreter, BML.HTMLBRElement));
interpreter.setProperty(globalObject, "BMLBRElement", this.domClassToPseudo(interpreter, BML.BMLBRElement));
interpreter.setProperty(globalObject, "HTMLHtmlElement", this.domClassToPseudo(interpreter, BML.HTMLHtmlElement));
interpreter.setProperty(globalObject, "BMLBmlElement", this.domClassToPseudo(interpreter, BML.BMLBmlElement));
interpreter.setProperty(globalObject, "HTMLAnchorElement", this.domClassToPseudo(interpreter, BML.HTMLAnchorElement));
interpreter.setProperty(globalObject, "BMLAnchorElement", this.domClassToPseudo(interpreter, BML.BMLAnchorElement));
interpreter.setProperty(globalObject, "HTMLInputElement", this.domClassToPseudo(interpreter, BML.HTMLInputElement));
interpreter.setProperty(globalObject, "BMLInputElement", this.domClassToPseudo(interpreter, BML.BMLInputElement));
interpreter.setProperty(globalObject, "HTMLObjectElement", this.domClassToPseudo(interpreter, BML.HTMLObjectElement));
interpreter.setProperty(globalObject, "BMLObjectElement", this.domClassToPseudo(interpreter, BML.BMLObjectElement));
interpreter.setProperty(globalObject, "BMLSpanElement", this.domClassToPseudo(interpreter, BML.BMLSpanElement));
interpreter.setProperty(globalObject, "HTMLBodyElement", this.domClassToPseudo(interpreter, BML.HTMLBodyElement));
interpreter.setProperty(globalObject, "BMLBodyElement", this.domClassToPseudo(interpreter, BML.BMLBodyElement));
interpreter.setProperty(globalObject, "HTMLDivElement", this.domClassToPseudo(interpreter, BML.HTMLDivElement));
interpreter.setProperty(globalObject, "BMLDivElement", this.domClassToPseudo(interpreter, BML.BMLDivElement));
interpreter.setProperty(globalObject, "HTMLParagraphElement", this.domClassToPseudo(interpreter, BML.HTMLParagraphElement));
interpreter.setProperty(globalObject, "BMLParagraphElement", this.domClassToPseudo(interpreter, BML.BMLParagraphElement));
interpreter.setProperty(globalObject, "HTMLMetaElement", this.domClassToPseudo(interpreter, BML.HTMLMetaElement));
interpreter.setProperty(globalObject, "HTMLTitleElement", this.domClassToPseudo(interpreter, BML.HTMLTitleElement));
interpreter.setProperty(globalObject, "HTMLScriptElement", this.domClassToPseudo(interpreter, BML.HTMLScriptElement));
interpreter.setProperty(globalObject, "HTMLStyleElement", this.domClassToPseudo(interpreter, BML.HTMLStyleElement));
interpreter.setProperty(globalObject, "HTMLHeadElement", this.domClassToPseudo(interpreter, BML.HTMLHeadElement));
interpreter.setProperty(globalObject, "BMLBeventElement", this.domClassToPseudo(interpreter, BML.BMLBeventElement));
interpreter.setProperty(globalObject, "BMLBeitemElement", this.domClassToPseudo(interpreter, BML.BMLBeitemElement));
interpreter.setProperty(globalObject, "BMLEvent", this.domClassToPseudo(interpreter, BML.BMLEvent));
interpreter.setProperty(globalObject, "BMLIntrinsicEvent", this.domClassToPseudo(interpreter, BML.BMLIntrinsicEvent));
interpreter.setProperty(globalObject, "BMLBeventEvent", this.domClassToPseudo(interpreter, BML.BMLBeventEvent));
interpreter.setProperty(globalObject, "DOMImplementation", this.domClassToPseudo(interpreter, BML.DOMImplementation));
interpreter.setProperty(globalObject, "BMLCSS2Properties", this.domClassToPseudo(interpreter, BMLCSS2Properties));
}
public reset() {
const content = this.content;
function launchDocument(callback: (result: any, promiseValue: any) => void, documentName: string, transitionStyle: string | undefined): void {
browserLog("launchDocument", documentName, transitionStyle);
const r = content.launchDocument(String(documentName));
callback(r, LAUNCH_DOCUMENT_CALLED);
}
function reloadActiveDocument(callback: (result: any, promiseValue: any) => void): void {
browserLog("reloadActiveDocument");
const r = content.launchDocument(browser.getActiveDocument()!);
callback(r, LAUNCH_DOCUMENT_CALLED);
}
const epg = this.epg;
const resources = this.resources;
function epgTune(callback: (result: any, promiseValue: any) => void, service_ref: string): void {
browserLog("%cepgTune", "font-size: 4em", service_ref);
const { originalNetworkId, transportStreamId, serviceId } = resources.parseServiceReference(service_ref);
if (originalNetworkId == null || transportStreamId == null || serviceId == null) {
callback(NaN, LAUNCH_DOCUMENT_CALLED);
} else {
const r = epg.tune?.(originalNetworkId, transportStreamId, serviceId);
callback(r, LAUNCH_DOCUMENT_CALLED);
}
}
const browserAPI = this.browserAPI;
const browser = browserAPI.browser;
const asyncBrowser = browserAPI.asyncBrowser;
this.interpreter = new Interpreter("", (interpreter: any, globalObject: any) => {
interpreter.setProperty(globalObject, "___log", interpreter.createNativeFunction(function log(log: string) {
eventTrace(log);
}));
const pseudoBrowser = interpreter.nativeToPseudo(browser);
for (let i = 0; i < 64; i++) {
function defineRW2(pseudo: any, propName: string) {
interpreter.setProperty(pseudo, propName, Interpreter.VALUE_IN_DESCRIPTOR, {
get: interpreter.createNativeFunction(function getGreg(this: { data: any }) {
return browserAPI.getGreg(i);
}),
set: interpreter.createNativeFunction(function setGreg(this: { data: any }, value: any) {
browserAPI.setGreg(i, String(value));
}),
});
}
function defineRW3(pseudo: any, propName: string) {
interpreter.setProperty(pseudo, propName, Interpreter.VALUE_IN_DESCRIPTOR, {
get: interpreter.createNativeFunction(function getUreg(this: { data: any }) {
return browserAPI.getUreg(i);
}),
set: interpreter.createNativeFunction(function setUreg(this: { data: any }, value: any) {
browserAPI.setUreg(i, String(value));
}),
});
}
defineRW2(interpreter.getProperty(pseudoBrowser, "Greg"), i.toString());
defineRW3(interpreter.getProperty(pseudoBrowser, "Ureg"), i.toString());
}
interpreter.setProperty(globalObject, "browser", pseudoBrowser);
for (const prop in asyncBrowser) {
const asyncFunc = (asyncBrowser as any)[prop];
interpreter.setProperty(pseudoBrowser, prop, interpreter.createAsyncFunction(function asyncWrap(callback: (result: any, resolveValue: any) => void, ...args: any[]): void {
(asyncFunc(...args.map(x => interpreter.pseudoToNative(x))) as Promise<any>).then(result => {
callback(interpreter.nativeToPseudo(result), undefined);
});
}));
}
interpreter.setProperty(pseudoBrowser, "launchDocument", interpreter.createAsyncFunction(launchDocument));
interpreter.setProperty(pseudoBrowser, "reloadActiveDocument", interpreter.createAsyncFunction(reloadActiveDocument));
interpreter.setProperty(pseudoBrowser, "epgTune", interpreter.createAsyncFunction(epgTune));
interpreter.setProperty(pseudoBrowser, "readPersistentArray", interpreter.createNativeFunction(function readPersistentArray(filename: string, structure: string): any[] | null {
return interpreter.arrayNativeToPseudo(browser.readPersistentArray(filename, structure));
}));
interpreter.setProperty(pseudoBrowser, "writePersistentArray", interpreter.createNativeFunction(function writePersistentArray(filename: string, structure: string, data: any[], period?: Date): number {
return browser.writePersistentArray(filename, structure, interpreter.arrayPseudoToNative(data), period);
}));
const resources = this.resources;
interpreter.setProperty(pseudoBrowser, "getProgramID", interpreter.createAsyncFunction(function getProgramID(callback: (result: any, promiseValue: any) => void, type: number) {
resources.getProgramInfoAsync().then(_ => {
const pid = browser.getProgramID(type);
callback(pid, undefined);
});
}));
this.registerDOMClasses(interpreter, globalObject);
interpreter.setProperty(globalObject, "document", this.domObjectToPseudo(interpreter, this.content.bmlDocument));
const pseudoBinaryTable = interpreter.createAsyncFunction(function BinaryTable(this: any, callback: (result: any, resolveValue: any) => void, table_ref: string, structure: string) {
resources.fetchResourceAsync(table_ref).then(res => {
if (!res) {
browserLog("BinaryTable", table_ref, "not found");
callback(null, undefined);
return;
}
browserLog("new BinaryTable", table_ref);
let buffer: Uint8Array = res.data;
this.instance = new BT.BinaryTable(buffer, structure);
callback(this, undefined);
});
});
interpreter.setNativeFunctionPrototype(pseudoBinaryTable, "close", function close(this: { instance: BT.BinaryTable }) {
return this.instance.close();
});
interpreter.setNativeFunctionPrototype(pseudoBinaryTable, "toNumber", function toNumber(this: { instance: BT.BinaryTable }, row: number, column: number): number {
return this.instance.toNumber(row, column);
});
interpreter.setNativeFunctionPrototype(pseudoBinaryTable, "toString", function toString(this: { instance: BT.BinaryTable }, row: number, column: number): string | null {
return this.instance.toString(row, column);
});
interpreter.setNativeFunctionPrototype(pseudoBinaryTable, "toArray", function toArray(this: { instance: BT.BinaryTable }, startRow: number, numRow: number): any[] | null {
const r = this.instance.toArray(startRow, numRow);
if (r == null) {
return r;
}
return interpreter.arrayNativeToPseudo(r.map(x => interpreter.arrayNativeToPseudo(x)));
});
interpreter.setNativeFunctionPrototype(pseudoBinaryTable, "search", function toArray(this: { instance: BT.BinaryTable }, startRow: number, ...args: any[]): number {
const resultArray = args[args.length - 1];
args[args.length - 1] = interpreter.arrayPseudoToNative(args[args.length - 1]);
const result = this.instance.search(startRow, ...args);
// FIXME: errorshori
const props = Object.getOwnPropertyNames(args[args.length - 1]);
for (var i = 0; i < props.length; i++) {
interpreter.setProperty(resultArray, props[i], interpreter.nativeToPseudo(args[args.length - 1][props[i]]));
}
return result;
});
interpreter.setProperty(pseudoBinaryTable.properties["prototype"], "nrow", Interpreter.VALUE_IN_DESCRIPTOR, {
get: interpreter.createNativeFunction(function getNRow(this: { instance: BT.BinaryTable }) {
return this.instance.nrow;
})
});
interpreter.setProperty(pseudoBinaryTable.properties["prototype"], "ncolumn", Interpreter.VALUE_IN_DESCRIPTOR, {
get: interpreter.createNativeFunction(function getNColumn(this: { instance: BT.BinaryTable }) {
return this.instance.ncolumn;
})
});
interpreter.setProperty(globalObject, "BinaryTable", pseudoBinaryTable);
function initDate(interpreter: any, globalObject: any) {
var thisInterpreter = interpreter;
var wrapper;
// Date constructor.
wrapper = function Date(this: { data: Date }, value: any, _var_args: any) {
if (!thisInterpreter.calledWithNew()) {
// Called as `Date()`.
// Calling Date() as a function returns a string, no arguments are heeded.
console.error("Date()");
return Interpreter.nativeGlobal.Date();
}
// Called as `new Date(...)`.
var args = [null].concat(Array.from(arguments));
if (args.length <= 1 && value == null && resources.currentTimeUnixMillis != null) {
// currentDateMode=1ならtimeUnixMillisを取得した時間からオフセット追加とかが理想かもしれない
browserLog("new Date()");
this.data = new Interpreter.nativeGlobal.Date(resources.currentTimeUnixMillis);
} else {
this.data = new (Function.prototype.bind.apply(
Interpreter.nativeGlobal.Date, args as any));
}
return this;
};
interpreter.DATE = interpreter.createNativeFunction(wrapper, true);
interpreter.DATE_PROTO = interpreter.DATE.properties['prototype'];
interpreter.setProperty(globalObject, 'Date', interpreter.DATE,
Interpreter.NONENUMERABLE_DESCRIPTOR);
// Static methods on Date.
interpreter.setProperty(interpreter.DATE, 'now', interpreter.createNativeFunction(Date.now, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
interpreter.setProperty(interpreter.DATE, 'parse',
interpreter.createNativeFunction(Date.parse, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
interpreter.setProperty(interpreter.DATE, 'UTC', interpreter.createNativeFunction(Date.UTC, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
// Instance methods on Date.
var functions = ['getDate', 'getDay', 'getFullYear', 'getHours',
'getMilliseconds', 'getMinutes', 'getMonth', 'getSeconds', 'getTime',
'getTimezoneOffset', 'getUTCDate', 'getUTCDay', 'getUTCFullYear',
'getUTCHours', 'getUTCMilliseconds', 'getUTCMinutes', 'getUTCMonth',
'getUTCSeconds', 'getYear',
'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate',
'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes',
'setUTCMonth', 'setUTCSeconds', 'setYear',
'toDateString', 'toISOString', 'toJSON', 'toGMTString',
'toLocaleDateString', 'toLocaleString', 'toLocaleTimeString',
'toTimeString', 'toUTCString'];
for (var i = 0; i < functions.length; i++) {
wrapper = (function (nativeFunc) {
return function (this: { data: Date }, _var_args: any) {
var date = this.data;
if (!(date instanceof Date)) {
thisInterpreter.throwException(thisInterpreter.TYPE_ERROR,
nativeFunc + ' not called on a Date');
}
var args = [];
for (var i = 0; i < arguments.length; i++) {
args[i] = thisInterpreter.pseudoToNative(arguments[i]);
}
return (date as any)[nativeFunc].apply(date, args);
};
})(functions[i]);
interpreter.setNativeFunctionPrototype(interpreter.DATE, functions[i], wrapper);
}
interpreter.setNativeFunctionPrototype(interpreter.DATE, "toString", function (this: { data: Date }) {
browserLog("Date.toString()", this.data);
return bmlDate.toString.call(this.data);
});
interpreter.setNativeFunctionPrototype(interpreter.DATE, "toLocaleString", function (this: { data: Date }) {
browserLog("Date.toLocaleString()", this.data);
return bmlDate.toString.call(this.data);
});
interpreter.setNativeFunctionPrototype(interpreter.DATE, "toUTCString", function (this: { data: Date }) {
browserLog("Date.toUTCString()", this.data);
return bmlDate.toUTCString.call(this.data);
});
}
initDate(interpreter, globalObject);
initString(interpreter, globalObject);
initNumber(interpreter, globalObject);
});
this.resetStack();
}
_isExecuting: boolean;
// lazyinit
browserAPI: BrowserAPI = null!;
resources: Resources = null!;
content: Content = null!;
epg: EPG = null!;
public constructor() {
this._isExecuting = false;
}
public setupEnvironment(browserAPI: BrowserAPI, resources: Resources, content: Content, epg: EPG): void {
this.browserAPI = browserAPI;
this._isExecuting = false;
this.resources = resources;
this.content = content;
this.epg = epg;
this.reset();
}
public addScript(script: string, src?: string): Promise<boolean> {
this.interpreter.appendCode(script, src);
return this.runScript();
}
exeNum: number = 0;
async runScript(): Promise<boolean> {
if (this.isExecuting) {
throw new Error("this.isExecuting");
}
const prevContext = this.content.context;
let exit = false;
const exeNum = this.exeNum++;
interpreterTrace("runScript()", exeNum, prevContext, this.content.context);
try {
this._isExecuting = true;
while (true) {
interpreterTrace("RUN SCRIPT", exeNum, prevContext, this.content.context);
const r = await this.interpreter.runAsync(500, () => {
console.warn("script execution timeout");
return new Promise((resolve) => {
setTimeout(() => {
resolve(true);
}, 100);
});
});
interpreterTrace("RETURN RUN SCRIPT", exeNum, r, prevContext, this.content.context);
if (r === true) {
continue;
}
if (r === LAUNCH_DOCUMENT_CALLED) {
interpreterTrace("browser.launchDocument called.");
exit = true;
} else if (this.content.context !== prevContext) {
console.error("context switched", this.content.context, prevContext);
exit = true;
}
break;
}
if (!exit && this.content.context !== prevContext) {
console.error("context switched", this.content.context, prevContext);
exit = true;
}
} finally {
interpreterTrace("leave runScript()", exeNum, exit, prevContext, this.content.context);
if (exit) {
return true;
} else {
this._isExecuting = false;
}
}
return false;
}
public get isExecuting() {
return this._isExecuting;
}
public async runEventHandler(funcName: string): Promise<boolean> {
this.interpreter.appendCode(`___log(\"${funcName}\");${funcName}();`);
return await this.runScript();
}
public destroyStack(): void {
}
public resetStack(): void {
const state = new Interpreter.State(this.interpreter.ast, this.interpreter.globalScope);
state.done = false;
this.interpreter.stateStack.length = 0;
this.interpreter.stateStack[0] = state;
this._isExecuting = false;
}
} | the_stack |
import * as gax from 'google-gax';
import {
Callback,
CallOptions,
Descriptors,
ClientOptions,
PaginationCallback,
GaxCall,
} from 'google-gax';
import {Transform} from 'stream';
import {RequestType} from 'google-gax/build/src/apitypes';
import * as protos from '../../protos/protos';
import jsonProtos = require('../../protos/protos.json');
/**
* Client JSON configuration object, loaded from
* `src/v2/logging_service_v2_client_config.json`.
* This file defines retry strategy and timeouts for all API methods in this library.
*/
import * as gapicConfig from './logging_service_v2_client_config.json';
const version = require('../../../package.json').version;
/**
* Service for ingesting and querying logs.
* @class
* @memberof v2
*/
export class LoggingServiceV2Client {
private _terminated = false;
private _opts: ClientOptions;
private _providedCustomServicePath: boolean;
private _gaxModule: typeof gax | typeof gax.fallback;
private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient;
private _protos: {};
private _defaults: {[method: string]: gax.CallSettings};
auth: gax.GoogleAuth;
descriptors: Descriptors = {
page: {},
stream: {},
longrunning: {},
batching: {},
};
warn: (code: string, message: string, warnType?: string) => void;
innerApiCalls: {[name: string]: Function};
pathTemplates: {[name: string]: gax.PathTemplate};
loggingServiceV2Stub?: Promise<{[name: string]: Function}>;
/**
* Construct an instance of LoggingServiceV2Client.
*
* @param {object} [options] - The configuration object.
* The options accepted by the constructor are described in detail
* in [this document](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#creating-the-client-instance).
* The common options are:
* @param {object} [options.credentials] - Credentials object.
* @param {string} [options.credentials.client_email]
* @param {string} [options.credentials.private_key]
* @param {string} [options.email] - Account email address. Required when
* using a .pem or .p12 keyFilename.
* @param {string} [options.keyFilename] - Full path to the a .json, .pem, or
* .p12 key downloaded from the Google Developers Console. If you provide
* a path to a JSON file, the projectId option below is not necessary.
* NOTE: .pem and .p12 require you to specify options.email as well.
* @param {number} [options.port] - The port on which to connect to
* the remote host.
* @param {string} [options.projectId] - The project ID from the Google
* Developer's Console, e.g. 'grape-spaceship-123'. We will also check
* the environment variable GCLOUD_PROJECT for your project ID. If your
* app is running in an environment which supports
* {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials},
* your project ID will be detected automatically.
* @param {string} [options.apiEndpoint] - The domain name of the
* API remote host.
* @param {gax.ClientConfig} [options.clientConfig] - Client configuration override.
* Follows the structure of {@link gapicConfig}.
* @param {boolean} [options.fallback] - Use HTTP fallback mode.
* In fallback mode, a special browser-compatible transport implementation is used
* instead of gRPC transport. In browser context (if the `window` object is defined)
* the fallback mode is enabled automatically; set `options.fallback` to `false`
* if you need to override this behavior.
*/
constructor(opts?: ClientOptions) {
// Ensure that options include all the required fields.
const staticMembers = this.constructor as typeof LoggingServiceV2Client;
const servicePath =
opts?.servicePath || opts?.apiEndpoint || staticMembers.servicePath;
this._providedCustomServicePath = !!(
opts?.servicePath || opts?.apiEndpoint
);
const port = opts?.port || staticMembers.port;
const clientConfig = opts?.clientConfig ?? {};
const fallback =
opts?.fallback ??
(typeof window !== 'undefined' && typeof window?.fetch === 'function');
opts = Object.assign({servicePath, port, clientConfig, fallback}, opts);
// If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case.
if (servicePath !== staticMembers.servicePath && !('scopes' in opts)) {
opts['scopes'] = staticMembers.scopes;
}
// Choose either gRPC or proto-over-HTTP implementation of google-gax.
this._gaxModule = opts.fallback ? gax.fallback : gax;
// Create a `gaxGrpc` object, with any grpc-specific options sent to the client.
this._gaxGrpc = new this._gaxModule.GrpcClient(opts);
// Save options to use in initialize() method.
this._opts = opts;
// Save the auth object to the client, for use by other methods.
this.auth = this._gaxGrpc.auth as gax.GoogleAuth;
// Set useJWTAccessWithScope on the auth object.
this.auth.useJWTAccessWithScope = true;
// Set defaultServicePath on the auth object.
this.auth.defaultServicePath = staticMembers.servicePath;
// Set the default scopes in auth client if needed.
if (servicePath === staticMembers.servicePath) {
this.auth.defaultScopes = staticMembers.scopes;
}
// Determine the client header string.
const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`];
if (typeof process !== 'undefined' && 'versions' in process) {
clientHeader.push(`gl-node/${process.versions.node}`);
} else {
clientHeader.push(`gl-web/${this._gaxModule.version}`);
}
if (!opts.fallback) {
clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`);
} else if (opts.fallback === 'rest') {
clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`);
}
if (opts.libName && opts.libVersion) {
clientHeader.push(`${opts.libName}/${opts.libVersion}`);
}
// Load the applicable protos.
this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos);
// This API contains "path templates"; forward-slash-separated
// identifiers to uniquely identify resources within the API.
// Create useful helper objects for these.
this.pathTemplates = {
billingAccountCmekSettingsPathTemplate: new this._gaxModule.PathTemplate(
'billingAccounts/{billing_account}/cmekSettings'
),
billingAccountExclusionPathTemplate: new this._gaxModule.PathTemplate(
'billingAccounts/{billing_account}/exclusions/{exclusion}'
),
billingAccountLocationBucketPathTemplate:
new this._gaxModule.PathTemplate(
'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}'
),
billingAccountLocationBucketViewPathTemplate:
new this._gaxModule.PathTemplate(
'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}/views/{view}'
),
billingAccountLogPathTemplate: new this._gaxModule.PathTemplate(
'billingAccounts/{billing_account}/logs/{log}'
),
billingAccountSinkPathTemplate: new this._gaxModule.PathTemplate(
'billingAccounts/{billing_account}/sinks/{sink}'
),
folderCmekSettingsPathTemplate: new this._gaxModule.PathTemplate(
'folders/{folder}/cmekSettings'
),
folderExclusionPathTemplate: new this._gaxModule.PathTemplate(
'folders/{folder}/exclusions/{exclusion}'
),
folderLocationBucketPathTemplate: new this._gaxModule.PathTemplate(
'folders/{folder}/locations/{location}/buckets/{bucket}'
),
folderLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate(
'folders/{folder}/locations/{location}/buckets/{bucket}/views/{view}'
),
folderLogPathTemplate: new this._gaxModule.PathTemplate(
'folders/{folder}/logs/{log}'
),
folderSinkPathTemplate: new this._gaxModule.PathTemplate(
'folders/{folder}/sinks/{sink}'
),
logMetricPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/metrics/{metric}'
),
organizationCmekSettingsPathTemplate: new this._gaxModule.PathTemplate(
'organizations/{organization}/cmekSettings'
),
organizationExclusionPathTemplate: new this._gaxModule.PathTemplate(
'organizations/{organization}/exclusions/{exclusion}'
),
organizationLocationBucketPathTemplate: new this._gaxModule.PathTemplate(
'organizations/{organization}/locations/{location}/buckets/{bucket}'
),
organizationLocationBucketViewPathTemplate:
new this._gaxModule.PathTemplate(
'organizations/{organization}/locations/{location}/buckets/{bucket}/views/{view}'
),
organizationLogPathTemplate: new this._gaxModule.PathTemplate(
'organizations/{organization}/logs/{log}'
),
organizationSinkPathTemplate: new this._gaxModule.PathTemplate(
'organizations/{organization}/sinks/{sink}'
),
projectPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}'
),
projectCmekSettingsPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/cmekSettings'
),
projectExclusionPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/exclusions/{exclusion}'
),
projectLocationBucketPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/locations/{location}/buckets/{bucket}'
),
projectLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/locations/{location}/buckets/{bucket}/views/{view}'
),
projectLogPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/logs/{log}'
),
projectSinkPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/sinks/{sink}'
),
};
// Some of the methods on this service return "paged" results,
// (e.g. 50 results at a time, with tokens to get subsequent
// pages). Denote the keys used for pagination and results.
this.descriptors.page = {
listLogEntries: new this._gaxModule.PageDescriptor(
'pageToken',
'nextPageToken',
'entries'
),
listMonitoredResourceDescriptors: new this._gaxModule.PageDescriptor(
'pageToken',
'nextPageToken',
'resourceDescriptors'
),
listLogs: new this._gaxModule.PageDescriptor(
'pageToken',
'nextPageToken',
'logNames'
),
};
// Some of the methods on this service provide streaming responses.
// Provide descriptors for these.
this.descriptors.stream = {
tailLogEntries: new this._gaxModule.StreamDescriptor(
gax.StreamType.BIDI_STREAMING
),
};
const protoFilesRoot = this._gaxModule.protobuf.Root.fromJSON(jsonProtos);
// Some methods on this API support automatically batching
// requests; denote this.
this.descriptors.batching = {
writeLogEntries: new this._gaxModule.BundleDescriptor(
'entries',
['log_name', 'resource', 'labels'],
null,
gax.createByteLengthFunction(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
protoFilesRoot.lookupType('google.logging.v2.LogEntry') as any
)
),
};
// Put together the default options sent with requests.
this._defaults = this._gaxGrpc.constructSettings(
'google.logging.v2.LoggingServiceV2',
gapicConfig as gax.ClientConfig,
opts.clientConfig || {},
{'x-goog-api-client': clientHeader.join(' ')}
);
// Set up a dictionary of "inner API calls"; the core implementation
// of calling the API is handled in `google-gax`, with this code
// merely providing the destination and request information.
this.innerApiCalls = {};
// Add a warn function to the client constructor so it can be easily tested.
this.warn = gax.warn;
}
/**
* Initialize the client.
* Performs asynchronous operations (such as authentication) and prepares the client.
* This function will be called automatically when any class method is called for the
* first time, but if you need to initialize it before calling an actual method,
* feel free to call initialize() directly.
*
* You can await on this method if you want to make sure the client is initialized.
*
* @returns {Promise} A promise that resolves to an authenticated service stub.
*/
initialize() {
// If the client stub promise is already initialized, return immediately.
if (this.loggingServiceV2Stub) {
return this.loggingServiceV2Stub;
}
// Put together the "service stub" for
// google.logging.v2.LoggingServiceV2.
this.loggingServiceV2Stub = this._gaxGrpc.createStub(
this._opts.fallback
? (this._protos as protobuf.Root).lookupService(
'google.logging.v2.LoggingServiceV2'
)
: // eslint-disable-next-line @typescript-eslint/no-explicit-any
(this._protos as any).google.logging.v2.LoggingServiceV2,
this._opts,
this._providedCustomServicePath
) as Promise<{[method: string]: Function}>;
// Iterate over each of the methods that the service provides
// and create an API call method for each.
const loggingServiceV2StubMethods = [
'deleteLog',
'writeLogEntries',
'listLogEntries',
'listMonitoredResourceDescriptors',
'listLogs',
'tailLogEntries',
];
for (const methodName of loggingServiceV2StubMethods) {
const callPromise = this.loggingServiceV2Stub.then(
stub =>
(...args: Array<{}>) => {
if (this._terminated) {
return Promise.reject('The client has already been closed.');
}
const func = stub[methodName];
return func.apply(stub, args);
},
(err: Error | null | undefined) => () => {
throw err;
}
);
const descriptor =
this.descriptors.page[methodName] ||
this.descriptors.stream[methodName] ||
this.descriptors.batching?.[methodName] ||
undefined;
const apiCall = this._gaxModule.createApiCall(
callPromise,
this._defaults[methodName],
descriptor
);
this.innerApiCalls[methodName] = apiCall;
}
return this.loggingServiceV2Stub;
}
/**
* The DNS address for this API service.
* @returns {string} The DNS address for this service.
*/
static get servicePath() {
return 'logging.googleapis.com';
}
/**
* The DNS address for this API service - same as servicePath(),
* exists for compatibility reasons.
* @returns {string} The DNS address for this service.
*/
static get apiEndpoint() {
return 'logging.googleapis.com';
}
/**
* The port for this API service.
* @returns {number} The default port for this service.
*/
static get port() {
return 443;
}
/**
* The scopes needed to make gRPC calls for every method defined
* in this service.
* @returns {string[]} List of default scopes.
*/
static get scopes() {
return [
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/cloud-platform.read-only',
'https://www.googleapis.com/auth/logging.admin',
'https://www.googleapis.com/auth/logging.read',
'https://www.googleapis.com/auth/logging.write',
];
}
getProjectId(): Promise<string>;
getProjectId(callback: Callback<string, undefined, undefined>): void;
/**
* Return the project ID used by this class.
* @returns {Promise} A promise that resolves to string containing the project ID.
*/
getProjectId(
callback?: Callback<string, undefined, undefined>
): Promise<string> | void {
if (callback) {
this.auth.getProjectId(callback);
return;
}
return this.auth.getProjectId();
}
// -------------------
// -- Service calls --
// -------------------
/**
* Deletes all the log entries in a log. The log reappears if it receives new
* entries. Log entries written shortly before the delete operation might not
* be deleted. Entries received after the delete operation with a timestamp
* before the operation will be deleted.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.logName
* Required. The resource name of the log to delete:
*
* "projects/[PROJECT_ID]/logs/[LOG_ID]"
* "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]"
* "folders/[FOLDER_ID]/logs/[LOG_ID]"
*
* `[LOG_ID]` must be URL-encoded. For example,
* `"projects/my-project-id/logs/syslog"`,
* `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`.
* For more information about log names, see
* {@link google.logging.v2.LogEntry|LogEntry}.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Empty]{@link google.protobuf.Empty}.
* Please see the
* [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods)
* for more details and examples.
* @example <caption>include:samples/generated/v2/logging_service_v2.delete_log.js</caption>
* region_tag:logging_v2_generated_LoggingServiceV2_DeleteLog_async
*/
deleteLog(
request?: protos.google.logging.v2.IDeleteLogRequest,
options?: CallOptions
): Promise<
[
protos.google.protobuf.IEmpty,
protos.google.logging.v2.IDeleteLogRequest | undefined,
{} | undefined
]
>;
deleteLog(
request: protos.google.logging.v2.IDeleteLogRequest,
options: CallOptions,
callback: Callback<
protos.google.protobuf.IEmpty,
protos.google.logging.v2.IDeleteLogRequest | null | undefined,
{} | null | undefined
>
): void;
deleteLog(
request: protos.google.logging.v2.IDeleteLogRequest,
callback: Callback<
protos.google.protobuf.IEmpty,
protos.google.logging.v2.IDeleteLogRequest | null | undefined,
{} | null | undefined
>
): void;
deleteLog(
request?: protos.google.logging.v2.IDeleteLogRequest,
optionsOrCallback?:
| CallOptions
| Callback<
protos.google.protobuf.IEmpty,
protos.google.logging.v2.IDeleteLogRequest | null | undefined,
{} | null | undefined
>,
callback?: Callback<
protos.google.protobuf.IEmpty,
protos.google.logging.v2.IDeleteLogRequest | null | undefined,
{} | null | undefined
>
): Promise<
[
protos.google.protobuf.IEmpty,
protos.google.logging.v2.IDeleteLogRequest | undefined,
{} | undefined
]
> | void {
request = request || {};
let options: CallOptions;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
} else {
options = optionsOrCallback as CallOptions;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
gax.routingHeader.fromParams({
log_name: request.logName || '',
});
this.initialize();
return this.innerApiCalls.deleteLog(request, options, callback);
}
/**
* Writes log entries to Logging. This API method is the
* only way to send log entries to Logging. This method
* is used, directly or indirectly, by the Logging agent
* (fluentd) and all logging libraries configured to use Logging.
* A single request may contain log entries for a maximum of 1000
* different resources (projects, organizations, billing accounts or
* folders)
*
* @param {Object} request
* The request object that will be sent.
* @param {string} [request.logName]
* Optional. A default log resource name that is assigned to all log entries
* in `entries` that do not specify a value for `log_name`:
*
* "projects/[PROJECT_ID]/logs/[LOG_ID]"
* "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]"
* "folders/[FOLDER_ID]/logs/[LOG_ID]"
*
* `[LOG_ID]` must be URL-encoded. For example:
*
* "projects/my-project-id/logs/syslog"
* "organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"
*
* The permission `logging.logEntries.create` is needed on each project,
* organization, billing account, or folder that is receiving new log
* entries, whether the resource is specified in `logName` or in an
* individual log entry.
* @param {google.api.MonitoredResource} [request.resource]
* Optional. A default monitored resource object that is assigned to all log
* entries in `entries` that do not specify a value for `resource`. Example:
*
* { "type": "gce_instance",
* "labels": {
* "zone": "us-central1-a", "instance_id": "00000000000000000000" }}
*
* See {@link google.logging.v2.LogEntry|LogEntry}.
* @param {number[]} [request.labels]
* Optional. Default labels that are added to the `labels` field of all log
* entries in `entries`. If a log entry already has a label with the same key
* as a label in this parameter, then the log entry's label is not changed.
* See {@link google.logging.v2.LogEntry|LogEntry}.
* @param {number[]} request.entries
* Required. The log entries to send to Logging. The order of log
* entries in this list does not matter. Values supplied in this method's
* `log_name`, `resource`, and `labels` fields are copied into those log
* entries in this list that do not include values for their corresponding
* fields. For more information, see the
* {@link google.logging.v2.LogEntry|LogEntry} type.
*
* If the `timestamp` or `insert_id` fields are missing in log entries, then
* this method supplies the current time or a unique identifier, respectively.
* The supplied values are chosen so that, among the log entries that did not
* supply their own values, the entries earlier in the list will sort before
* the entries later in the list. See the `entries.list` method.
*
* Log entries with timestamps that are more than the
* [logs retention period](https://cloud.google.com/logging/quota-policy) in
* the past or more than 24 hours in the future will not be available when
* calling `entries.list`. However, those log entries can still be [exported
* with
* LogSinks](https://cloud.google.com/logging/docs/api/tasks/exporting-logs).
*
* To improve throughput and to avoid exceeding the
* [quota limit](https://cloud.google.com/logging/quota-policy) for calls to
* `entries.write`, you should try to include several log entries in this
* list, rather than calling this method for each individual log entry.
* @param {boolean} [request.partialSuccess]
* Optional. Whether valid entries should be written even if some other
* entries fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any
* entry is not written, then the response status is the error associated
* with one of the failed entries and the response includes error details
* keyed by the entries' zero-based index in the `entries.write` method.
* @param {boolean} [request.dryRun]
* Optional. If true, the request should expect normal response, but the
* entries won't be persisted nor exported. Useful for checking whether the
* logging API endpoints are working properly before sending valuable data.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [WriteLogEntriesResponse]{@link google.logging.v2.WriteLogEntriesResponse}.
* Please see the
* [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods)
* for more details and examples.
* @example <caption>include:samples/generated/v2/logging_service_v2.write_log_entries.js</caption>
* region_tag:logging_v2_generated_LoggingServiceV2_WriteLogEntries_async
*/
writeLogEntries(
request?: protos.google.logging.v2.IWriteLogEntriesRequest,
options?: CallOptions
): Promise<
[
protos.google.logging.v2.IWriteLogEntriesResponse,
protos.google.logging.v2.IWriteLogEntriesRequest | undefined,
{} | undefined
]
>;
writeLogEntries(
request: protos.google.logging.v2.IWriteLogEntriesRequest,
options: CallOptions,
callback: Callback<
protos.google.logging.v2.IWriteLogEntriesResponse,
protos.google.logging.v2.IWriteLogEntriesRequest | null | undefined,
{} | null | undefined
>
): void;
writeLogEntries(
request: protos.google.logging.v2.IWriteLogEntriesRequest,
callback: Callback<
protos.google.logging.v2.IWriteLogEntriesResponse,
protos.google.logging.v2.IWriteLogEntriesRequest | null | undefined,
{} | null | undefined
>
): void;
writeLogEntries(
request?: protos.google.logging.v2.IWriteLogEntriesRequest,
optionsOrCallback?:
| CallOptions
| Callback<
protos.google.logging.v2.IWriteLogEntriesResponse,
protos.google.logging.v2.IWriteLogEntriesRequest | null | undefined,
{} | null | undefined
>,
callback?: Callback<
protos.google.logging.v2.IWriteLogEntriesResponse,
protos.google.logging.v2.IWriteLogEntriesRequest | null | undefined,
{} | null | undefined
>
): Promise<
[
protos.google.logging.v2.IWriteLogEntriesResponse,
protos.google.logging.v2.IWriteLogEntriesRequest | undefined,
{} | undefined
]
> | void {
request = request || {};
let options: CallOptions;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
} else {
options = optionsOrCallback as CallOptions;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
this.initialize();
return this.innerApiCalls.writeLogEntries(request, options, callback);
}
/**
* Streaming read of log entries as they are ingested. Until the stream is
* terminated, it will continue reading logs.
*
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Stream}
* An object stream which is both readable and writable. It accepts objects
* representing [TailLogEntriesRequest]{@link google.logging.v2.TailLogEntriesRequest} for write() method, and
* will emit objects representing [TailLogEntriesResponse]{@link google.logging.v2.TailLogEntriesResponse} on 'data' event asynchronously.
* Please see the
* [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming)
* for more details and examples.
* @example <caption>include:samples/generated/v2/logging_service_v2.tail_log_entries.js</caption>
* region_tag:logging_v2_generated_LoggingServiceV2_TailLogEntries_async
*/
tailLogEntries(options?: CallOptions): gax.CancellableStream {
this.initialize();
return this.innerApiCalls.tailLogEntries(options);
}
/**
* Lists log entries. Use this method to retrieve log entries that originated
* from a project/folder/organization/billing account. For ways to export log
* entries, see [Exporting
* Logs](https://cloud.google.com/logging/docs/export).
*
* @param {Object} request
* The request object that will be sent.
* @param {string[]} request.resourceNames
* Required. Names of one or more parent resources from which to
* retrieve log entries:
*
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
*
* May alternatively be one or more views
* projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* organization/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
*
* Projects listed in the `project_ids` field are added to this list.
* @param {string} [request.filter]
* Optional. A filter that chooses which log entries to return. See [Advanced
* Logs Queries](https://cloud.google.com/logging/docs/view/advanced-queries).
* Only log entries that match the filter are returned. An empty filter
* matches all log entries in the resources listed in `resource_names`.
* Referencing a parent resource that is not listed in `resource_names` will
* cause the filter to return no results. The maximum length of the filter is
* 20000 characters.
* @param {string} [request.orderBy]
* Optional. How the results should be sorted. Presently, the only permitted
* values are `"timestamp asc"` (default) and `"timestamp desc"`. The first
* option returns entries in order of increasing values of
* `LogEntry.timestamp` (oldest first), and the second option returns entries
* in order of decreasing timestamps (newest first). Entries with equal
* timestamps are returned in order of their `insert_id` values.
* @param {number} [request.pageSize]
* Optional. The maximum number of results to return from this request.
* Default is 50. If the value is negative or exceeds 1000,
* the request is rejected. The presence of `next_page_token` in the
* response indicates that more results might be available.
* @param {string} [request.pageToken]
* Optional. If present, then retrieve the next batch of results from the
* preceding call to this method. `page_token` must be the value of
* `next_page_token` from the previous response. The values of other method
* parameters should be identical to those in the previous call.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is Array of [LogEntry]{@link google.logging.v2.LogEntry}.
* The client library will perform auto-pagination by default: it will call the API as many
* times as needed and will merge results from all the pages into this array.
* Note that it can affect your quota.
* We recommend using `listLogEntriesAsync()`
* method described below for async iteration which you can stop as needed.
* Please see the
* [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination)
* for more details and examples.
*/
listLogEntries(
request?: protos.google.logging.v2.IListLogEntriesRequest,
options?: CallOptions
): Promise<
[
protos.google.logging.v2.ILogEntry[],
protos.google.logging.v2.IListLogEntriesRequest | null,
protos.google.logging.v2.IListLogEntriesResponse
]
>;
listLogEntries(
request: protos.google.logging.v2.IListLogEntriesRequest,
options: CallOptions,
callback: PaginationCallback<
protos.google.logging.v2.IListLogEntriesRequest,
protos.google.logging.v2.IListLogEntriesResponse | null | undefined,
protos.google.logging.v2.ILogEntry
>
): void;
listLogEntries(
request: protos.google.logging.v2.IListLogEntriesRequest,
callback: PaginationCallback<
protos.google.logging.v2.IListLogEntriesRequest,
protos.google.logging.v2.IListLogEntriesResponse | null | undefined,
protos.google.logging.v2.ILogEntry
>
): void;
listLogEntries(
request?: protos.google.logging.v2.IListLogEntriesRequest,
optionsOrCallback?:
| CallOptions
| PaginationCallback<
protos.google.logging.v2.IListLogEntriesRequest,
protos.google.logging.v2.IListLogEntriesResponse | null | undefined,
protos.google.logging.v2.ILogEntry
>,
callback?: PaginationCallback<
protos.google.logging.v2.IListLogEntriesRequest,
protos.google.logging.v2.IListLogEntriesResponse | null | undefined,
protos.google.logging.v2.ILogEntry
>
): Promise<
[
protos.google.logging.v2.ILogEntry[],
protos.google.logging.v2.IListLogEntriesRequest | null,
protos.google.logging.v2.IListLogEntriesResponse
]
> | void {
request = request || {};
let options: CallOptions;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
} else {
options = optionsOrCallback as CallOptions;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
this.initialize();
return this.innerApiCalls.listLogEntries(request, options, callback);
}
/**
* Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object.
* @param {Object} request
* The request object that will be sent.
* @param {string[]} request.resourceNames
* Required. Names of one or more parent resources from which to
* retrieve log entries:
*
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
*
* May alternatively be one or more views
* projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* organization/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
*
* Projects listed in the `project_ids` field are added to this list.
* @param {string} [request.filter]
* Optional. A filter that chooses which log entries to return. See [Advanced
* Logs Queries](https://cloud.google.com/logging/docs/view/advanced-queries).
* Only log entries that match the filter are returned. An empty filter
* matches all log entries in the resources listed in `resource_names`.
* Referencing a parent resource that is not listed in `resource_names` will
* cause the filter to return no results. The maximum length of the filter is
* 20000 characters.
* @param {string} [request.orderBy]
* Optional. How the results should be sorted. Presently, the only permitted
* values are `"timestamp asc"` (default) and `"timestamp desc"`. The first
* option returns entries in order of increasing values of
* `LogEntry.timestamp` (oldest first), and the second option returns entries
* in order of decreasing timestamps (newest first). Entries with equal
* timestamps are returned in order of their `insert_id` values.
* @param {number} [request.pageSize]
* Optional. The maximum number of results to return from this request.
* Default is 50. If the value is negative or exceeds 1000,
* the request is rejected. The presence of `next_page_token` in the
* response indicates that more results might be available.
* @param {string} [request.pageToken]
* Optional. If present, then retrieve the next batch of results from the
* preceding call to this method. `page_token` must be the value of
* `next_page_token` from the previous response. The values of other method
* parameters should be identical to those in the previous call.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Stream}
* An object stream which emits an object representing [LogEntry]{@link google.logging.v2.LogEntry} on 'data' event.
* The client library will perform auto-pagination by default: it will call the API as many
* times as needed. Note that it can affect your quota.
* We recommend using `listLogEntriesAsync()`
* method described below for async iteration which you can stop as needed.
* Please see the
* [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination)
* for more details and examples.
*/
listLogEntriesStream(
request?: protos.google.logging.v2.IListLogEntriesRequest,
options?: CallOptions
): Transform {
request = request || {};
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
const defaultCallSettings = this._defaults['listLogEntries'];
const callSettings = defaultCallSettings.merge(options);
this.initialize();
return this.descriptors.page.listLogEntries.createStream(
this.innerApiCalls.listLogEntries as gax.GaxCall,
request,
callSettings
);
}
/**
* Equivalent to `listLogEntries`, but returns an iterable object.
*
* `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand.
* @param {Object} request
* The request object that will be sent.
* @param {string[]} request.resourceNames
* Required. Names of one or more parent resources from which to
* retrieve log entries:
*
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
*
* May alternatively be one or more views
* projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* organization/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
*
* Projects listed in the `project_ids` field are added to this list.
* @param {string} [request.filter]
* Optional. A filter that chooses which log entries to return. See [Advanced
* Logs Queries](https://cloud.google.com/logging/docs/view/advanced-queries).
* Only log entries that match the filter are returned. An empty filter
* matches all log entries in the resources listed in `resource_names`.
* Referencing a parent resource that is not listed in `resource_names` will
* cause the filter to return no results. The maximum length of the filter is
* 20000 characters.
* @param {string} [request.orderBy]
* Optional. How the results should be sorted. Presently, the only permitted
* values are `"timestamp asc"` (default) and `"timestamp desc"`. The first
* option returns entries in order of increasing values of
* `LogEntry.timestamp` (oldest first), and the second option returns entries
* in order of decreasing timestamps (newest first). Entries with equal
* timestamps are returned in order of their `insert_id` values.
* @param {number} [request.pageSize]
* Optional. The maximum number of results to return from this request.
* Default is 50. If the value is negative or exceeds 1000,
* the request is rejected. The presence of `next_page_token` in the
* response indicates that more results might be available.
* @param {string} [request.pageToken]
* Optional. If present, then retrieve the next batch of results from the
* preceding call to this method. `page_token` must be the value of
* `next_page_token` from the previous response. The values of other method
* parameters should be identical to those in the previous call.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Object}
* An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols).
* When you iterate the returned iterable, each element will be an object representing
* [LogEntry]{@link google.logging.v2.LogEntry}. The API will be called under the hood as needed, once per the page,
* so you can stop the iteration when you don't need more results.
* Please see the
* [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination)
* for more details and examples.
* @example <caption>include:samples/generated/v2/logging_service_v2.list_log_entries.js</caption>
* region_tag:logging_v2_generated_LoggingServiceV2_ListLogEntries_async
*/
listLogEntriesAsync(
request?: protos.google.logging.v2.IListLogEntriesRequest,
options?: CallOptions
): AsyncIterable<protos.google.logging.v2.ILogEntry> {
request = request || {};
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
const defaultCallSettings = this._defaults['listLogEntries'];
const callSettings = defaultCallSettings.merge(options);
this.initialize();
return this.descriptors.page.listLogEntries.asyncIterate(
this.innerApiCalls['listLogEntries'] as GaxCall,
request as unknown as RequestType,
callSettings
) as AsyncIterable<protos.google.logging.v2.ILogEntry>;
}
/**
* Lists the descriptors for monitored resource types used by Logging.
*
* @param {Object} request
* The request object that will be sent.
* @param {number} [request.pageSize]
* Optional. The maximum number of results to return from this request.
* Non-positive values are ignored. The presence of `nextPageToken` in the
* response indicates that more results might be available.
* @param {string} [request.pageToken]
* Optional. If present, then retrieve the next batch of results from the
* preceding call to this method. `pageToken` must be the value of
* `nextPageToken` from the previous response. The values of other method
* parameters should be identical to those in the previous call.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is Array of [MonitoredResourceDescriptor]{@link google.api.MonitoredResourceDescriptor}.
* The client library will perform auto-pagination by default: it will call the API as many
* times as needed and will merge results from all the pages into this array.
* Note that it can affect your quota.
* We recommend using `listMonitoredResourceDescriptorsAsync()`
* method described below for async iteration which you can stop as needed.
* Please see the
* [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination)
* for more details and examples.
*/
listMonitoredResourceDescriptors(
request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest,
options?: CallOptions
): Promise<
[
protos.google.api.IMonitoredResourceDescriptor[],
protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest | null,
protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse
]
>;
listMonitoredResourceDescriptors(
request: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest,
options: CallOptions,
callback: PaginationCallback<
protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest,
| protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse
| null
| undefined,
protos.google.api.IMonitoredResourceDescriptor
>
): void;
listMonitoredResourceDescriptors(
request: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest,
callback: PaginationCallback<
protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest,
| protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse
| null
| undefined,
protos.google.api.IMonitoredResourceDescriptor
>
): void;
listMonitoredResourceDescriptors(
request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest,
optionsOrCallback?:
| CallOptions
| PaginationCallback<
protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest,
| protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse
| null
| undefined,
protos.google.api.IMonitoredResourceDescriptor
>,
callback?: PaginationCallback<
protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest,
| protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse
| null
| undefined,
protos.google.api.IMonitoredResourceDescriptor
>
): Promise<
[
protos.google.api.IMonitoredResourceDescriptor[],
protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest | null,
protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse
]
> | void {
request = request || {};
let options: CallOptions;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
} else {
options = optionsOrCallback as CallOptions;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
this.initialize();
return this.innerApiCalls.listMonitoredResourceDescriptors(
request,
options,
callback
);
}
/**
* Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object.
* @param {Object} request
* The request object that will be sent.
* @param {number} [request.pageSize]
* Optional. The maximum number of results to return from this request.
* Non-positive values are ignored. The presence of `nextPageToken` in the
* response indicates that more results might be available.
* @param {string} [request.pageToken]
* Optional. If present, then retrieve the next batch of results from the
* preceding call to this method. `pageToken` must be the value of
* `nextPageToken` from the previous response. The values of other method
* parameters should be identical to those in the previous call.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Stream}
* An object stream which emits an object representing [MonitoredResourceDescriptor]{@link google.api.MonitoredResourceDescriptor} on 'data' event.
* The client library will perform auto-pagination by default: it will call the API as many
* times as needed. Note that it can affect your quota.
* We recommend using `listMonitoredResourceDescriptorsAsync()`
* method described below for async iteration which you can stop as needed.
* Please see the
* [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination)
* for more details and examples.
*/
listMonitoredResourceDescriptorsStream(
request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest,
options?: CallOptions
): Transform {
request = request || {};
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
const defaultCallSettings =
this._defaults['listMonitoredResourceDescriptors'];
const callSettings = defaultCallSettings.merge(options);
this.initialize();
return this.descriptors.page.listMonitoredResourceDescriptors.createStream(
this.innerApiCalls.listMonitoredResourceDescriptors as gax.GaxCall,
request,
callSettings
);
}
/**
* Equivalent to `listMonitoredResourceDescriptors`, but returns an iterable object.
*
* `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand.
* @param {Object} request
* The request object that will be sent.
* @param {number} [request.pageSize]
* Optional. The maximum number of results to return from this request.
* Non-positive values are ignored. The presence of `nextPageToken` in the
* response indicates that more results might be available.
* @param {string} [request.pageToken]
* Optional. If present, then retrieve the next batch of results from the
* preceding call to this method. `pageToken` must be the value of
* `nextPageToken` from the previous response. The values of other method
* parameters should be identical to those in the previous call.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Object}
* An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols).
* When you iterate the returned iterable, each element will be an object representing
* [MonitoredResourceDescriptor]{@link google.api.MonitoredResourceDescriptor}. The API will be called under the hood as needed, once per the page,
* so you can stop the iteration when you don't need more results.
* Please see the
* [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination)
* for more details and examples.
* @example <caption>include:samples/generated/v2/logging_service_v2.list_monitored_resource_descriptors.js</caption>
* region_tag:logging_v2_generated_LoggingServiceV2_ListMonitoredResourceDescriptors_async
*/
listMonitoredResourceDescriptorsAsync(
request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest,
options?: CallOptions
): AsyncIterable<protos.google.api.IMonitoredResourceDescriptor> {
request = request || {};
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
const defaultCallSettings =
this._defaults['listMonitoredResourceDescriptors'];
const callSettings = defaultCallSettings.merge(options);
this.initialize();
return this.descriptors.page.listMonitoredResourceDescriptors.asyncIterate(
this.innerApiCalls['listMonitoredResourceDescriptors'] as GaxCall,
request as unknown as RequestType,
callSettings
) as AsyncIterable<protos.google.api.IMonitoredResourceDescriptor>;
}
/**
* Lists the logs in projects, organizations, folders, or billing accounts.
* Only logs that have entries are listed.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The resource name that owns the logs:
*
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* @param {number} [request.pageSize]
* Optional. The maximum number of results to return from this request.
* Non-positive values are ignored. The presence of `nextPageToken` in the
* response indicates that more results might be available.
* @param {string} [request.pageToken]
* Optional. If present, then retrieve the next batch of results from the
* preceding call to this method. `pageToken` must be the value of
* `nextPageToken` from the previous response. The values of other method
* parameters should be identical to those in the previous call.
* @param {string[]} [request.resourceNames]
* Optional. The resource name that owns the logs:
* projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* organization/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
*
* To support legacy queries, it could also be:
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is Array of string.
* The client library will perform auto-pagination by default: it will call the API as many
* times as needed and will merge results from all the pages into this array.
* Note that it can affect your quota.
* We recommend using `listLogsAsync()`
* method described below for async iteration which you can stop as needed.
* Please see the
* [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination)
* for more details and examples.
*/
listLogs(
request?: protos.google.logging.v2.IListLogsRequest,
options?: CallOptions
): Promise<
[
string[],
protos.google.logging.v2.IListLogsRequest | null,
protos.google.logging.v2.IListLogsResponse
]
>;
listLogs(
request: protos.google.logging.v2.IListLogsRequest,
options: CallOptions,
callback: PaginationCallback<
protos.google.logging.v2.IListLogsRequest,
protos.google.logging.v2.IListLogsResponse | null | undefined,
string
>
): void;
listLogs(
request: protos.google.logging.v2.IListLogsRequest,
callback: PaginationCallback<
protos.google.logging.v2.IListLogsRequest,
protos.google.logging.v2.IListLogsResponse | null | undefined,
string
>
): void;
listLogs(
request?: protos.google.logging.v2.IListLogsRequest,
optionsOrCallback?:
| CallOptions
| PaginationCallback<
protos.google.logging.v2.IListLogsRequest,
protos.google.logging.v2.IListLogsResponse | null | undefined,
string
>,
callback?: PaginationCallback<
protos.google.logging.v2.IListLogsRequest,
protos.google.logging.v2.IListLogsResponse | null | undefined,
string
>
): Promise<
[
string[],
protos.google.logging.v2.IListLogsRequest | null,
protos.google.logging.v2.IListLogsResponse
]
> | void {
request = request || {};
let options: CallOptions;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
} else {
options = optionsOrCallback as CallOptions;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
gax.routingHeader.fromParams({
parent: request.parent || '',
});
this.initialize();
return this.innerApiCalls.listLogs(request, options, callback);
}
/**
* Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object.
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The resource name that owns the logs:
*
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* @param {number} [request.pageSize]
* Optional. The maximum number of results to return from this request.
* Non-positive values are ignored. The presence of `nextPageToken` in the
* response indicates that more results might be available.
* @param {string} [request.pageToken]
* Optional. If present, then retrieve the next batch of results from the
* preceding call to this method. `pageToken` must be the value of
* `nextPageToken` from the previous response. The values of other method
* parameters should be identical to those in the previous call.
* @param {string[]} [request.resourceNames]
* Optional. The resource name that owns the logs:
* projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* organization/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
*
* To support legacy queries, it could also be:
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Stream}
* An object stream which emits an object representing string on 'data' event.
* The client library will perform auto-pagination by default: it will call the API as many
* times as needed. Note that it can affect your quota.
* We recommend using `listLogsAsync()`
* method described below for async iteration which you can stop as needed.
* Please see the
* [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination)
* for more details and examples.
*/
listLogsStream(
request?: protos.google.logging.v2.IListLogsRequest,
options?: CallOptions
): Transform {
request = request || {};
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
gax.routingHeader.fromParams({
parent: request.parent || '',
});
const defaultCallSettings = this._defaults['listLogs'];
const callSettings = defaultCallSettings.merge(options);
this.initialize();
return this.descriptors.page.listLogs.createStream(
this.innerApiCalls.listLogs as gax.GaxCall,
request,
callSettings
);
}
/**
* Equivalent to `listLogs`, but returns an iterable object.
*
* `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand.
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The resource name that owns the logs:
*
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* @param {number} [request.pageSize]
* Optional. The maximum number of results to return from this request.
* Non-positive values are ignored. The presence of `nextPageToken` in the
* response indicates that more results might be available.
* @param {string} [request.pageToken]
* Optional. If present, then retrieve the next batch of results from the
* preceding call to this method. `pageToken` must be the value of
* `nextPageToken` from the previous response. The values of other method
* parameters should be identical to those in the previous call.
* @param {string[]} [request.resourceNames]
* Optional. The resource name that owns the logs:
* projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* organization/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
* folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]
*
* To support legacy queries, it could also be:
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Object}
* An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols).
* When you iterate the returned iterable, each element will be an object representing
* string. The API will be called under the hood as needed, once per the page,
* so you can stop the iteration when you don't need more results.
* Please see the
* [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination)
* for more details and examples.
* @example <caption>include:samples/generated/v2/logging_service_v2.list_logs.js</caption>
* region_tag:logging_v2_generated_LoggingServiceV2_ListLogs_async
*/
listLogsAsync(
request?: protos.google.logging.v2.IListLogsRequest,
options?: CallOptions
): AsyncIterable<string> {
request = request || {};
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
gax.routingHeader.fromParams({
parent: request.parent || '',
});
const defaultCallSettings = this._defaults['listLogs'];
const callSettings = defaultCallSettings.merge(options);
this.initialize();
return this.descriptors.page.listLogs.asyncIterate(
this.innerApiCalls['listLogs'] as GaxCall,
request as unknown as RequestType,
callSettings
) as AsyncIterable<string>;
}
// --------------------
// -- Path templates --
// --------------------
/**
* Return a fully-qualified billingAccountCmekSettings resource name string.
*
* @param {string} billing_account
* @returns {string} Resource name string.
*/
billingAccountCmekSettingsPath(billingAccount: string) {
return this.pathTemplates.billingAccountCmekSettingsPathTemplate.render({
billing_account: billingAccount,
});
}
/**
* Parse the billing_account from BillingAccountCmekSettings resource.
*
* @param {string} billingAccountCmekSettingsName
* A fully-qualified path representing billing_account_cmekSettings resource.
* @returns {string} A string representing the billing_account.
*/
matchBillingAccountFromBillingAccountCmekSettingsName(
billingAccountCmekSettingsName: string
) {
return this.pathTemplates.billingAccountCmekSettingsPathTemplate.match(
billingAccountCmekSettingsName
).billing_account;
}
/**
* Return a fully-qualified billingAccountExclusion resource name string.
*
* @param {string} billing_account
* @param {string} exclusion
* @returns {string} Resource name string.
*/
billingAccountExclusionPath(billingAccount: string, exclusion: string) {
return this.pathTemplates.billingAccountExclusionPathTemplate.render({
billing_account: billingAccount,
exclusion: exclusion,
});
}
/**
* Parse the billing_account from BillingAccountExclusion resource.
*
* @param {string} billingAccountExclusionName
* A fully-qualified path representing billing_account_exclusion resource.
* @returns {string} A string representing the billing_account.
*/
matchBillingAccountFromBillingAccountExclusionName(
billingAccountExclusionName: string
) {
return this.pathTemplates.billingAccountExclusionPathTemplate.match(
billingAccountExclusionName
).billing_account;
}
/**
* Parse the exclusion from BillingAccountExclusion resource.
*
* @param {string} billingAccountExclusionName
* A fully-qualified path representing billing_account_exclusion resource.
* @returns {string} A string representing the exclusion.
*/
matchExclusionFromBillingAccountExclusionName(
billingAccountExclusionName: string
) {
return this.pathTemplates.billingAccountExclusionPathTemplate.match(
billingAccountExclusionName
).exclusion;
}
/**
* Return a fully-qualified billingAccountLocationBucket resource name string.
*
* @param {string} billing_account
* @param {string} location
* @param {string} bucket
* @returns {string} Resource name string.
*/
billingAccountLocationBucketPath(
billingAccount: string,
location: string,
bucket: string
) {
return this.pathTemplates.billingAccountLocationBucketPathTemplate.render({
billing_account: billingAccount,
location: location,
bucket: bucket,
});
}
/**
* Parse the billing_account from BillingAccountLocationBucket resource.
*
* @param {string} billingAccountLocationBucketName
* A fully-qualified path representing billing_account_location_bucket resource.
* @returns {string} A string representing the billing_account.
*/
matchBillingAccountFromBillingAccountLocationBucketName(
billingAccountLocationBucketName: string
) {
return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(
billingAccountLocationBucketName
).billing_account;
}
/**
* Parse the location from BillingAccountLocationBucket resource.
*
* @param {string} billingAccountLocationBucketName
* A fully-qualified path representing billing_account_location_bucket resource.
* @returns {string} A string representing the location.
*/
matchLocationFromBillingAccountLocationBucketName(
billingAccountLocationBucketName: string
) {
return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(
billingAccountLocationBucketName
).location;
}
/**
* Parse the bucket from BillingAccountLocationBucket resource.
*
* @param {string} billingAccountLocationBucketName
* A fully-qualified path representing billing_account_location_bucket resource.
* @returns {string} A string representing the bucket.
*/
matchBucketFromBillingAccountLocationBucketName(
billingAccountLocationBucketName: string
) {
return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(
billingAccountLocationBucketName
).bucket;
}
/**
* Return a fully-qualified billingAccountLocationBucketView resource name string.
*
* @param {string} billing_account
* @param {string} location
* @param {string} bucket
* @param {string} view
* @returns {string} Resource name string.
*/
billingAccountLocationBucketViewPath(
billingAccount: string,
location: string,
bucket: string,
view: string
) {
return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.render(
{
billing_account: billingAccount,
location: location,
bucket: bucket,
view: view,
}
);
}
/**
* Parse the billing_account from BillingAccountLocationBucketView resource.
*
* @param {string} billingAccountLocationBucketViewName
* A fully-qualified path representing billing_account_location_bucket_view resource.
* @returns {string} A string representing the billing_account.
*/
matchBillingAccountFromBillingAccountLocationBucketViewName(
billingAccountLocationBucketViewName: string
) {
return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(
billingAccountLocationBucketViewName
).billing_account;
}
/**
* Parse the location from BillingAccountLocationBucketView resource.
*
* @param {string} billingAccountLocationBucketViewName
* A fully-qualified path representing billing_account_location_bucket_view resource.
* @returns {string} A string representing the location.
*/
matchLocationFromBillingAccountLocationBucketViewName(
billingAccountLocationBucketViewName: string
) {
return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(
billingAccountLocationBucketViewName
).location;
}
/**
* Parse the bucket from BillingAccountLocationBucketView resource.
*
* @param {string} billingAccountLocationBucketViewName
* A fully-qualified path representing billing_account_location_bucket_view resource.
* @returns {string} A string representing the bucket.
*/
matchBucketFromBillingAccountLocationBucketViewName(
billingAccountLocationBucketViewName: string
) {
return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(
billingAccountLocationBucketViewName
).bucket;
}
/**
* Parse the view from BillingAccountLocationBucketView resource.
*
* @param {string} billingAccountLocationBucketViewName
* A fully-qualified path representing billing_account_location_bucket_view resource.
* @returns {string} A string representing the view.
*/
matchViewFromBillingAccountLocationBucketViewName(
billingAccountLocationBucketViewName: string
) {
return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(
billingAccountLocationBucketViewName
).view;
}
/**
* Return a fully-qualified billingAccountLog resource name string.
*
* @param {string} billing_account
* @param {string} log
* @returns {string} Resource name string.
*/
billingAccountLogPath(billingAccount: string, log: string) {
return this.pathTemplates.billingAccountLogPathTemplate.render({
billing_account: billingAccount,
log: log,
});
}
/**
* Parse the billing_account from BillingAccountLog resource.
*
* @param {string} billingAccountLogName
* A fully-qualified path representing billing_account_log resource.
* @returns {string} A string representing the billing_account.
*/
matchBillingAccountFromBillingAccountLogName(billingAccountLogName: string) {
return this.pathTemplates.billingAccountLogPathTemplate.match(
billingAccountLogName
).billing_account;
}
/**
* Parse the log from BillingAccountLog resource.
*
* @param {string} billingAccountLogName
* A fully-qualified path representing billing_account_log resource.
* @returns {string} A string representing the log.
*/
matchLogFromBillingAccountLogName(billingAccountLogName: string) {
return this.pathTemplates.billingAccountLogPathTemplate.match(
billingAccountLogName
).log;
}
/**
* Return a fully-qualified billingAccountSink resource name string.
*
* @param {string} billing_account
* @param {string} sink
* @returns {string} Resource name string.
*/
billingAccountSinkPath(billingAccount: string, sink: string) {
return this.pathTemplates.billingAccountSinkPathTemplate.render({
billing_account: billingAccount,
sink: sink,
});
}
/**
* Parse the billing_account from BillingAccountSink resource.
*
* @param {string} billingAccountSinkName
* A fully-qualified path representing billing_account_sink resource.
* @returns {string} A string representing the billing_account.
*/
matchBillingAccountFromBillingAccountSinkName(
billingAccountSinkName: string
) {
return this.pathTemplates.billingAccountSinkPathTemplate.match(
billingAccountSinkName
).billing_account;
}
/**
* Parse the sink from BillingAccountSink resource.
*
* @param {string} billingAccountSinkName
* A fully-qualified path representing billing_account_sink resource.
* @returns {string} A string representing the sink.
*/
matchSinkFromBillingAccountSinkName(billingAccountSinkName: string) {
return this.pathTemplates.billingAccountSinkPathTemplate.match(
billingAccountSinkName
).sink;
}
/**
* Return a fully-qualified folderCmekSettings resource name string.
*
* @param {string} folder
* @returns {string} Resource name string.
*/
folderCmekSettingsPath(folder: string) {
return this.pathTemplates.folderCmekSettingsPathTemplate.render({
folder: folder,
});
}
/**
* Parse the folder from FolderCmekSettings resource.
*
* @param {string} folderCmekSettingsName
* A fully-qualified path representing folder_cmekSettings resource.
* @returns {string} A string representing the folder.
*/
matchFolderFromFolderCmekSettingsName(folderCmekSettingsName: string) {
return this.pathTemplates.folderCmekSettingsPathTemplate.match(
folderCmekSettingsName
).folder;
}
/**
* Return a fully-qualified folderExclusion resource name string.
*
* @param {string} folder
* @param {string} exclusion
* @returns {string} Resource name string.
*/
folderExclusionPath(folder: string, exclusion: string) {
return this.pathTemplates.folderExclusionPathTemplate.render({
folder: folder,
exclusion: exclusion,
});
}
/**
* Parse the folder from FolderExclusion resource.
*
* @param {string} folderExclusionName
* A fully-qualified path representing folder_exclusion resource.
* @returns {string} A string representing the folder.
*/
matchFolderFromFolderExclusionName(folderExclusionName: string) {
return this.pathTemplates.folderExclusionPathTemplate.match(
folderExclusionName
).folder;
}
/**
* Parse the exclusion from FolderExclusion resource.
*
* @param {string} folderExclusionName
* A fully-qualified path representing folder_exclusion resource.
* @returns {string} A string representing the exclusion.
*/
matchExclusionFromFolderExclusionName(folderExclusionName: string) {
return this.pathTemplates.folderExclusionPathTemplate.match(
folderExclusionName
).exclusion;
}
/**
* Return a fully-qualified folderLocationBucket resource name string.
*
* @param {string} folder
* @param {string} location
* @param {string} bucket
* @returns {string} Resource name string.
*/
folderLocationBucketPath(folder: string, location: string, bucket: string) {
return this.pathTemplates.folderLocationBucketPathTemplate.render({
folder: folder,
location: location,
bucket: bucket,
});
}
/**
* Parse the folder from FolderLocationBucket resource.
*
* @param {string} folderLocationBucketName
* A fully-qualified path representing folder_location_bucket resource.
* @returns {string} A string representing the folder.
*/
matchFolderFromFolderLocationBucketName(folderLocationBucketName: string) {
return this.pathTemplates.folderLocationBucketPathTemplate.match(
folderLocationBucketName
).folder;
}
/**
* Parse the location from FolderLocationBucket resource.
*
* @param {string} folderLocationBucketName
* A fully-qualified path representing folder_location_bucket resource.
* @returns {string} A string representing the location.
*/
matchLocationFromFolderLocationBucketName(folderLocationBucketName: string) {
return this.pathTemplates.folderLocationBucketPathTemplate.match(
folderLocationBucketName
).location;
}
/**
* Parse the bucket from FolderLocationBucket resource.
*
* @param {string} folderLocationBucketName
* A fully-qualified path representing folder_location_bucket resource.
* @returns {string} A string representing the bucket.
*/
matchBucketFromFolderLocationBucketName(folderLocationBucketName: string) {
return this.pathTemplates.folderLocationBucketPathTemplate.match(
folderLocationBucketName
).bucket;
}
/**
* Return a fully-qualified folderLocationBucketView resource name string.
*
* @param {string} folder
* @param {string} location
* @param {string} bucket
* @param {string} view
* @returns {string} Resource name string.
*/
folderLocationBucketViewPath(
folder: string,
location: string,
bucket: string,
view: string
) {
return this.pathTemplates.folderLocationBucketViewPathTemplate.render({
folder: folder,
location: location,
bucket: bucket,
view: view,
});
}
/**
* Parse the folder from FolderLocationBucketView resource.
*
* @param {string} folderLocationBucketViewName
* A fully-qualified path representing folder_location_bucket_view resource.
* @returns {string} A string representing the folder.
*/
matchFolderFromFolderLocationBucketViewName(
folderLocationBucketViewName: string
) {
return this.pathTemplates.folderLocationBucketViewPathTemplate.match(
folderLocationBucketViewName
).folder;
}
/**
* Parse the location from FolderLocationBucketView resource.
*
* @param {string} folderLocationBucketViewName
* A fully-qualified path representing folder_location_bucket_view resource.
* @returns {string} A string representing the location.
*/
matchLocationFromFolderLocationBucketViewName(
folderLocationBucketViewName: string
) {
return this.pathTemplates.folderLocationBucketViewPathTemplate.match(
folderLocationBucketViewName
).location;
}
/**
* Parse the bucket from FolderLocationBucketView resource.
*
* @param {string} folderLocationBucketViewName
* A fully-qualified path representing folder_location_bucket_view resource.
* @returns {string} A string representing the bucket.
*/
matchBucketFromFolderLocationBucketViewName(
folderLocationBucketViewName: string
) {
return this.pathTemplates.folderLocationBucketViewPathTemplate.match(
folderLocationBucketViewName
).bucket;
}
/**
* Parse the view from FolderLocationBucketView resource.
*
* @param {string} folderLocationBucketViewName
* A fully-qualified path representing folder_location_bucket_view resource.
* @returns {string} A string representing the view.
*/
matchViewFromFolderLocationBucketViewName(
folderLocationBucketViewName: string
) {
return this.pathTemplates.folderLocationBucketViewPathTemplate.match(
folderLocationBucketViewName
).view;
}
/**
* Return a fully-qualified folderLog resource name string.
*
* @param {string} folder
* @param {string} log
* @returns {string} Resource name string.
*/
folderLogPath(folder: string, log: string) {
return this.pathTemplates.folderLogPathTemplate.render({
folder: folder,
log: log,
});
}
/**
* Parse the folder from FolderLog resource.
*
* @param {string} folderLogName
* A fully-qualified path representing folder_log resource.
* @returns {string} A string representing the folder.
*/
matchFolderFromFolderLogName(folderLogName: string) {
return this.pathTemplates.folderLogPathTemplate.match(folderLogName).folder;
}
/**
* Parse the log from FolderLog resource.
*
* @param {string} folderLogName
* A fully-qualified path representing folder_log resource.
* @returns {string} A string representing the log.
*/
matchLogFromFolderLogName(folderLogName: string) {
return this.pathTemplates.folderLogPathTemplate.match(folderLogName).log;
}
/**
* Return a fully-qualified folderSink resource name string.
*
* @param {string} folder
* @param {string} sink
* @returns {string} Resource name string.
*/
folderSinkPath(folder: string, sink: string) {
return this.pathTemplates.folderSinkPathTemplate.render({
folder: folder,
sink: sink,
});
}
/**
* Parse the folder from FolderSink resource.
*
* @param {string} folderSinkName
* A fully-qualified path representing folder_sink resource.
* @returns {string} A string representing the folder.
*/
matchFolderFromFolderSinkName(folderSinkName: string) {
return this.pathTemplates.folderSinkPathTemplate.match(folderSinkName)
.folder;
}
/**
* Parse the sink from FolderSink resource.
*
* @param {string} folderSinkName
* A fully-qualified path representing folder_sink resource.
* @returns {string} A string representing the sink.
*/
matchSinkFromFolderSinkName(folderSinkName: string) {
return this.pathTemplates.folderSinkPathTemplate.match(folderSinkName).sink;
}
/**
* Return a fully-qualified logMetric resource name string.
*
* @param {string} project
* @param {string} metric
* @returns {string} Resource name string.
*/
logMetricPath(project: string, metric: string) {
return this.pathTemplates.logMetricPathTemplate.render({
project: project,
metric: metric,
});
}
/**
* Parse the project from LogMetric resource.
*
* @param {string} logMetricName
* A fully-qualified path representing LogMetric resource.
* @returns {string} A string representing the project.
*/
matchProjectFromLogMetricName(logMetricName: string) {
return this.pathTemplates.logMetricPathTemplate.match(logMetricName)
.project;
}
/**
* Parse the metric from LogMetric resource.
*
* @param {string} logMetricName
* A fully-qualified path representing LogMetric resource.
* @returns {string} A string representing the metric.
*/
matchMetricFromLogMetricName(logMetricName: string) {
return this.pathTemplates.logMetricPathTemplate.match(logMetricName).metric;
}
/**
* Return a fully-qualified organizationCmekSettings resource name string.
*
* @param {string} organization
* @returns {string} Resource name string.
*/
organizationCmekSettingsPath(organization: string) {
return this.pathTemplates.organizationCmekSettingsPathTemplate.render({
organization: organization,
});
}
/**
* Parse the organization from OrganizationCmekSettings resource.
*
* @param {string} organizationCmekSettingsName
* A fully-qualified path representing organization_cmekSettings resource.
* @returns {string} A string representing the organization.
*/
matchOrganizationFromOrganizationCmekSettingsName(
organizationCmekSettingsName: string
) {
return this.pathTemplates.organizationCmekSettingsPathTemplate.match(
organizationCmekSettingsName
).organization;
}
/**
* Return a fully-qualified organizationExclusion resource name string.
*
* @param {string} organization
* @param {string} exclusion
* @returns {string} Resource name string.
*/
organizationExclusionPath(organization: string, exclusion: string) {
return this.pathTemplates.organizationExclusionPathTemplate.render({
organization: organization,
exclusion: exclusion,
});
}
/**
* Parse the organization from OrganizationExclusion resource.
*
* @param {string} organizationExclusionName
* A fully-qualified path representing organization_exclusion resource.
* @returns {string} A string representing the organization.
*/
matchOrganizationFromOrganizationExclusionName(
organizationExclusionName: string
) {
return this.pathTemplates.organizationExclusionPathTemplate.match(
organizationExclusionName
).organization;
}
/**
* Parse the exclusion from OrganizationExclusion resource.
*
* @param {string} organizationExclusionName
* A fully-qualified path representing organization_exclusion resource.
* @returns {string} A string representing the exclusion.
*/
matchExclusionFromOrganizationExclusionName(
organizationExclusionName: string
) {
return this.pathTemplates.organizationExclusionPathTemplate.match(
organizationExclusionName
).exclusion;
}
/**
* Return a fully-qualified organizationLocationBucket resource name string.
*
* @param {string} organization
* @param {string} location
* @param {string} bucket
* @returns {string} Resource name string.
*/
organizationLocationBucketPath(
organization: string,
location: string,
bucket: string
) {
return this.pathTemplates.organizationLocationBucketPathTemplate.render({
organization: organization,
location: location,
bucket: bucket,
});
}
/**
* Parse the organization from OrganizationLocationBucket resource.
*
* @param {string} organizationLocationBucketName
* A fully-qualified path representing organization_location_bucket resource.
* @returns {string} A string representing the organization.
*/
matchOrganizationFromOrganizationLocationBucketName(
organizationLocationBucketName: string
) {
return this.pathTemplates.organizationLocationBucketPathTemplate.match(
organizationLocationBucketName
).organization;
}
/**
* Parse the location from OrganizationLocationBucket resource.
*
* @param {string} organizationLocationBucketName
* A fully-qualified path representing organization_location_bucket resource.
* @returns {string} A string representing the location.
*/
matchLocationFromOrganizationLocationBucketName(
organizationLocationBucketName: string
) {
return this.pathTemplates.organizationLocationBucketPathTemplate.match(
organizationLocationBucketName
).location;
}
/**
* Parse the bucket from OrganizationLocationBucket resource.
*
* @param {string} organizationLocationBucketName
* A fully-qualified path representing organization_location_bucket resource.
* @returns {string} A string representing the bucket.
*/
matchBucketFromOrganizationLocationBucketName(
organizationLocationBucketName: string
) {
return this.pathTemplates.organizationLocationBucketPathTemplate.match(
organizationLocationBucketName
).bucket;
}
/**
* Return a fully-qualified organizationLocationBucketView resource name string.
*
* @param {string} organization
* @param {string} location
* @param {string} bucket
* @param {string} view
* @returns {string} Resource name string.
*/
organizationLocationBucketViewPath(
organization: string,
location: string,
bucket: string,
view: string
) {
return this.pathTemplates.organizationLocationBucketViewPathTemplate.render(
{
organization: organization,
location: location,
bucket: bucket,
view: view,
}
);
}
/**
* Parse the organization from OrganizationLocationBucketView resource.
*
* @param {string} organizationLocationBucketViewName
* A fully-qualified path representing organization_location_bucket_view resource.
* @returns {string} A string representing the organization.
*/
matchOrganizationFromOrganizationLocationBucketViewName(
organizationLocationBucketViewName: string
) {
return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(
organizationLocationBucketViewName
).organization;
}
/**
* Parse the location from OrganizationLocationBucketView resource.
*
* @param {string} organizationLocationBucketViewName
* A fully-qualified path representing organization_location_bucket_view resource.
* @returns {string} A string representing the location.
*/
matchLocationFromOrganizationLocationBucketViewName(
organizationLocationBucketViewName: string
) {
return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(
organizationLocationBucketViewName
).location;
}
/**
* Parse the bucket from OrganizationLocationBucketView resource.
*
* @param {string} organizationLocationBucketViewName
* A fully-qualified path representing organization_location_bucket_view resource.
* @returns {string} A string representing the bucket.
*/
matchBucketFromOrganizationLocationBucketViewName(
organizationLocationBucketViewName: string
) {
return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(
organizationLocationBucketViewName
).bucket;
}
/**
* Parse the view from OrganizationLocationBucketView resource.
*
* @param {string} organizationLocationBucketViewName
* A fully-qualified path representing organization_location_bucket_view resource.
* @returns {string} A string representing the view.
*/
matchViewFromOrganizationLocationBucketViewName(
organizationLocationBucketViewName: string
) {
return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(
organizationLocationBucketViewName
).view;
}
/**
* Return a fully-qualified organizationLog resource name string.
*
* @param {string} organization
* @param {string} log
* @returns {string} Resource name string.
*/
organizationLogPath(organization: string, log: string) {
return this.pathTemplates.organizationLogPathTemplate.render({
organization: organization,
log: log,
});
}
/**
* Parse the organization from OrganizationLog resource.
*
* @param {string} organizationLogName
* A fully-qualified path representing organization_log resource.
* @returns {string} A string representing the organization.
*/
matchOrganizationFromOrganizationLogName(organizationLogName: string) {
return this.pathTemplates.organizationLogPathTemplate.match(
organizationLogName
).organization;
}
/**
* Parse the log from OrganizationLog resource.
*
* @param {string} organizationLogName
* A fully-qualified path representing organization_log resource.
* @returns {string} A string representing the log.
*/
matchLogFromOrganizationLogName(organizationLogName: string) {
return this.pathTemplates.organizationLogPathTemplate.match(
organizationLogName
).log;
}
/**
* Return a fully-qualified organizationSink resource name string.
*
* @param {string} organization
* @param {string} sink
* @returns {string} Resource name string.
*/
organizationSinkPath(organization: string, sink: string) {
return this.pathTemplates.organizationSinkPathTemplate.render({
organization: organization,
sink: sink,
});
}
/**
* Parse the organization from OrganizationSink resource.
*
* @param {string} organizationSinkName
* A fully-qualified path representing organization_sink resource.
* @returns {string} A string representing the organization.
*/
matchOrganizationFromOrganizationSinkName(organizationSinkName: string) {
return this.pathTemplates.organizationSinkPathTemplate.match(
organizationSinkName
).organization;
}
/**
* Parse the sink from OrganizationSink resource.
*
* @param {string} organizationSinkName
* A fully-qualified path representing organization_sink resource.
* @returns {string} A string representing the sink.
*/
matchSinkFromOrganizationSinkName(organizationSinkName: string) {
return this.pathTemplates.organizationSinkPathTemplate.match(
organizationSinkName
).sink;
}
/**
* Return a fully-qualified project resource name string.
*
* @param {string} project
* @returns {string} Resource name string.
*/
projectPath(project: string) {
return this.pathTemplates.projectPathTemplate.render({
project: project,
});
}
/**
* Parse the project from Project resource.
*
* @param {string} projectName
* A fully-qualified path representing Project resource.
* @returns {string} A string representing the project.
*/
matchProjectFromProjectName(projectName: string) {
return this.pathTemplates.projectPathTemplate.match(projectName).project;
}
/**
* Return a fully-qualified projectCmekSettings resource name string.
*
* @param {string} project
* @returns {string} Resource name string.
*/
projectCmekSettingsPath(project: string) {
return this.pathTemplates.projectCmekSettingsPathTemplate.render({
project: project,
});
}
/**
* Parse the project from ProjectCmekSettings resource.
*
* @param {string} projectCmekSettingsName
* A fully-qualified path representing project_cmekSettings resource.
* @returns {string} A string representing the project.
*/
matchProjectFromProjectCmekSettingsName(projectCmekSettingsName: string) {
return this.pathTemplates.projectCmekSettingsPathTemplate.match(
projectCmekSettingsName
).project;
}
/**
* Return a fully-qualified projectExclusion resource name string.
*
* @param {string} project
* @param {string} exclusion
* @returns {string} Resource name string.
*/
projectExclusionPath(project: string, exclusion: string) {
return this.pathTemplates.projectExclusionPathTemplate.render({
project: project,
exclusion: exclusion,
});
}
/**
* Parse the project from ProjectExclusion resource.
*
* @param {string} projectExclusionName
* A fully-qualified path representing project_exclusion resource.
* @returns {string} A string representing the project.
*/
matchProjectFromProjectExclusionName(projectExclusionName: string) {
return this.pathTemplates.projectExclusionPathTemplate.match(
projectExclusionName
).project;
}
/**
* Parse the exclusion from ProjectExclusion resource.
*
* @param {string} projectExclusionName
* A fully-qualified path representing project_exclusion resource.
* @returns {string} A string representing the exclusion.
*/
matchExclusionFromProjectExclusionName(projectExclusionName: string) {
return this.pathTemplates.projectExclusionPathTemplate.match(
projectExclusionName
).exclusion;
}
/**
* Return a fully-qualified projectLocationBucket resource name string.
*
* @param {string} project
* @param {string} location
* @param {string} bucket
* @returns {string} Resource name string.
*/
projectLocationBucketPath(project: string, location: string, bucket: string) {
return this.pathTemplates.projectLocationBucketPathTemplate.render({
project: project,
location: location,
bucket: bucket,
});
}
/**
* Parse the project from ProjectLocationBucket resource.
*
* @param {string} projectLocationBucketName
* A fully-qualified path representing project_location_bucket resource.
* @returns {string} A string representing the project.
*/
matchProjectFromProjectLocationBucketName(projectLocationBucketName: string) {
return this.pathTemplates.projectLocationBucketPathTemplate.match(
projectLocationBucketName
).project;
}
/**
* Parse the location from ProjectLocationBucket resource.
*
* @param {string} projectLocationBucketName
* A fully-qualified path representing project_location_bucket resource.
* @returns {string} A string representing the location.
*/
matchLocationFromProjectLocationBucketName(
projectLocationBucketName: string
) {
return this.pathTemplates.projectLocationBucketPathTemplate.match(
projectLocationBucketName
).location;
}
/**
* Parse the bucket from ProjectLocationBucket resource.
*
* @param {string} projectLocationBucketName
* A fully-qualified path representing project_location_bucket resource.
* @returns {string} A string representing the bucket.
*/
matchBucketFromProjectLocationBucketName(projectLocationBucketName: string) {
return this.pathTemplates.projectLocationBucketPathTemplate.match(
projectLocationBucketName
).bucket;
}
/**
* Return a fully-qualified projectLocationBucketView resource name string.
*
* @param {string} project
* @param {string} location
* @param {string} bucket
* @param {string} view
* @returns {string} Resource name string.
*/
projectLocationBucketViewPath(
project: string,
location: string,
bucket: string,
view: string
) {
return this.pathTemplates.projectLocationBucketViewPathTemplate.render({
project: project,
location: location,
bucket: bucket,
view: view,
});
}
/**
* Parse the project from ProjectLocationBucketView resource.
*
* @param {string} projectLocationBucketViewName
* A fully-qualified path representing project_location_bucket_view resource.
* @returns {string} A string representing the project.
*/
matchProjectFromProjectLocationBucketViewName(
projectLocationBucketViewName: string
) {
return this.pathTemplates.projectLocationBucketViewPathTemplate.match(
projectLocationBucketViewName
).project;
}
/**
* Parse the location from ProjectLocationBucketView resource.
*
* @param {string} projectLocationBucketViewName
* A fully-qualified path representing project_location_bucket_view resource.
* @returns {string} A string representing the location.
*/
matchLocationFromProjectLocationBucketViewName(
projectLocationBucketViewName: string
) {
return this.pathTemplates.projectLocationBucketViewPathTemplate.match(
projectLocationBucketViewName
).location;
}
/**
* Parse the bucket from ProjectLocationBucketView resource.
*
* @param {string} projectLocationBucketViewName
* A fully-qualified path representing project_location_bucket_view resource.
* @returns {string} A string representing the bucket.
*/
matchBucketFromProjectLocationBucketViewName(
projectLocationBucketViewName: string
) {
return this.pathTemplates.projectLocationBucketViewPathTemplate.match(
projectLocationBucketViewName
).bucket;
}
/**
* Parse the view from ProjectLocationBucketView resource.
*
* @param {string} projectLocationBucketViewName
* A fully-qualified path representing project_location_bucket_view resource.
* @returns {string} A string representing the view.
*/
matchViewFromProjectLocationBucketViewName(
projectLocationBucketViewName: string
) {
return this.pathTemplates.projectLocationBucketViewPathTemplate.match(
projectLocationBucketViewName
).view;
}
/**
* Return a fully-qualified projectLog resource name string.
*
* @param {string} project
* @param {string} log
* @returns {string} Resource name string.
*/
projectLogPath(project: string, log: string) {
return this.pathTemplates.projectLogPathTemplate.render({
project: project,
log: log,
});
}
/**
* Parse the project from ProjectLog resource.
*
* @param {string} projectLogName
* A fully-qualified path representing project_log resource.
* @returns {string} A string representing the project.
*/
matchProjectFromProjectLogName(projectLogName: string) {
return this.pathTemplates.projectLogPathTemplate.match(projectLogName)
.project;
}
/**
* Parse the log from ProjectLog resource.
*
* @param {string} projectLogName
* A fully-qualified path representing project_log resource.
* @returns {string} A string representing the log.
*/
matchLogFromProjectLogName(projectLogName: string) {
return this.pathTemplates.projectLogPathTemplate.match(projectLogName).log;
}
/**
* Return a fully-qualified projectSink resource name string.
*
* @param {string} project
* @param {string} sink
* @returns {string} Resource name string.
*/
projectSinkPath(project: string, sink: string) {
return this.pathTemplates.projectSinkPathTemplate.render({
project: project,
sink: sink,
});
}
/**
* Parse the project from ProjectSink resource.
*
* @param {string} projectSinkName
* A fully-qualified path representing project_sink resource.
* @returns {string} A string representing the project.
*/
matchProjectFromProjectSinkName(projectSinkName: string) {
return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName)
.project;
}
/**
* Parse the sink from ProjectSink resource.
*
* @param {string} projectSinkName
* A fully-qualified path representing project_sink resource.
* @returns {string} A string representing the sink.
*/
matchSinkFromProjectSinkName(projectSinkName: string) {
return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName)
.sink;
}
/**
* Terminate the gRPC channel and close the client.
*
* The client will no longer be usable and all future behavior is undefined.
* @returns {Promise} A promise that resolves when the client is closed.
*/
close(): Promise<void> {
this.initialize();
if (!this._terminated) {
return this.loggingServiceV2Stub!.then(stub => {
this._terminated = true;
stub.close();
});
}
return Promise.resolve();
}
} | the_stack |
import { Trans } from "@lingui/macro";
import { i18nMark } from "@lingui/react";
import qs from "query-string";
import mixin from "reactjs-mixin";
import { Link, routerShape } from "react-router";
import * as React from "react";
import { Dropdown, Tooltip, Modal, Confirm } from "reactjs-components";
import {
Badge,
Box,
Icon,
InfoBoxInline,
Tooltip as UIKitTooltip,
} from "@dcos/ui-kit";
import { SystemIcons } from "@dcos/ui-kit/dist/packages/icons/dist/system-icons-enum";
import { ProductIcons } from "@dcos/ui-kit/dist/packages/icons/dist/product-icons-enum";
import {
green,
red,
iconSizeL,
iconSizeXs,
} from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens";
import classNames from "classnames";
import Breadcrumb from "#SRC/js/components/Breadcrumb";
import BreadcrumbTextContent from "#SRC/js/components/BreadcrumbTextContent";
import CosmosPackagesStore from "#SRC/js/stores/CosmosPackagesStore";
import Image from "#SRC/js/components/Image";
import ImageViewer from "#SRC/js/components/ImageViewer";
import Loader from "#SRC/js/components/Loader";
import DCOSStore from "#SRC/js/stores/DCOSStore";
import MetadataStore from "#SRC/js/stores/MetadataStore";
import Page from "#SRC/js/components/Page";
import RequestErrorMsg from "#SRC/js/components/RequestErrorMsg";
import StoreMixin from "#SRC/js/mixins/StoreMixin";
import StringUtil from "#SRC/js/utils/StringUtil";
import defaultServiceImage from "#PLUGINS/services/src/img/icon-service-default-large@2x.png";
import { DCOS_CHANGE } from "#SRC/js/constants/EventTypes";
import * as LastUpdated from "#SRC/js/components/LastUpdated";
import FrameworkUtil from "#PLUGINS/services/src/js/utils/FrameworkUtil";
import * as semver from "semver/preload";
import dcosVersion$ from "#SRC/js/stores/dcos-version";
const runningServicesNames = (labels = []) =>
labels
.filter((label) => label.key === "DCOS_SERVICE_NAME")
.map((label) => label.value);
const PackageDetailBreadcrumbs = ({ cosmosPackage, isLoading }) => {
const name = cosmosPackage.getName();
const version = cosmosPackage.getVersion();
const crumbs = [
<Breadcrumb key={0} title="Catalog">
<BreadcrumbTextContent>
<Link to="/catalog/packages">
<Trans render="span">Catalog</Trans>
</Link>
</BreadcrumbTextContent>
</Breadcrumb>,
<Breadcrumb key={1} title={!isLoading && name}>
{!isLoading && (
<BreadcrumbTextContent>
<Link to={`/catalog/packages/${name}`} query={{ version }} key={0}>
{name}
</Link>
</BreadcrumbTextContent>
)}
</Breadcrumb>,
];
return (
<Page.Header.Breadcrumbs
iconID={ProductIcons.Packages}
breadcrumbs={crumbs}
/>
);
};
class PackageDetailTab extends mixin(StoreMixin) {
state = {
hasError: 0,
isConfirmOpen: false,
isLoadingSelectedVersion: false,
isLoadingVersions: false,
runningPackageNames: { state: "loading" },
};
// prettier-ignore
store_listeners = [
{name: "cosmosPackages", events: ["packageDescriptionError", "packageDescriptionSuccess", "listVersionsSuccess", "listVersionsError"], suppressUpdate: true}
];
retrievePackageInfo(packageName, version) {
const cosmosPackage = CosmosPackagesStore.getPackageDetails();
const packageVersions = CosmosPackagesStore.getPackageVersions(packageName);
// Fetch package versions if necessary
if (packageVersions == null) {
this.setState({ isLoadingVersions: true });
CosmosPackagesStore.fetchPackageVersions(packageName);
}
// Fetch new description if name or version changed
if (
cosmosPackage == null ||
packageName !== cosmosPackage.getName() ||
version !== cosmosPackage.getVersion()
) {
this.setState({ isLoadingSelectedVersion: true });
CosmosPackagesStore.fetchPackageDescription(packageName, version);
}
}
onStoreChange = () => {
this.setState({
runningPackageNames: {
state: "success",
data: runningServicesNames(DCOSStore.serviceTree.getLabels()),
},
});
};
componentDidMount(...args) {
super.componentDidMount(...args);
DCOSStore.addChangeListener(DCOS_CHANGE, this.onStoreChange);
dcosVersion$.subscribe(({ version }) => {
this.setState({ version });
});
this.retrievePackageInfo(
this.props.params.packageName,
this.props.location.query.version
);
}
componentWillUnmount() {
DCOSStore.removeChangeListener(DCOS_CHANGE, this.onStoreChange);
}
UNSAFE_componentWillReceiveProps(nextProps) {
this.retrievePackageInfo(
nextProps.params.packageName,
nextProps.location.query.version
);
}
onCosmosPackagesStorePackageDescriptionError() {
this.setState({ hasError: true });
}
onCosmosPackagesStorePackageDescriptionSuccess() {
this.setState({
hasError: false,
isLoadingSelectedVersion: false,
});
}
onCosmosPackagesStoreListVersionsSuccess() {
this.setState({ isLoadingVersions: false });
}
handleReviewAndRunClick = (isCertified) => {
if (isCertified) {
return this.handleConfirmClick();
}
this.setState({ isConfirmOpen: true });
};
handleConfirmClick = () => {
const { router } = this.context;
const { params, location } = this.props;
router.push(
`/catalog/packages/${encodeURIComponent(
params.packageName
)}/deploy?${qs.stringify({ version: location.query.version })}`
);
};
handleConfirmClose = () => {
this.setState({ isConfirmOpen: false });
};
handlePackageVersionChange = (selection) => {
const query = {
...this.props.location.query,
version: selection.id,
};
window.location.replace(
`#${this.props.location.pathname}?${qs.stringify(query)}`
);
};
getErrorScreen() {
return <RequestErrorMsg />;
}
getItems(definition, renderItem) {
const items = [];
definition.forEach((item, index) => {
const { label, type, value } = item;
// When there is no content to render, discard it all together
if (!value || (Array.isArray(value) && !value.length)) {
return null;
}
// If not specific type assume value is renderable
let content = value;
// Render sub items
if (type === "subItems") {
content = this.getItems(value, this.getSubItem);
}
items.push(renderItem(label, content, index));
});
return items;
}
getItem(label, value, key) {
if (!label || !value) {
return null;
}
if (typeof value === "string") {
value = <p className="flush">{value}</p>;
}
return (
<div
className="pod pod-shorter flush-top flush-right flush-left"
key={key}
>
<h2 className="short-bottom">{label}</h2>
{value}
</div>
);
}
getSubItem(label, value, key) {
let content = value;
if (StringUtil.isEmail(value)) {
content = (
<a key={key} href={`mailto:${value}`}>
{value}
</a>
);
}
if (StringUtil.isUrl(value)) {
content = (
<a key={key} href={value} target="_blank">
{value}
</a>
);
}
if (!label) {
return (
<p key={key} className="short">
{content}
</p>
);
}
return (
<p key={key} className="short">
{`${label}: `}
{content}
</p>
);
}
mapLicenses(licenses) {
return licenses.map((license) => {
const item = {
label: license.name,
value: license.url,
};
return item;
});
}
getPackageBadge(cosmosPackage) {
const isCertified = cosmosPackage.isCertified();
const badgeCopy = isCertified
? i18nMark("Certified")
: i18nMark("Community");
const appearance = isCertified ? "primary" : "default";
return (
<span className="column-3">
<Trans id={badgeCopy} render={<Badge appearance={appearance} />} />
</span>
);
}
renderCliHint() {
return (
<div>
<Trans render="p">CLI Only Package</Trans>
<Trans render="p">
{"This package can only be installed using the CLI. See the "}
<a
href={MetadataStore.buildDocsURI(
"/cli/command-reference/dcos-package/dcos-package-install/"
)}
target="_blank"
>
documentation
</a>
.
</Trans>
</div>
);
}
renderInstallButton = ({ tooltipContent, disabled }, isCertified) => {
const button = (
<button
className={classNames("button button-primary", { disabled })}
onClick={() => disabled || this.handleReviewAndRunClick(isCertified)}
>
<Trans render="span">Review & Run</Trans>
</button>
);
return !tooltipContent ? (
button
) : (
<Tooltip
wrapText={true}
content={tooltipContent}
suppress={!disabled}
width={200}
>
{button}
</Tooltip>
);
};
hasUnresolvedDependency = (cosmosPackage) => {
const dep = dependency(cosmosPackage);
return dep && !(this.state.runningPackageNames.data || []).includes(dep);
};
renderReviewAndRunButton = (cosmosPackage) => {
if (cosmosPackage.isCLIOnly()) {
return this.renderCliHint();
}
const isCertified = cosmosPackage.isCertified();
if (this.state.isLoadingSelectedVersion) {
return this.renderInstallButton(
{
disabled: true,
tooltipContent: <Trans>Loading selected version</Trans>,
},
isCertified
);
}
if (this.hasUnresolvedDependency(cosmosPackage)) {
return this.renderInstallButton(
{
disabled: true,
tooltipContent: (
<Trans>
Cannot run without {dependency(cosmosPackage)} package.
</Trans>
),
},
isCertified
);
}
if (
this.state.version &&
cosmosPackage.minDcosReleaseVersion &&
semver.compare(
semver.coerce(this.state.version),
semver.coerce(cosmosPackage.minDcosReleaseVersion)
) < 0
) {
return this.renderInstallButton(
{
disabled: true,
tooltipContent: (
<Trans>
This version of {cosmosPackage.getName()} requires DC/OS version{" "}
{cosmosPackage.minDcosReleaseVersion} or higher, but you are
running DC/OS version {semver.coerce(this.state.version)}
</Trans>
),
},
isCertified
);
}
return this.renderInstallButton(
{ tooltipContent: "", disabled: false },
isCertified
);
};
getPackageVersionsDropdown() {
const cosmosPackage = CosmosPackagesStore.getPackageDetails();
const packageName = cosmosPackage.getName();
const packageVersions = CosmosPackagesStore.getPackageVersions(packageName);
if (packageVersions == null) {
return null;
}
const selectedVersion = cosmosPackage.getVersion();
const availableVersions = packageVersions.getVersions().map((version) => ({
html: version,
id: version,
}));
if (availableVersions.length === 0) {
return null;
}
return (
<Dropdown
buttonClassName="button button-primary-link dropdown-toggle flush-left flush-right"
dropdownMenuClassName="dropdown-menu"
dropdownMenuListClassName="dropdown-menu-list"
onItemSelection={this.handlePackageVersionChange}
items={availableVersions}
persistentID={selectedVersion}
transition={true}
wrapperClassName="dropdown"
/>
);
}
getPackageDescription(definition, cosmosPackage) {
return (
<div className="pod flush-horizontal flush-bottom">
{this.getItems(definition, this.getItem)}
<ImageViewer images={cosmosPackage.getScreenshots()} />
</div>
);
}
onInstalledSuccessModalClose = () => {
const query = {
...this.props.location.query,
};
delete query.appId;
window.location.replace(
`#${this.props.location.pathname}?${qs.stringify(query)}`
);
};
getInstalledSuccessModal(name) {
const { location } = this.props;
return (
<Modal
modalClass={"modal modal-small"}
open={!!location.query.appId}
onClose={this.onInstalledSuccessModalClose}
>
<div className="modal-install-package-tab-form-wrapper">
<div className="modal-body">
<div className="horizontal-center">
<span className="text-success">
<Icon
shape={SystemIcons.CircleCheck}
size={iconSizeL}
color={green}
/>
</span>
<Trans render="h2" className="short-top short-bottom">
Success!
</Trans>
<Trans
render="div"
className="install-package-modal-package-notes text-overflow-break-word"
>
{StringUtil.capitalize(name)} is being installed.
</Trans>
</div>
</div>
<div className="modal-footer">
<div className="button-collection button-collection-stacked horizontal-center">
<a
className="button button-success button-block"
href={`#/services/detail/${encodeURIComponent(
location.query.appId
)}`}
>
<Trans render="span">Open Service</Trans>
</a>
</div>
</div>
</div>
</Modal>
);
}
render() {
const { props, state } = this;
if (state.hasError || !props.params.packageName) {
return this.getErrorScreen();
}
const cosmosPackage = CosmosPackagesStore.getPackageDetails();
if (!cosmosPackage) {
return <Loader />;
}
const name = cosmosPackage.getName();
const description = cosmosPackage.getDescription();
const preInstallNotes = cosmosPackage.getPreInstallNotes();
let preInstallNotesParsed = null;
if (preInstallNotes) {
preInstallNotesParsed = StringUtil.parseMarkdown(preInstallNotes);
preInstallNotesParsed.__html =
"<strong>Preinstall Notes: </strong>" + preInstallNotesParsed.__html;
}
const updatedAt = FrameworkUtil.getLastUpdated(cosmosPackage);
const definition = [
{
label: "Description",
value: description && (
<div
dangerouslySetInnerHTML={StringUtil.parseMarkdown(description)}
/>
),
},
{
label: " ",
value: preInstallNotes && (
<InfoBoxInline
appearance="warning"
message={
<div
className="pre-install-notes"
dangerouslySetInnerHTML={preInstallNotesParsed}
/>
}
/>
),
},
{
label: "Information",
type: "subItems",
value: [
{ label: "SCM", value: cosmosPackage.getSCM() },
{ label: "Maintainer", value: cosmosPackage.getMaintainer() },
{ value: updatedAt ? LastUpdated.render(updatedAt) : null },
],
},
{
label: "Licenses",
type: "subItems",
value: this.mapLicenses(cosmosPackage.getLicenses()),
},
];
const isLoading = this.state.runningPackageNames.state === "loading";
return (
<Page>
<Page.Header
breadcrumbs={
<PackageDetailBreadcrumbs
cosmosPackage={cosmosPackage}
isLoading={state.isLoadingSelectedVersion}
/>
}
/>
{!isLoading ? (
<div>
<div className="container">
{this.hasUnresolvedDependency(cosmosPackage) &&
renderUnresolvedDependency(dependency(cosmosPackage))}
<div className="media-object-spacing-wrapper media-object-spacing-wide media-object-offset">
<div className="media-object media-object-align-top media-object-wrap">
<div className="media-object-item">
<div className="icon icon-huge icon-image-container icon-app-container icon-app-container--borderless icon-default-white">
<Image
fallbackSrc={defaultServiceImage}
src={
state.isLoadingSelectedVersion
? defaultServiceImage
: cosmosPackage.getIcons()["icon-large"]
}
/>
</div>
</div>
{!state.isLoadingSelectedVersion && (
<div className="media-object-item media-object-item-grow ">
<h1 className="short flush-top flush-bottom">
{cosmosPackage.getHasKnownIssues() ? (
<Box display="inline-block">
<UIKitTooltip
id="has-known-issues"
preferredDirections={["top-left"]}
trigger={
<span>
<Icon color={red} shape={SystemIcons.Yield} />
</span>
}
>
<Trans render="span">
This package is known to have issues when
started with its default settings.
</Trans>
</UIKitTooltip>{" "}
</Box>
) : null}
{name}
</h1>
<div className="flex flex-align-items-center">
<span className="package-version-label">
<Trans>Version</Trans>:
</span>
{this.getPackageVersionsDropdown()}
</div>
<div className="row">
{this.getPackageBadge(cosmosPackage)}
</div>
</div>
)}
<Confirm
open={state.isConfirmOpen}
onClose={this.handleConfirmClose}
leftButtonText={<Trans>Cancel</Trans>}
leftButtonClassName="button button-primary-link flush-left"
leftButtonCallback={this.handleConfirmClose}
rightButtonText={<Trans>Continue</Trans>}
rightButtonClassName="button button-primary"
rightButtonCallback={this.handleConfirmClick}
>
<Trans render="h2" className="text-align-center flush-top">
Install Community Package
</Trans>
<Trans>
<p>
This package is not tested for production environments
and technical support is not provided.
</p>
<p>Would you like to proceed?</p>
</Trans>
</Confirm>
<div className="media-object-item package-action-buttons">
{this.renderReviewAndRunButton(cosmosPackage)}
</div>
</div>
</div>
{state.isLoadingSelectedVersion ? (
<Loader />
) : (
this.getPackageDescription(definition, cosmosPackage)
)}
</div>
{this.getInstalledSuccessModal(name)}
</div>
) : (
<Loader />
)}
</Page>
);
}
}
PackageDetailTab.contextTypes = {
router: routerShape,
};
const dependency = (cosmosPackage) => (cosmosPackage.manager || {}).packageName;
const renderUnresolvedDependency = (dependency) => (
<div className="infoBoxWrapper">
<InfoBoxInline
message={
<div>
<Icon shape={SystemIcons.CircleInformation} size={iconSizeXs} />{" "}
<Trans>
This service cannot run without the {dependency} package. Please run{" "}
<Link to={`/catalog/packages/${dependency}`}>
{dependency} package
</Link>{" "}
to enable this service.
</Trans>
</div>
}
/>
</div>
);
export default PackageDetailTab; | the_stack |
import { Vue, Component, Watch } from 'vue-property-decorator';
import { Annyang } from 'annyang';
import annyang from 'annyang';
import _ from 'lodash';
import $ from 'jquery';
import ns from '@/store/namespaces';
import FormInput from '@/components/form-input/form-input';
import { FlowsenseTokenCategory, FlowsenseToken, FlowsenseCategorizedToken } from '@/store/flowsense/types';
import * as flowsenseUtil from '@/store/flowsense/util';
import { showSystemMessage, areRangesIntersected, systemMessageErrorHandler, elementOffset } from '@/common/util';
const DROPDOWN_MARGIN_PX = 10;
const TOKEN_COMPLETION_DROPDOWN_DELAY_MS = 250;
const TOKEN_COMPLETION_DROPDOWN_Y_OFFSET_PX = 10;
const QUERY_COMPLETION_DELAY_MS = 30000;
interface DropdownElement {
text: string;
annotation: string; // additional description of the entry, such as the dataset name a column belongs to
class: string;
onClick: () => void;
}
interface QueryCompletionDropdownElement {
tokens: FlowsenseToken[];
onClick: () => void;
}
interface ManualCategory {
startIndex: number;
endIndex: number; // exclusive on the last character
chosenCategory: number;
}
@Component({
components: {
FormInput,
},
})
export default class FlowsenseInput extends Vue {
@ns.flowsense.State('inputVisible') private visible!: boolean;
@ns.flowsense.State('voiceEnabled') private isVoiceEnabled!: boolean;
@ns.flowsense.Mutation('toggleVoice') private toggleFlowsenseVoice!: () => void;
@ns.flowsense.Mutation('closeInput') private closeFlowsenseInput!: () => void;
@ns.flowsense.Action('query') private dispatchQuery!: (tokens: FlowsenseToken[]) => Promise<boolean>;
@ns.flowsense.Action('autoComplete') private dispatchAutoComplete!: (tokens: FlowsenseToken[]) =>
Promise<FlowsenseToken[][]>;
@ns.flowsense.Getter('specialUtterances') private flowsenseSpecialUtterances!: FlowsenseCategorizedToken[];
private tokens: FlowsenseToken[] = [];
private text = '';
private prevText = '';
private calibratedText = '';
private voice: Annyang = annyang as Annyang;
private isVoiceInProgress = false;
private isVoiceSupported = true;
private isWaiting = false; // waiting for query response
private isInputHidden = false;
private lastEditPosition = 0;
// Dropdown elements for selecting token categories
private tokenCategoryDropdown: DropdownElement[] = [];
// Dropdown elements for auto completing special utterances
private tokenCompletionDropdown: DropdownElement[] = [];
private tokenCompletionDropdownSelectedIndex: number = 0;
private tokenCompletionDropdownPositionX = 0;
private tokenCompletionDropdownTimeout: NodeJS.Timer | null = null;
// Dropdown elements for auto completing query.
private queryCompletionMessage = '';
private queryCompletionDropdown: QueryCompletionDropdownElement[] = [];
private queryCompletionDropdownTimeout: NodeJS.Timer | null = null;
private queryCompletionDropdownSelectedIndex: number = 0;
private clickX = 0;
private clickY = 0;
private manualCategories: ManualCategory[] = [];
get microphoneClass() {
return this.isVoiceInProgress ? 'active' : '';
}
get tokenCompletionDropdownStyle() {
const inputHeight = $(this.$el).find('#input').height() as number;
return {
left: this.tokenCompletionDropdownPositionX + 'px',
top: (inputHeight + TOKEN_COMPLETION_DROPDOWN_Y_OFFSET_PX) + 'px',
};
}
get tokenCategoryDropdownStyle() {
return {
left: this.clickX + 'px',
top: this.clickY + 'px',
};
}
get isTokenCategoryDropdownVisible(): boolean {
return this.tokenCategoryDropdown.length > 0;
}
get isTokenCompletionDropdownVisible(): boolean {
return this.tokenCompletionDropdown.length > 0;
}
get isQueryCompletionDropdownVisible(): boolean {
return this.queryCompletionDropdown.length > 0 && this.queryCompletionMessage === '';
}
private mounted() {
this.voice = annyang as Annyang;
if (!this.voice) {
this.isVoiceSupported = false;
return;
}
this.voice.addCallback('soundstart', () => {
this.isVoiceInProgress = true;
});
this.voice.addCallback('result', possiblePhrases => {
const phrases: string[] = possiblePhrases as any; // tslint:disable-line no-any
const cursorPosition = this.getCursorPosition();
const newText = this.text.slice(0, cursorPosition) + phrases[0] + this.text.slice(cursorPosition);
this.onTextInput(newText);
this.isVoiceInProgress = false;
this.voice.abort();
this.voice.start();
});
}
/**
* Parses the text into tokens, separated by spaces.
*/
private parseInput(text: string) {
this.tokens = flowsenseUtil.parseTokens(text);
this.checkTokenCategories();
}
/**
* Parses each token and checks if the token is one of the special utterance category.
* Performs exact match on tokens to avoid input text length changes while the user is typing.
*/
private checkTokenCategories() {
this.tokens.forEach((token, index) => {
if (token.chosenCategory !== -1 && token.manuallySet) {
// If the token's category is manually set, do not update.
return;
}
if (flowsenseUtil.isSeparator(token.text)) { // skip separator
return;
}
if (token.isPhrase) { // Skip identified compound tokens in a phrase.
return;
}
let iteration = 2;
while (iteration--) {
if (iteration === 0 && index + 2 >= this.tokens.length) {
continue;
}
const tokenText = iteration === 1 ? token.text :
token.text + this.tokens[index + 1].text + this.tokens[index + 2].text;
for (const utterance of this.flowsenseSpecialUtterances) {
let matched = false;
for (const text of utterance.matchText as string[]) {
let tolerance = .2;
if (utterance.category === FlowsenseTokenCategory.NODE_LABEL ||
utterance.category === FlowsenseTokenCategory.DATASET) {
tolerance = 0;
}
if (flowsenseUtil.matchToken(tokenText, text, tolerance)) {
matched = true;
break;
}
}
if (matched) {
token.categories.push(utterance);
}
}
if (token.categories.length > 1) {
const manual = this.manualCategories.find(category => category.startIndex === token.index);
token.chosenCategory = manual !== undefined ? manual.chosenCategory : 1;
break;
}
}
if (token.chosenCategory === -1) {
token.chosenCategory = 0;
} else if (iteration === 0) { // bigram identified
token.text += this.tokens[index + 1].text + this.tokens[index + 2].text;
this.tokens[index + 1].isPhrase = this.tokens[index + 2].isPhrase = true;
}
});
this.tokens = this.tokens.filter(token => !token.isPhrase);
}
/**
* Parses the text input.
* TODO: Currently we put a limit on the maximum input length based on the input box width, as the UI does not handle
* long query that exceeds the width of the input box. A long query will cause the input box to horizontally scroll.
* But the "tag-row" is so far designed to overlap the input text. When scroll happens, the overlap will mess up.
*/
private onTextInput(text: string | null) {
this.resetQueryCompletionTimeout();
this.isInputHidden = false;
const finalText = text || '';
this.calibratedText = finalText;
this.$nextTick(() => {
const width = $(this.$el).find('.width-calibration').width() as number;
const maxWidth = ($(this.$el).find('#input').width() as number) -
($(this.$el).find('#buttons').outerWidth() as number);
const cursorPosition = this.getCursorPosition();
if (width > maxWidth) {
showSystemMessage(this.$store, 'exceeded maximum query length', 'warn');
this.text = ''; // Clear the text so that form-input can upate <input>'s value properly
this.$nextTick(() => { // Wait for next tick, otherwise <input> will not get value update.
this.text = this.prevText;
this.parseInput(this.text);
this.$nextTick(() => this.setCursorPosition(cursorPosition === this.text.length ?
cursorPosition : cursorPosition - 1));
});
return;
}
const edit = (this.$refs.input as FormInput).getLastEdit();
this.lastEditPosition = edit.endIndex;
this.calibratedText = this.calibratedText.slice(0, edit.endIndex);
this.$nextTick(() => {
this.tokenCompletionDropdownPositionX = $(this.$el).find('.width-calibration').width() as number;
});
// deltaLength characters have been inserted/removed at index cursorPosition.
// All manually identified category ranges that are after the cursor position are shifted.
let deltaLength = 0;
if (edit.type === 'insert') {
deltaLength = edit.value.length;
} else if (edit.type === 'delete') {
deltaLength = -edit.value.length;
} else if (edit.type === 'replace') {
deltaLength = edit.value.length - (edit.endIndex - edit.startIndex);
}
// Note that when edit.type is 'undo', there is currently no way to determine the precise changes on the text.
// So we cannot preserve the manually set token categories correctly when the undo changes the index of a
// manually categorized token.
// When deltaLength is zero, it is a single-character replacement
this.manualCategories = this.manualCategories.map(range => {
// If an insertion, deletion, or replacement happens within a manual category range,
// the range is no longer valid and removed.
if (edit.type === 'insert' && range.startIndex < edit.startIndex && edit.startIndex < range.endIndex) {
// Insert strictly within the token.
return null;
} else if (areRangesIntersected([range.startIndex, range.endIndex - 1], [edit.startIndex, edit.endIndex - 1])) {
// Delete or replace touches the range if the two index ranges intersect.
return null;
}
if (range.startIndex >= edit.startIndex) {
range.startIndex += deltaLength;
range.endIndex += deltaLength;
}
return range;
}).filter(category => category !== null) as ManualCategory[];
this.prevText = finalText;
this.parseInput(finalText);
this.text = this.textFromTokens();
this.generateTokenCompletionDropdown();
});
this.generateQueryCompletionDropdown();
}
/**
* Generates text from the parsed tokens.
*/
private textFromTokens(): string {
return this.tokens.map(token => token.text).join('');
}
/**
* Handles tab key that can completes a token.
*/
private onTab() {
if (this.isTokenCompletionDropdownVisible) {
this.tokenCompletionDropdown[this.tokenCompletionDropdownSelectedIndex].onClick();
this.tokenCompletionDropdown = []; // close dropdown
} else if (this.isQueryCompletionDropdownVisible) {
this.queryCompletionDropdown[this.queryCompletionDropdownSelectedIndex].onClick();
this.clearQueryCompletion();
}
}
/**
* Moves down to choose the next auto completable token.
*/
private onArrowDown() {
if (this.isTokenCompletionDropdownVisible) {
this.tokenCompletionDropdownSelectedIndex++;
if (this.tokenCompletionDropdownSelectedIndex >= this.tokenCompletionDropdown.length) {
this.tokenCompletionDropdownSelectedIndex = 0;
}
} else if (this.isQueryCompletionDropdownVisible) {
this.queryCompletionDropdownSelectedIndex++;
if (this.queryCompletionDropdownSelectedIndex >= this.queryCompletionDropdown.length) {
this.queryCompletionDropdownSelectedIndex = 0;
}
}
}
/**
* Moves up to choose the previous auto completable token.
*/
private onArrowUp() {
if (this.isTokenCompletionDropdownVisible) {
this.tokenCompletionDropdownSelectedIndex--;
if (this.tokenCompletionDropdownSelectedIndex < 0) {
this.tokenCompletionDropdownSelectedIndex = this.tokenCompletionDropdown.length - 1;
}
} else if (this.isQueryCompletionDropdownVisible) {
this.queryCompletionDropdownSelectedIndex--;
if (this.queryCompletionDropdownSelectedIndex < 0) {
this.queryCompletionDropdownSelectedIndex = this.queryCompletionDropdown.length - 1;
}
}
}
/**
* Handles enter key.
*/
private onEnter() {
if (this.isTokenCompletionDropdownVisible || this.isQueryCompletionDropdownVisible) {
// If the token/query completion dropdown is visible, choose the option in the dropdown.
this.onTab();
return;
}
// Otherwise, submit the query.
this.submitQuery();
}
private resetQueryCompletionTimeout() {
if (this.queryCompletionDropdownTimeout !== null) {
clearTimeout(this.queryCompletionDropdownTimeout);
}
this.queryCompletionDropdownTimeout = setTimeout(() => this.submitQueryCompletion(), QUERY_COMPLETION_DELAY_MS);
}
/**
* Checks the last token in the list and produces an auto completion list for this token.
*/
private generateTokenCompletionDropdown() {
let startIndex = 0;
let possiblyEditedToken: FlowsenseToken | null = null;
for (const token of this.tokens) {
startIndex += token.text.length;
if (startIndex > this.lastEditPosition) {
possiblyEditedToken = token;
break;
}
}
this.tokenCompletionDropdownSelectedIndex = 0;
this.tokenCompletionDropdown = [];
if (this.tokenCompletionDropdownTimeout !== null) {
clearTimeout(this.tokenCompletionDropdownTimeout);
}
if (possiblyEditedToken === null) {
return;
}
const editedToken = possiblyEditedToken;
const timeout = TOKEN_COMPLETION_DROPDOWN_DELAY_MS;
const utterances = this.flowsenseSpecialUtterances.filter(utterance => {
for (const text of utterance.matchText) {
if (flowsenseUtil.matchNonTrivialPrefix(text, editedToken.text)) {
return true;
}
}
return false;
});
const dropdown = utterances.map((category, categoryIndex) => ({
text: category.displayText || '',
annotation: category.annotation || '',
class: category.category !== FlowsenseTokenCategory.NONE ? 'categorized ' + category.category : '',
onClick: () => {
const deltaLength = (category.displayText as string).length - editedToken.text.length;
const editPosition = this.lastEditPosition + 1;
editedToken.text = category.displayText as string;
this.text = this.textFromTokens();
this.parseInput(this.text);
this.$nextTick(() => {
const inputElement = $(this.$el).find('#input')[0] as HTMLInputElement;
inputElement.setSelectionRange(editPosition + deltaLength, editPosition + deltaLength);
});
this.tokenCompletionDropdown = []; // close the token completion dropdown
},
}));
if (dropdown.length) {
this.tokenCompletionDropdownTimeout =
setTimeout(() => {
this.tokenCompletionDropdown = dropdown;
}, timeout);
}
}
/**
* Generates a token category dropdown for the "index"-th categorizable token.
*/
private generateTokenCategoryDropdown(index: number) {
this.tokenCategoryDropdown = this.tokens[index].categories.map((category, categoryIndex) => ({
text: category.displayText || '',
annotation: category.annotation || '',
class: category.category !== FlowsenseTokenCategory.NONE ? 'categorized ' + category.category : '',
onClick: () => {
this.tokens[index].chosenCategory = categoryIndex;
const existing = this.manualCategories.find(range => range.startIndex === this.tokens[index].index &&
range.endIndex === this.tokens[index].index + this.tokens[index].text.length);
if (existing) {
existing.chosenCategory = categoryIndex;
} else {
this.manualCategories.push({
startIndex: this.tokens[index].index,
endIndex: this.tokens[index].index + this.tokens[index].text.length,
chosenCategory: categoryIndex,
});
}
this.tokenCategoryDropdown = []; // hide dropdown
},
}));
}
/**
* Generates auto completion queries in a dropdown.
*/
private generateQueryCompletionDropdown() {
this.clearQueryCompletion();
this.resetQueryCompletionTimeout();
}
private submitQueryCompletion() {
if (this.queryCompletionDropdownTimeout !== null) {
// submitQueryCompletion may be called from UI button click. Avoid sending the request twice when the user is
// viewing the suggested queries.
clearTimeout(this.queryCompletionDropdownTimeout);
}
if (!this.visible || !this.tokens.length) {
return;
}
this.isWaiting = true;
this.dispatchAutoComplete(this.tokens)
.then(suggestions => {
if (this.isTokenCategoryDropdownVisible ||
this.isTokenCompletionDropdownVisible ||
!this.visible) {
// A dropdown is already in place. Avoid surprising change of dropdown.
return;
}
this.queryCompletionDropdown = suggestions.map(suggestion => {
return {
tokens: suggestion,
onClick: () => {
this.queryCompletionDropdown = [];
this.tokens = suggestion;
this.text = this.textFromTokens();
this.setCursorPosition(this.text.length);
},
};
});
if (!this.queryCompletionDropdown.length) {
this.queryCompletionMessage = 'no suggestions available';
}
$(this.$el).find('#input').focus();
})
.finally(() => this.isWaiting = false);
}
private getCursorPosition(): number {
const inputElement = $(this.$el).find('#input')[0] as HTMLInputElement;
return inputElement.selectionStart as number;
}
private setCursorPosition(position: number) {
const inputElement = $(this.$el).find('#input')[0] as HTMLInputElement;
inputElement.setSelectionRange(position, position);
}
private toggleVoice() {
this.toggleFlowsenseVoice();
}
private clickToken(evt: MouseEvent, index: number) {
this.closeAllDropdowns();
const $target = $(evt.target as HTMLElement);
const offset = elementOffset($target, $(this.$el));
this.clickX = offset.left;
this.clickY = offset.top + ($target.height() as number) + DROPDOWN_MARGIN_PX;
this.generateTokenCategoryDropdown(index);
}
private onHideInput() {
this.isInputHidden = true;
}
private submitQuery() {
if (this.isInputHidden) {
// Do nothing when the input is hidden by clicking on the background.
return;
}
this.isWaiting = true;
this.dispatchQuery(this.tokens)
.then(success => {
if (success) {
// If the query is successful, clear the text to get ready for the next input.
this.text = '';
this.tokens = [];
this.closeFlowsenseInput();
} else {
// If the query is rejected, the text is kept so that it can be edited.
showSystemMessage(this.$store, 'Sorry, FlowSense does not understand that query', 'warn');
}
})
.catch(err => systemMessageErrorHandler(this.$store)(err))
.finally(() => this.isWaiting = false);
}
private onClickQueryCompletion() {
this.closeAllDropdowns();
this.submitQueryCompletion();
}
private clearQueryCompletion() {
this.queryCompletionDropdown = [];
this.queryCompletionMessage = '';
}
private closeAllDropdowns() {
this.tokenCategoryDropdown = [];
this.tokenCompletionDropdown = [];
this.clearQueryCompletion();
}
@Watch('visible')
private onVisibleChange() {
this.tokenCategoryDropdown = []; // hide dropdown whenever visibility changes
this.tokenCompletionDropdown = [];
this.clearQueryCompletion();
this.onVoiceEnabledChange();
if (this.visible) {
this.$nextTick(() => $(this.$el).find('#input').focus()); // wait for transition to complete before focus()
}
}
@Watch('isVoiceEnabled')
private onVoiceEnabledChange() {
if (!this.voice) {
return;
}
if (this.visible && this.isVoiceEnabled) {
this.voice.start();
} else {
this.isVoiceInProgress = false;
this.voice.abort();
}
}
} | the_stack |
import {
Directive,
ElementRef,
EventEmitter,
Inject,
Input,
OnDestroy,
Output,
} from "@angular/core";
import {
Content,
Direction,
LatLng,
latLng,
LatLngExpression,
LeafletEvent,
Point,
Tooltip,
} from "leaflet";
import { LayerProvider } from "./layer.provider";
/**
* Angular2 directive for Leaflet tooltips.
*
* *You can use this directive in an Angular2 template after importing `YagaModule`.*
*
* How to use in a template:
* ```html
* <yaga-map>
* <yaga-marker>
* <yaga-tooltip
* [(content)]="..."
* [(opened)]="..."
* [(lat)]="..."
* [(lng)]="..."
* [(position)]="..."
* [(opacity)]="..."
*
* (open)="..."
* (close)="..."
*
* [className]="..."
* [pane]="..."
* [interactive]="..."
* [sticky]="..."
* [direction]="..."
* [permanent]="..."
* [offset]="..."
* >
* <p>You can pass your content right here!</p>
* </yaga-tooltip>
* </yaga-marker>
* </yaga-map>
* ```
*/
@Directive({
selector: "yaga-tooltip",
})
export class TooltipDirective extends Tooltip implements OnDestroy {
/**
* Two-Way bound property for the content of a tooltip.
* Use it with `<yaga-tooltip [(content)]="someValue">` or `<yaga-tooltip (contentChange)="processEvent($event)">`
*
* You can also pass the content directly within the web-component as view-content
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-setcontent Original Leaflet documentation
*/
@Output() public contentChange: EventEmitter<Content> = new EventEmitter();
/**
* Two-Way bound property for the state of being opened.
* Use it with `<yaga-tooltip [(opened)]="someValue">` or `<yaga-tooltip (openedChange)="processEvent($event)">`
*
* You can also use the `tooltipOpened` property in the parent directives
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-openon Original Leaflet documentation
*/
@Output() public openedChange: EventEmitter<boolean> = new EventEmitter();
/**
* Two-Way bound property for the latitude position of the tooltip.
* Use it with `<yaga-tooltip [(lat)]="someValue">` or `<yaga-tooltip (latChange)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-setlatlng Original Leaflet documentation
*/
@Output() public latChange: EventEmitter<number> = new EventEmitter();
/**
* Two-Way bound property for the longitude position of the tooltip.
* Use it with `<yaga-tooltip [(lng)]="someValue">` or `<yaga-tooltip (lngChange)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-setlatlng Original Leaflet documentation
*/
@Output() public lngChange: EventEmitter<number> = new EventEmitter();
/**
* Two-Way bound property for the position (LatLng) of the tooltip.
* Use it with `<yaga-tooltip [(position)]="someValue">` or `<yaga-tooltip (positionChange)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-setlatlng Original Leaflet documentation
*/
@Output() public positionChange: EventEmitter<LatLng> = new EventEmitter();
/**
* Two-Way bound property for the opacity of the tooltip.
* Use it with `<yaga-tooltip [(opacity)]="someValue">` or `<yaga-tooltip (opacityChange)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-setlatlng Original Leaflet documentation
*/
@Output() public opacityChange: EventEmitter<number> = new EventEmitter();
/**
* From leaflet fired open event.
* Use it with `<yaga-tooltip (open)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-tooltipopen Original Leaflet documentation
*/
@Output("open") public openEvent: EventEmitter<LeafletEvent> = new EventEmitter();
/**
* From leaflet fired close event.
* Use it with `<yaga-tooltip (close)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-tooltipclose Original Leaflet documentation
*/
@Output("close") public closeEvent: EventEmitter<LeafletEvent> = new EventEmitter();
constructor(
protected layerProvider: LayerProvider,
@Inject(ElementRef) elementRef: ElementRef,
) {
super();
this.setContent(elementRef.nativeElement);
this.on("add", (event: LeafletEvent): void => {
this.openEvent.emit(event);
this.openedChange.emit(true);
});
this.on("remove", (event: LeafletEvent): void => {
this.closeEvent.emit(event);
this.openedChange.emit(false);
});
this.layerProvider.ref!.bindTooltip(this);
}
/**
* This function gets called from Angular on destroy of the html-component.
* @link https://angular.io/docs/ts/latest/api/core/index/OnDestroy-class.html
*/
public ngOnDestroy(): void {
this.layerProvider.ref!.unbindTooltip();
}
/**
* Derived method of the original setContent method.
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-setcontent Original Leaflet documentation
*/
public setContent(content: any): this { // Content
this.contentChange.emit((content));
return super.setContent((content as HTMLElement));
}
/**
* Two-Way bound property for the content.
* Use it with `<yaga-tooltip [(content)]="someValue">` or `<yaga-tooltip [content]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-setcontent Original Leaflet documentation
*/
@Input() public set content(val: Content) {
this.setContent(val);
}
public get content(): Content {
return this.getContent() || "";
}
/**
* Two-Way bound property for the opened state.
* Use it with `<yaga-tooltip [(opened)]="someValue">` or `<yaga-tooltip [opened]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-openon Original Leaflet documentation
*/
@Input() public set opened(val: boolean) {
if (val) {
this.layerProvider.ref!.openTooltip();
return;
}
this.layerProvider.ref!.closeTooltip();
}
public get opened(): boolean {
return !!(this as any)._map;
}
/**
* Derived method of the original setLatLng method.
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-setlatlng Original Leaflet documentation
*/
public setLatLng(latlng: LatLngExpression): this {
super.setLatLng(latlng);
this.latChange.emit(this.lat);
this.lngChange.emit(this.lng);
this.positionChange.emit(latLng(this.lat, this.lng));
return this;
}
/**
* Two-Way bound property for the latitude position of the tooltip.
* Use it with `<yaga-tooltip [(lat)]="someValue">` or `<yaga-tooltip [lat]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-setlatlng Original Leaflet documentation
*/
@Input() public set lat(val: number) {
this.setLatLng([val, this.lng]);
}
public get lat(): number {
if (!this.getLatLng()) {
return NaN;
}
return this.getLatLng()!.lat;
}
/**
* Two-Way bound property for the longitude position of the tooltip.
* Use it with `<yaga-tooltip [(lng)]="someValue">` or `<yaga-tooltip [lng]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-setlatlng Original Leaflet documentation
*/
@Input() public set lng(val: number) {
this.setLatLng([this.lat, val]);
}
public get lng(): number {
if (!this.getLatLng()) {
return NaN;
}
return this.getLatLng()!.lng;
}
/**
* Two-Way bound property for the position of the tooltip.
* Use it with `<yaga-tooltip [(position)]="someValue">` or `<yaga-tooltip [position]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-setlatlng Original Leaflet documentation
*/
@Input() public set position(val: LatLng) {
this.setLatLng(val);
}
public get position(): LatLng {
if (!this.getLatLng()) {
return new LatLng(NaN, NaN);
}
return this.getLatLng()!;
}
/**
* Derived method of the original setContent method.
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-setcontent Original Leaflet documentation
*/
public setOpacity(val: number): void {
super.setOpacity(val);
this.opacityChange.emit(val);
}
/**
* Two-Way bound property for the opacity of the tooltip.
* Use it with `<yaga-tooltip [(opacity)]="someValue">` or `<yaga-tooltip [opacity]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-opacity Original Leaflet documentation
*/
@Input() public set opacity(val: number | undefined) {
if (val === undefined) {
val = 1;
}
this.setOpacity(val);
}
public get opacity(): number | undefined {
return this.options.opacity;
}
/**
* Input for the CSS class name.
* Use it with `<yaga-tooltip [autoClose]="className">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-classname Original Leaflet documentation
*/
@Input() public set className(val: string | undefined) {
if (!(this as any)._container) {
this.options.className = val;
return;
}
const oldClassName = ((this as any)._container as HTMLDivElement).getAttribute("class") || "";
const newClassNameSplited: string[] = oldClassName.split(` ${this.options.className} `);
if (newClassNameSplited.length === 1) {
newClassNameSplited.push("");
}
((this as any)._container as HTMLDivElement).setAttribute("class", newClassNameSplited.join(` ${val} `).trim());
this.options.className = val;
}
public get className(): string | undefined {
return this.options.className;
}
/**
* Input for the pane.
* Use it with `<yaga-tooltip [pane]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-pane Original Leaflet documentation
*/
@Input() public set pane(val: string | undefined) {
this.options.pane = val;
(this as any)._updateLayout();
}
public get pane(): string | undefined {
return this.options.pane;
}
/**
* Input for the interactive state.
* Use it with `<yaga-tooltip [interactive]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-interactive Original Leaflet documentation
*/
@Input() public set interactive(val: boolean) {
this.options.interactive = val;
(this as any)._updateLayout();
}
public get interactive(): boolean {
return !!this.options.interactive;
}
/**
* Input for the sticky.
* Use it with `<yaga-tooltip [sticky]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-sticky Original Leaflet documentation
*/
@Input() public set sticky(val: boolean) {
(this as any)._initTooltipInteractions.call(this.layerProvider.ref, true);
this.options.sticky = val;
(this as any)._initTooltipInteractions.call(this.layerProvider.ref, false);
}
public get sticky(): boolean {
return !!this.options.sticky;
}
/**
* Input for the direction.
* Use it with `<yaga-tooltip [direction]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-direction Original Leaflet documentation
*/
@Input() public set direction(val: Direction | undefined) {
this.options.direction = val;
this.reopen();
}
public get direction(): Direction | undefined {
return this.options.direction;
}
/**
* Input for the permanent state.
* Use it with `<yaga-tooltip [permanent]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-permanent Original Leaflet documentation
*/
@Input() public set permanent(val: boolean) {
(this as any)._initTooltipInteractions.call(this.layerProvider.ref, true);
this.options.permanent = val;
(this as any)._initTooltipInteractions.call(this.layerProvider.ref, false);
}
public get permanent(): boolean {
return !!this.options.permanent;
}
/**
* Input for the offset.
* Use it with `<yaga-tooltip [offset]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#tooltip-offset Original Leaflet documentation
*/
@Input() public set offset(val: Point | undefined) {
this.options.offset = val;
this.reopen();
}
public get offset(): Point | undefined {
return (this.options.offset as Point);
}
public reopen(force: boolean = false) {
if (force || this.opened) {
this.layerProvider.ref!.closeTooltip();
this.layerProvider.ref!.openTooltip();
}
}
} | the_stack |
import {
CascaderCI,
CheckboxCI,
CheckboxGroupCI,
CI,
DatePickerCI,
DialogCI,
DrawerCI,
DropdownCI,
DropdownItemCI,
DropdownMenuCI,
FormCI,
FormItemCI,
FormWrapperCI,
IconCI,
Icons,
ImageCI,
ImageGroupCI,
InputCI,
InputGroupCI,
InputPasswordCI,
LoadingCI,
MessageBoxCI,
MessageCI,
NotificationCI,
ProgressCI,
RadioCI,
RadioGroupCI,
SelectCI,
OptionCI,
SwitchCI,
TableCI,
TableColumnCI,
TagCI,
TextAreaCI,
TimePickerCI,
UiInterface,
UploadCI,
TreeSelectCI,
TabsCI,
TabPaneCI,
CollapseCI,
CollapseItemCI,
ButtonCI,
PaginationCI
} from "@fast-crud/ui-interface";
import { TooltipCI } from "../../ui-interface/src/ui-interface";
export class Antdv implements UiInterface {
constructor(target) {
this.notification.get = target.Notification;
this.message.get = target.Message;
this.messageBox.get = target.MessageBox;
}
type = "antdv";
modelValue = "value";
formWrapper: FormWrapperCI = {
visible: "visible",
customClass: "class",
titleSlotName: "title",
buildOnClosedBind(is, onClosed: Function): {} {
if (is === "a-modal") {
return { afterClose: onClosed };
} else if (is === "a-drawer") {
return {
onAfterVisibleChange: (visible) => {
if (visible === false) {
onClosed(visible);
}
}
};
}
return {};
},
buildWidthBind(is, width) {
return { width: width };
},
buildInitBind(is) {
return {};
},
name: "fs-form-wrapper"
};
messageBox: MessageBoxCI = {
name: "a-model",
get: undefined,
open: (context) => {
return this.messageBox.confirm(context);
},
confirm: (context) => {
return new Promise<void>((resolve, reject) => {
function onOk() {
resolve();
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
function onCancel() {
reject(new Error("cancel"));
}
const newContext = {
...context,
content: context.message,
onOk,
onCancel
};
this.messageBox.get.confirm(newContext);
});
}
};
message: MessageCI = {
get: undefined,
name: "a-message",
open: (type, context) => {
let content = context;
if (typeof context !== "string") {
content = context.message || context.content;
}
this.message.get[type](content);
},
success: (context) => {
this.message.open("success", context);
},
error: (context) => {
this.message.open("error", context);
},
warn: (context) => {
this.message.open("warn", context);
},
info: (context) => {
this.message.open("info", context);
}
};
notification: NotificationCI = {
get: undefined,
name: "a-notification",
open: (type, context) => {
if (typeof context === "string") {
context = {
message: context
};
}
type = type || context.type;
if (type) {
this.notification.get[type](context);
} else {
this.notification.get.open(context);
}
},
success: (context) => {
this.notification.open("success", context);
},
error: (context) => {
this.notification.open("error", context);
},
warn: (context) => {
this.notification.open("warn", context);
},
info: (context) => {
this.notification.open("info", context);
}
};
icon: IconCI = {
name: "",
isComponent: true
};
icons: Icons = {
add: "PlusOutlined",
columnsFilter: "ControlOutlined",
compact: "DragOutlined",
edit: "EditOutlined",
export: "UploadOutlined",
refresh: "SyncOutlined",
remove: "DeleteOutlined",
search: "SearchOutlined",
check: "CheckOutlined",
sort: "DragOutlined",
close: "CloseOutlined",
arrowRight: "ArrowRightOutlined",
arrowLeft: "ArrowLeftOutlined",
left: "LeftOutlined",
right: "RightOutlined",
more: "EllipsisOutlined",
plus: "PlusOutlined",
zoomIn: "ZoomInOutlined",
zoomOut: "ZoomOutOutlined",
refreshLeft: "UndoOutlined",
refreshRight: "RedoOutlined",
upload: "UploadOutlined",
fullScreen: "CompressOutlined",
unFullScreen: "ExpandOutlined",
question: "QuestionCircleOutlined"
};
dialog: DialogCI = {
name: "a-modal",
visible: "visible",
customClass: "wrapClassName",
footer(footer = null) {
return { footer };
},
buildOnClosedBind(onClosed: Function): {} {
return { afterClose: onClosed };
}
};
button: ButtonCI = {
name: "a-button",
textType: { type: "link" },
linkType: { type: "link" },
circle: { shape: "circle" },
colors: (type) => {
if (type === "danger") {
return { danger: true };
}
if (type === "info" || type === "warning") {
return { type: "default" };
}
return { type };
}
};
buttonGroup: CI = {
name: "a-button-group"
};
card: CI = {
name: "a-card"
};
cascader: CascaderCI = {
name: "a-cascader",
modelValue: "value",
clearable: "allowClear",
fieldNames(namesMap) {
return { fieldNames: namesMap };
}
};
checkboxGroup: CheckboxGroupCI = {
name: "a-checkbox-group",
modelValue: "value"
};
checkbox: CheckboxCI = {
name: "a-checkbox",
resolveEvent(e) {
return e.target.checked;
},
value: "value",
modelValue: "checked",
onChange(callback){
return {
"onUpdate:checked": callback
}
}
};
col: CI = {
name: "a-col"
};
collapseTransition: CI = {
name: "div"
};
drawer: DrawerCI = {
name: "a-drawer",
visible: "visible",
customClass: "class",
width: "width"
};
form: FormCI = {
name: "a-form",
inlineLayout: {
layout: "inline",
inline: true
},
resetWrap: (formRef, { form, initialForm }) => {
formRef.resetFields();
},
validateWrap: async (formRef) => {
return formRef.validate();
}
};
formItem: FormItemCI = {
name: "a-form-item",
prop: "name",
label: "label",
rules: "rules"
};
option: OptionCI = {
name: "a-select-option",
value: "value",
label: "label"
};
pagination: PaginationCI = {
name: "a-pagination",
currentPage: "current",
total: "total",
pageCount: null,
onChange({ setCurrentPage, setPageSize, doAfterChange }) {
return {
// antd 页码改动回调
onChange(page) {
setCurrentPage(page);
doAfterChange();
},
onShowSizeChange(current, size) {
setPageSize(size);
doAfterChange();
}
};
}
};
radio: RadioCI = {
name: "a-radio",
value: "value"
};
radioGroup: RadioGroupCI = {
name: "a-radio-group",
modelValue: "value"
};
row: CI = {
name: "a-row"
};
select: SelectCI = {
name: "a-select",
modelValue: "value",
clearable: "allowClear"
};
treeSelect: TreeSelectCI = {
name: "a-tree-select",
modelValue: "value",
clearable: "allowClear",
options: "tree-data",
value: "value",
label: "label",
children: "children"
};
table: TableCI = {
name: "a-table",
data: "dataSource",
renderMode: "config",
renderMethod: "customRender",
rebuildRenderScope: (scope) => {
return scope;
},
buildMaxHeight: (maxHeight) => {
return { scroll: { y: maxHeight }};
},
hasMaxHeight: (options) => {
return options?.scroll?.y != null;
},
defaultRowKey: "id",
fixedHeaderNeedComputeBodyHeight: true,
headerDomSelector: ".ant-table-thead",
vLoading: false,
onChange({ onSortChange, onFilterChange, onPagination }) {
return {
onChange: (pagination, filters, sorter, { currentDataSource }) => {
if (pagination && onPagination) {
onPagination({ ...pagination, data: currentDataSource });
}
if (filters && onFilterChange) {
onFilterChange({ ...filters, data: currentDataSource });
}
if (sorter && onSortChange) {
const { column, field, order } = sorter;
onSortChange({
isServerSort: order && column.sorter === true,
prop: field,
order,
asc: order === "ascend"
});
}
}
};
}
};
tableColumn: TableColumnCI = {
name: "a-table-column",
label: "title",
prop: "key",
row: "record",
index: "index"
};
tableColumnGroup: TableColumnCI = {
name: "a-table-column-group",
label: "title",
prop: "key",
row: "record",
index: "index"
};
textArea: TextAreaCI = {
name: "a-textarea",
type: undefined,
modelValue: "value",
clearable: "allowClear"
};
tag: TagCI = {
name: "a-tag",
type: "color",
colors: ["blue", "green", "orange", "red", "cyan", "purple"]
};
inputGroup: InputGroupCI = {
name: "a-input"
};
input: InputCI = {
name: "a-input",
clearable: "allowClear",
modelValue: "value"
};
inputPassword: InputPasswordCI = {
name: "a-input-password",
clearable: "allowClear",
modelValue: "value",
passwordType: { showPassword: true }
};
number: CI = {
name: "a-input-number"
};
switch: SwitchCI = {
activeColor: "active-color",
activeText: "checkedChildren",
activeValue: "active-value",
inactiveColor: "inactive-color",
inactiveText: "unCheckedChildren",
inactiveValue: "inactive-value",
modelValue: "checked",
name: "a-switch"
};
datePicker: DatePickerCI = {
name: "a-date-picker",
modelValue: "value",
buildDateType(type) {
if (type === "date") {
return { name: "a-date-picker" };
}
// year/month/date/week/datetime/datetimerange/daterange
if (type === "datetime") {
return { name: "a-date-picker", showTime: true };
}
if (type === "daterange") {
return { name: "a-range-picker" };
}
if (type === "datetimerange") {
return { name: "a-range-picker", showTime: true };
}
if (type === "month") {
return { name: "a-month-picker" };
}
if (type === "week") {
return { name: "a-week-picker" };
}
return { name: "a-date-picker" };
}
};
timePicker: TimePickerCI = {
name: "a-time-picker",
modelValue: "value"
};
dropdown: DropdownCI = {
name: "a-dropdown",
command: () => {
return {};
},
slotName: "overlay",
renderMode: "slot"
};
dropdownMenu: DropdownMenuCI = {
name: "a-menu",
command: (callback) => {
return {
onClick($event) {
callback($event.key);
}
};
}
};
dropdownItem: DropdownItemCI = {
name: "a-menu-item",
command: "key"
};
imageGroup: ImageGroupCI = {
name: "a-image-preview-group"
};
image: ImageCI = {
name: "a-image",
buildPreviewList: () => {
return {};
}
};
progress: ProgressCI = {
name: "a-progress"
};
loading: LoadingCI = {
name: "a-spin",
type: "component"
};
upload: UploadCI = {
name: "a-upload",
type: "",
typeImageCard: "picture-card",
typeImage: "picture",
getStatusFromEvent(event) {
return event?.file?.status;
},
getFileListFromEvent(event) {
return event?.fileList;
},
status: {
success: "done",
uploading: "uploading"
},
limitAdd: 0
};
tabs: TabsCI = {
name: "a-tabs"
};
tabPane: TabPaneCI = {
name: "a-tab-pane"
};
collapse: CollapseCI = {
name: "a-collapse",
modelValue: "activeKey",
keyName: "key"
};
collapseItem: CollapseItemCI = {
name: "a-collapse-panel"
};
tooltip: TooltipCI = {
name: "a-tooltip",
content: "title",
trigger: "default"
};
} | the_stack |
import { inject, Container } from 'aurelia-dependency-injection'
import {
CameraEventAggregator,
CameraEventType,
ConstantPositionProperty,
ConstantProperty,
ReferenceFrame,
Cartographic,
Cartesian2,
Cartesian3,
Quaternion,
Matrix3,
Matrix4,
PerspectiveFrustum,
CesiumMath
} from '../cesium/cesium-imports'
import { Configuration, Role, SerializedSubviewList } from '../common'
import { SessionService, ConnectService, SessionConnectService } from '../session'
import {
eastUpSouthToFixedFrame,
decomposePerspectiveProjectionMatrix,
getEntityPositionInReferenceFrame,
getEntityOrientationInReferenceFrame
} from '../utils'
import { EntityService } from '../entity'
import { ContextService } from '../context'
import { DeviceService } from '../device'
import { ViewService } from '../view'
import { PoseStatus } from '../entity'
import { RealityViewer } from './base'
import { RealityService } from '../reality'
import { VisibilityService } from '../visibility'
interface Movement {
startPosition:Cartesian2;
endPosition:Cartesian2;
}
interface PinchMovement {
distance: Movement;
angleAndHeight: Movement;
}
@inject(SessionService, ViewService, Container)
export class EmptyRealityViewer extends RealityViewer {
public type = 'empty';
private _aggregator:CameraEventAggregator|undefined;
private _moveFlags = {
moveForward : false,
moveBackward : false,
moveUp : false,
moveDown : false,
moveLeft : false,
moveRight : false
}
constructor(
private sessionService: SessionService,
private viewService: ViewService,
private container: Container,
public uri:string) {
super(uri);
function getFlagForKeyCode(keyCode) {
switch (keyCode) {
case 'W'.charCodeAt(0):
return 'moveForward';
case 'S'.charCodeAt(0):
return 'moveBackward';
case 'E'.charCodeAt(0):
return 'moveUp';
case 'R'.charCodeAt(0):
return 'moveDown';
case 'D'.charCodeAt(0):
return 'moveRight';
case 'A'.charCodeAt(0):
return 'moveLeft';
default:
return undefined;
}
}
const keydownListener = (e) => {
var flagName = getFlagForKeyCode(e.keyCode);
if (typeof flagName !== 'undefined') {
this._moveFlags[flagName] = true;
}
}
const keyupListener = (e) => {
var flagName = getFlagForKeyCode(e.keyCode);
if (typeof flagName !== 'undefined') {
this._moveFlags[flagName] = false;
}
}
if (typeof document !== 'undefined') {
this.presentChangeEvent.addEventListener(()=>{
if (this.isPresenting) {
this.viewService.element.style.backgroundColor = 'white';
if (!this._aggregator && this.viewService.element) {
this.viewService.element['disableRootEvents'] = true;
this._aggregator = new CameraEventAggregator(<any>this.viewService.element);
document.addEventListener('keydown', keydownListener, false);
document && document.addEventListener('keyup', keyupListener, false);
}
} else {
delete this.viewService.element.style.backgroundColor;
this._aggregator && this._aggregator.destroy();
this._aggregator = undefined;
document && document.removeEventListener('keydown', keydownListener);
document && document.removeEventListener('keyup', keyupListener);
for (const k in this._moveFlags) {
this._moveFlags[k] = false;
}
}
});
}
}
private _scratchMatrix3 = new Matrix3;
private _scratchMatrix4 = new Matrix4;
public load(): void {
// Create a child container so that we can conveniently setup all the services
// that would exist in a normal hosted reality viewer
const child = this.container.createChild();
// Create the session instance that will be used by the manager to talk to the reality
const session = this.sessionService.addManagedSessionPort(this.uri);
session.connectEvent.addEventListener(()=>{
this.connectEvent.raiseEvent(session); // let the manager know the session is ready
});
// use a SessionConnectService to create a connection via the session instance we created
child.registerInstance(ConnectService,
new SessionConnectService(session, this.sessionService.configuration)
);
// setup the configuration for our empty reality
child.registerInstance(Configuration, {
role: Role.REALITY_VIEWER,
uri: this.uri,
title: 'Empty',
version: this.sessionService.configuration.version,
supportsCustomProtocols: true,
protocols: ['ar.configureStage@v1']
});
// Create the basic services that we need to use.
// Note: we won't create a child ViewService here,
// as we are already managing the DOM with the
// ViewService that exists in the root container.
child.autoRegisterAll([SessionService, EntityService, VisibilityService, ContextService, DeviceService, RealityService]);
const childContextService = child.get(ContextService) as ContextService;
const childDeviceService = child.get(DeviceService) as DeviceService;
const childSessionService = child.get(SessionService) as SessionService;
const childRealityService = child.get(RealityService) as RealityService;
const childViewService = child.get(ViewService) as ViewService;
// the child device service should *not* submit frames to the vrdisplay.
childDeviceService.autoSubmitFrame = false;
let customStagePosition:Cartesian3|undefined;
let customStageOrientation:Quaternion|undefined;
// Create protocol handlers for `ar.configureStage` protocol
childRealityService.connectEvent.addEventListener((session)=>{
session.on['ar.configureStage.setStageGeolocation'] = ({geolocation}:{geolocation:Cartographic}) => {
customStagePosition = Cartesian3.fromRadians(geolocation.longitude, geolocation.latitude, geolocation.height, undefined, customStagePosition);
const transformMatrix = eastUpSouthToFixedFrame(customStagePosition, undefined, this._scratchMatrix4);
const rotationMatrix = Matrix4.getRotation(transformMatrix, this._scratchMatrix3);
customStageOrientation = Quaternion.fromRotationMatrix(rotationMatrix, customStageOrientation);
}
session.on['ar.configureStage.resetStageGeolocation'] = () => {
customStagePosition = undefined;
customStageOrientation = undefined;
}
});
// Setup everything after connected to the manager. The manager only connects once.
childSessionService.manager.connectEvent.addEventListener(()=>{
// since we aren't create a child view service and viewport service,
// suppress any errors from not handling these messages
childSessionService.manager.suppressErrorOnUnknownTopic = true;
const scratchQuaternion = new Quaternion;
const scratchQuaternionDragYaw = new Quaternion;
// const pitchQuat = new Quaternion;
const positionScratchCartesian = new Cartesian3;
const movementScratchCartesian = new Cartesian3;
const orientationMatrix = new Matrix3;
const up = new Cartesian3(0,0,1);
const right = new Cartesian3(1,0,0);
const forward = new Cartesian3(0,-1,0);
const scratchFrustum = new PerspectiveFrustum();
const deviceStage = childDeviceService.stage;
const deviceUser = childDeviceService.user;
const NEGATIVE_UNIT_Z = new Cartesian3(0,0,-1);
// const X_90ROT = Quaternion.fromAxisAngle(Cartesian3.UNIT_X, CesiumMath.PI_OVER_TWO);
const subviews:SerializedSubviewList = [];
const deviceUserPose = childContextService.createEntityPose(deviceUser, deviceStage);
const checkSuggestedGeolocationSubscription = () => {
if (childDeviceService.suggestedGeolocationSubscription) {
childDeviceService.subscribeGeolocation(childDeviceService.suggestedGeolocationSubscription);
} else {
childDeviceService.unsubscribeGeolocation();
}
}
checkSuggestedGeolocationSubscription();
const remove1 = childDeviceService.suggestedGeolocationSubscriptionChangeEvent.addEventListener(checkSuggestedGeolocationSubscription);
const remove2 = childDeviceService.frameStateEvent.addEventListener((frameState) => {
if (childSessionService.manager.isClosed) return;
const aggregator = this._aggregator;
const flags = this._moveFlags;
if (!this.isPresenting) {
aggregator && aggregator.reset();
return;
}
SerializedSubviewList.clone(frameState.subviews, subviews);
// provide fov controls
if (!childDeviceService.strict) {
decomposePerspectiveProjectionMatrix(subviews[0].projectionMatrix, scratchFrustum);
scratchFrustum.fov = childViewService.subviews[0] && childViewService.subviews[0].frustum.fov || CesiumMath.PI_OVER_THREE;
if (aggregator && aggregator.isMoving(CameraEventType.WHEEL)) {
const wheelMovement = aggregator.getMovement(CameraEventType.WHEEL);
const diff = wheelMovement.endPosition.y;
scratchFrustum.fov = Math.min(Math.max(scratchFrustum.fov - diff * 0.02, Math.PI/8), Math.PI-Math.PI/8);
}
if (aggregator && aggregator.isMoving(CameraEventType.PINCH)) {
const pinchMovement:PinchMovement = aggregator.getMovement(CameraEventType.PINCH);
const diff = pinchMovement.distance.endPosition.y - pinchMovement.distance.startPosition.y;
scratchFrustum.fov = Math.min(Math.max(scratchFrustum.fov - diff * 0.02, Math.PI/8), Math.PI-Math.PI/8);
}
subviews.forEach((s)=>{
const aspect = s.viewport.width / s.viewport.height;
scratchFrustum.aspectRatio = isFinite(aspect) ? aspect : 1;
Matrix4.clone(scratchFrustum.projectionMatrix, s.projectionMatrix);
});
}
const time = frameState.time;
deviceUserPose.update(time);
const overrideUser = !(deviceUserPose.status & PoseStatus.KNOWN);
// provide controls if the device does not have a physical pose
if (overrideUser) {
const contextUser = childContextService.user;
const contextStage = childContextService.stage;
const position =
getEntityPositionInReferenceFrame(contextUser, time, contextStage, positionScratchCartesian) ||
Cartesian3.fromElements(0, childDeviceService.suggestedUserHeight, 0, positionScratchCartesian);
let orientation = getEntityOrientationInReferenceFrame(contextUser, time, contextStage, scratchQuaternion) ||
Quaternion.clone(Quaternion.IDENTITY, scratchQuaternion);
if (aggregator && aggregator.isMoving(CameraEventType.LEFT_DRAG)) {
const dragMovement = aggregator.getMovement(CameraEventType.LEFT_DRAG);
if (orientation) {
// const dragPitch = Quaternion.fromAxisAngle(Cartesian3.UNIT_X, frustum.fov * (dragMovement.endPosition.y - dragMovement.startPosition.y) / app.view.getViewport().height, scratchQuaternionDragPitch);
const dragYaw = Quaternion.fromAxisAngle(Cartesian3.UNIT_Y, scratchFrustum.fov * (dragMovement.endPosition.x - dragMovement.startPosition.x) / frameState.viewport.width, scratchQuaternionDragYaw);
// const drag = Quaternion.multiply(dragPitch, dragYaw, dragYaw);
orientation = Quaternion.multiply(orientation, dragYaw, dragYaw);
(<any>contextUser.orientation).setValue(orientation);
}
}
Matrix3.fromQuaternion(orientation, orientationMatrix);
Matrix3.multiplyByVector(orientationMatrix, Cartesian3.UNIT_Y, up);
Matrix3.multiplyByVector(orientationMatrix, Cartesian3.UNIT_X, right);
Matrix3.multiplyByVector(orientationMatrix, NEGATIVE_UNIT_Z, forward);
var moveRate = 0.02;
if (flags.moveForward) {
Cartesian3.multiplyByScalar(forward, moveRate, movementScratchCartesian);
Cartesian3.add(position, movementScratchCartesian, position);
}
if (flags.moveBackward) {
Cartesian3.multiplyByScalar(forward, -moveRate, movementScratchCartesian);
Cartesian3.add(position, movementScratchCartesian, position);
}
if (flags.moveUp) {
Cartesian3.multiplyByScalar(up, moveRate, movementScratchCartesian);
Cartesian3.add(position, movementScratchCartesian, position);
}
if (flags.moveDown) {
Cartesian3.multiplyByScalar(up, -moveRate, movementScratchCartesian);
Cartesian3.add(position, movementScratchCartesian, position);
}
if (flags.moveLeft) {
Cartesian3.multiplyByScalar(right, -moveRate, movementScratchCartesian);
Cartesian3.add(position, movementScratchCartesian, position);
}
if (flags.moveRight) {
Cartesian3.multiplyByScalar(right, moveRate, movementScratchCartesian);
Cartesian3.add(position, movementScratchCartesian, position);
}
(contextUser.position as ConstantPositionProperty).setValue(position, contextStage);
(contextUser.orientation as ConstantProperty).setValue(orientation);
}
const overrideStage = customStagePosition && customStageOrientation ? true : false;
if (overrideStage) {
const contextStage = childContextService.stage;
(contextStage.position as ConstantPositionProperty).setValue(customStagePosition, ReferenceFrame.FIXED);
(contextStage.orientation as ConstantProperty).setValue(customStageOrientation);
}
const contextFrameState = childContextService.createFrameState(
time,
frameState.viewport,
subviews,
{
overrideUser,
overrideStage
}
);
childContextService.submitFrameState(contextFrameState);
aggregator && aggregator.reset();
});
childSessionService.manager.closeEvent.addEventListener(()=>{
remove1();
remove2();
});
})
childSessionService.connect();
}
} | the_stack |
import path from 'path'
import { CustomState } from '@vue/devtools-api'
import { stringifyCircularAutoChunks, parseCircularAutoChunks } from './transfer'
import {
getInstanceMap,
getCustomInstanceDetails,
getCustomRouterDetails,
getCustomStoreDetails,
isVueInstance,
} from './backend'
import { SharedData } from './shared-data'
import { isChrome, target } from './env'
function cached (fn) {
const cache = Object.create(null)
return function cachedFn (str) {
const hit = cache[str]
return hit || (cache[str] = fn(str))
}
}
const classifyRE = /(?:^|[-_/])(\w)/g
export const classify = cached((str) => {
return str && str.replace(classifyRE, toUpper)
})
const camelizeRE = /-(\w)/g
export const camelize = cached((str) => {
return str && str.replace(camelizeRE, toUpper)
})
const kebabizeRE = /([a-z0-9])([A-Z])/g
export const kebabize = cached((str) => {
return str && str
.replace(kebabizeRE, (_, lowerCaseCharacter, upperCaseLetter) => {
return `${lowerCaseCharacter}-${upperCaseLetter}`
})
.toLowerCase()
})
function toUpper (_, c) {
return c ? c.toUpperCase() : ''
}
export function getComponentDisplayName (originalName, style = 'class') {
switch (style) {
case 'class':
return classify(originalName)
case 'kebab':
return kebabize(originalName)
case 'original':
default:
return originalName
}
}
export function inDoc (node) {
if (!node) return false
const doc = node.ownerDocument.documentElement
const parent = node.parentNode
return doc === node ||
doc === parent ||
!!(parent && parent.nodeType === 1 && (doc.contains(parent)))
}
/**
* Stringify/parse data using CircularJSON.
*/
export const UNDEFINED = '__vue_devtool_undefined__'
export const INFINITY = '__vue_devtool_infinity__'
export const NEGATIVE_INFINITY = '__vue_devtool_negative_infinity__'
export const NAN = '__vue_devtool_nan__'
export const SPECIAL_TOKENS = {
true: true,
false: false,
undefined: UNDEFINED,
null: null,
'-Infinity': NEGATIVE_INFINITY,
Infinity: INFINITY,
NaN: NAN,
}
export const MAX_STRING_SIZE = 10000
export const MAX_ARRAY_SIZE = 5000
export function specialTokenToString (value) {
if (value === null) {
return 'null'
} else if (value === UNDEFINED) {
return 'undefined'
} else if (value === NAN) {
return 'NaN'
} else if (value === INFINITY) {
return 'Infinity'
} else if (value === NEGATIVE_INFINITY) {
return '-Infinity'
}
return false
}
/**
* Needed to prevent stack overflow
* while replacing complex objects
* like components because we create
* new objects with the CustomValue API
* (.i.e `{ _custom: { ... } }`)
*/
class EncodeCache {
map: Map<any, any>
constructor () {
this.map = new Map()
}
/**
* Returns a result unique to each input data
* @param {*} data Input data
* @param {*} factory Function used to create the unique result
*/
cache<TResult, TData> (data: TData, factory: (data: TData) => TResult): TResult {
const cached: TResult = this.map.get(data)
if (cached) {
return cached
} else {
const result = factory(data)
this.map.set(data, result)
return result
}
}
clear () {
this.map.clear()
}
}
const encodeCache = new EncodeCache()
class ReviveCache {
map: Map<number, any>
index: number
size: number
maxSize: number
constructor (maxSize: number) {
this.maxSize = maxSize
this.map = new Map()
this.index = 0
this.size = 0
}
cache (value: any) {
const currentIndex = this.index
this.map.set(currentIndex, value)
this.size++
if (this.size > this.maxSize) {
this.map.delete(currentIndex - this.size)
this.size--
}
this.index++
return currentIndex
}
read (id: number) {
return this.map.get(id)
}
}
const reviveCache = new ReviveCache(1000)
export function stringify (data) {
// Create a fresh cache for each serialization
encodeCache.clear()
return stringifyCircularAutoChunks(data, replacer)
}
function replacer (key) {
// @ts-ignore
const val = this[key]
const type = typeof val
if (Array.isArray(val)) {
const l = val.length
if (l > MAX_ARRAY_SIZE) {
return {
_isArray: true,
length: l,
items: val.slice(0, MAX_ARRAY_SIZE),
}
}
return val
} else if (typeof val === 'string') {
if (val.length > MAX_STRING_SIZE) {
return val.substr(0, MAX_STRING_SIZE) + `... (${(val.length)} total length)`
} else {
return val
}
} else if (type === 'undefined') {
return UNDEFINED
} else if (val === Infinity) {
return INFINITY
} else if (val === -Infinity) {
return NEGATIVE_INFINITY
} else if (type === 'function') {
return getCustomFunctionDetails(val)
} else if (type === 'symbol') {
return `[native Symbol ${Symbol.prototype.toString.call(val)}]`
} else if (val !== null && type === 'object') {
const proto = Object.prototype.toString.call(val)
if (proto === '[object Map]') {
return encodeCache.cache(val, () => getCustomMapDetails(val))
} else if (proto === '[object Set]') {
return encodeCache.cache(val, () => getCustomSetDetails(val))
} else if (proto === '[object RegExp]') {
// special handling of native type
return `[native RegExp ${RegExp.prototype.toString.call(val)}]`
} else if (proto === '[object Date]') {
return `[native Date ${Date.prototype.toString.call(val)}]`
} else if (proto === '[object Error]') {
return `[native Error ${val.message}<>${val.stack}]`
} else if (val.state && val._vm) {
return encodeCache.cache(val, () => getCustomStoreDetails(val))
} else if (val.constructor && val.constructor.name === 'VueRouter') {
return encodeCache.cache(val, () => getCustomRouterDetails(val))
} else if (isVueInstance(val)) {
return encodeCache.cache(val, () => getCustomInstanceDetails(val))
} else if (typeof val.render === 'function') {
return encodeCache.cache(val, () => getCustomComponentDefinitionDetails(val))
} else if (val.constructor && val.constructor.name === 'VNode') {
return `[native VNode <${val.tag}>]`
} else if (val instanceof HTMLElement) {
return encodeCache.cache(val, () => getCustomHTMLElementDetails(val))
}
} else if (Number.isNaN(val)) {
return NAN
}
return sanitize(val)
}
export function getCustomMapDetails (val) {
const list = []
val.forEach(
(value, key) => list.push({
key,
value,
}),
)
return {
_custom: {
type: 'map',
display: 'Map',
value: list,
readOnly: true,
fields: {
abstract: true,
},
},
}
}
export function reviveMap (val) {
const result = new Map()
const list = val._custom.value
for (let i = 0; i < list.length; i++) {
const { key, value } = list[i]
result.set(key, revive(value))
}
return result
}
export function getCustomSetDetails (val) {
const list = Array.from(val)
return {
_custom: {
type: 'set',
display: `Set[${list.length}]`,
value: list,
readOnly: true,
},
}
}
export function reviveSet (val) {
const result = new Set()
const list = val._custom.value
for (let i = 0; i < list.length; i++) {
const value = list[i]
result.add(revive(value))
}
return result
}
// Use a custom basename functions instead of the shimed version
// because it doesn't work on Windows
function basename (filename, ext) {
return path.basename(
filename.replace(/^[a-zA-Z]:/, '').replace(/\\/g, '/'),
ext,
)
}
export function getComponentName (options) {
const name = options.displayName || options.name || options._componentTag
if (name) {
return name
}
const file = options.__file // injected by vue-loader
if (file) {
return classify(basename(file, '.vue'))
}
}
export function getCustomComponentDefinitionDetails (def) {
let display = getComponentName(def)
if (display) {
if (def.name && def.__file) {
display += ` <span>(${def.__file})</span>`
}
} else {
display = '<i>Unknown Component</i>'
}
return {
_custom: {
type: 'component-definition',
display,
tooltip: 'Component definition',
...def.__file
? {
file: def.__file,
}
: {},
},
}
}
// eslint-disable-next-line @typescript-eslint/ban-types
export function getCustomFunctionDetails (func: Function): CustomState {
let string = ''
let matches = null
try {
string = Function.prototype.toString.call(func)
matches = String.prototype.match.call(string, /\([\s\S]*?\)/)
} catch (e) {
// Func is probably a Proxy, which can break Function.prototype.toString()
}
// Trim any excess whitespace from the argument string
const match = matches && matches[0]
const args = typeof match === 'string'
? `(${match.substr(1, match.length - 2).split(',').map(a => a.trim()).join(', ')})`
: '(?)'
const name = typeof func.name === 'string' ? func.name : ''
return {
_custom: {
type: 'function',
display: `<span>f</span> ${escape(name)}${args}`,
_reviveId: reviveCache.cache(func),
},
}
}
export function getCustomHTMLElementDetails (value: HTMLElement): CustomState {
try {
return {
_custom: {
type: 'HTMLElement',
display: `<span class="opacity-30"><</span><span class="text-blue-500">${value.tagName.toLowerCase()}</span><span class="opacity-30">></span>`,
value: namedNodeMapToObject(value.attributes),
actions: [
{
icon: 'input',
tooltip: 'Log element to console',
action: () => {
// eslint-disable-next-line no-console
console.log(value)
},
},
],
},
}
} catch (e) {
return {
_custom: {
type: 'HTMLElement',
display: `<span class="text-blue-500">${String(value)}</span>`,
},
}
}
}
function namedNodeMapToObject (map: NamedNodeMap) {
const result: any = {}
const l = map.length
for (let i = 0; i < l; i++) {
const node = map.item(i)
result[node.name] = node.value
}
return result
}
export function getCustomRefDetails (instance, key, ref) {
let value
if (Array.isArray(ref)) {
value = ref.map((r) => getCustomRefDetails(instance, key, r)).map(data => data.value)
} else {
let name
if (ref._isVue) {
name = getComponentName(ref.$options)
} else {
name = ref.tagName.toLowerCase()
}
value = {
_custom: {
display: `<${name}` +
(ref.id ? ` <span class="attr-title">id</span>="${ref.id}"` : '') +
(ref.className ? ` <span class="attr-title">class</span>="${ref.className}"` : '') + '>',
uid: instance.__VUE_DEVTOOLS_UID__,
type: 'reference',
},
}
}
return {
type: '$refs',
key: key,
value,
editable: false,
}
}
export function parse (data: any, revive = false) {
return revive
? parseCircularAutoChunks(data, reviver)
: parseCircularAutoChunks(data)
}
const specialTypeRE = /^\[native (\w+) (.*?)(<>((.|\s)*))?\]$/
const symbolRE = /^\[native Symbol Symbol\((.*)\)\]$/
function reviver (key, val) {
return revive(val)
}
export function revive (val) {
if (val === UNDEFINED) {
return undefined
} else if (val === INFINITY) {
return Infinity
} else if (val === NEGATIVE_INFINITY) {
return -Infinity
} else if (val === NAN) {
return NaN
} else if (val && val._custom) {
const { _custom: custom }: CustomState = val
if (custom.type === 'component') {
return getInstanceMap().get(custom.id)
} else if (custom.type === 'map') {
return reviveMap(val)
} else if (custom.type === 'set') {
return reviveSet(val)
} else if (custom._reviveId) {
return reviveCache.read(custom._reviveId)
} else {
return revive(custom.value)
}
} else if (symbolRE.test(val)) {
const [, string] = symbolRE.exec(val)
return Symbol.for(string)
} else if (specialTypeRE.test(val)) {
const [, type, string,, details] = specialTypeRE.exec(val)
const result = new window[type](string)
if (type === 'Error' && details) {
result.stack = details
}
return result
} else {
return val
}
}
/**
* Sanitize data to be posted to the other side.
* Since the message posted is sent with structured clone,
* we need to filter out any types that might cause an error.
*
* @param {*} data
* @return {*}
*/
function sanitize (data) {
if (
!isPrimitive(data) &&
!Array.isArray(data) &&
!isPlainObject(data)
) {
// handle types that will probably cause issues in
// the structured clone
return Object.prototype.toString.call(data)
} else {
return data
}
}
export function isPlainObject (obj) {
return Object.prototype.toString.call(obj) === '[object Object]'
}
function isPrimitive (data) {
if (data == null) {
return true
}
const type = typeof data
return (
type === 'string' ||
type === 'number' ||
type === 'boolean'
)
}
/**
* Searches a key or value in the object, with a maximum deepness
* @param {*} obj Search target
* @param {string} searchTerm Search string
* @returns {boolean} Search match
*/
export function searchDeepInObject (obj, searchTerm) {
const seen = new Map()
const result = internalSearchObject(obj, searchTerm.toLowerCase(), seen, 0)
seen.clear()
return result
}
const SEARCH_MAX_DEPTH = 10
/**
* Executes a search on each field of the provided object
* @param {*} obj Search target
* @param {string} searchTerm Search string
* @param {Map<any,boolean>} seen Map containing the search result to prevent stack overflow by walking on the same object multiple times
* @param {number} depth Deep search depth level, which is capped to prevent performance issues
* @returns {boolean} Search match
*/
function internalSearchObject (obj, searchTerm, seen, depth) {
if (depth > SEARCH_MAX_DEPTH) {
return false
}
let match = false
const keys = Object.keys(obj)
let key, value
for (let i = 0; i < keys.length; i++) {
key = keys[i]
value = obj[key]
match = internalSearchCheck(searchTerm, key, value, seen, depth + 1)
if (match) {
break
}
}
return match
}
/**
* Executes a search on each value of the provided array
* @param {*} array Search target
* @param {string} searchTerm Search string
* @param {Map<any,boolean>} seen Map containing the search result to prevent stack overflow by walking on the same object multiple times
* @param {number} depth Deep search depth level, which is capped to prevent performance issues
* @returns {boolean} Search match
*/
function internalSearchArray (array, searchTerm, seen, depth) {
if (depth > SEARCH_MAX_DEPTH) {
return false
}
let match = false
let value
for (let i = 0; i < array.length; i++) {
value = array[i]
match = internalSearchCheck(searchTerm, null, value, seen, depth + 1)
if (match) {
break
}
}
return match
}
/**
* Checks if the provided field matches the search terms
* @param {string} searchTerm Search string
* @param {string} key Field key (null if from array)
* @param {*} value Field value
* @param {Map<any,boolean>} seen Map containing the search result to prevent stack overflow by walking on the same object multiple times
* @param {number} depth Deep search depth level, which is capped to prevent performance issues
* @returns {boolean} Search match
*/
function internalSearchCheck (searchTerm, key, value, seen, depth) {
let match = false
let result
if (key === '_custom') {
key = value.display
value = value.value
}
(result = specialTokenToString(value)) && (value = result)
if (key && compare(key, searchTerm)) {
match = true
seen.set(value, true)
} else if (seen.has(value)) {
match = seen.get(value)
} else if (Array.isArray(value)) {
seen.set(value, null)
match = internalSearchArray(value, searchTerm, seen, depth)
seen.set(value, match)
} else if (isPlainObject(value)) {
seen.set(value, null)
match = internalSearchObject(value, searchTerm, seen, depth)
seen.set(value, match)
} else if (compare(value, searchTerm)) {
match = true
seen.set(value, true)
}
return match
}
/**
* Compares two values
* @param {*} value Mixed type value that will be cast to string
* @param {string} searchTerm Search string
* @returns {boolean} Search match
*/
function compare (value, searchTerm) {
return ('' + value).toLowerCase().indexOf(searchTerm) !== -1
}
export function sortByKey (state) {
return state && state.slice().sort((a, b) => {
if (a.key < b.key) return -1
if (a.key > b.key) return 1
return 0
})
}
export function simpleGet (object, path) {
const sections = Array.isArray(path) ? path : path.split('.')
for (let i = 0; i < sections.length; i++) {
object = object[sections[i]]
if (!object) {
return undefined
}
}
return object
}
export function focusInput (el) {
el.focus()
el.setSelectionRange(0, el.value.length)
}
export function openInEditor (file) {
// Console display
const fileName = file.replace(/\\/g, '\\\\')
const src = `fetch('${SharedData.openInEditorHost}__open-in-editor?file=${encodeURI(file)}').then(response => {
if (response.ok) {
console.log('File ${fileName} opened in editor')
} else {
const msg = 'Opening component ${fileName} failed'
const target = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {}
if (target.__VUE_DEVTOOLS_TOAST__) {
target.__VUE_DEVTOOLS_TOAST__(msg, 'error')
} else {
console.log('%c' + msg, 'color:red')
}
console.log('Check the setup of your project, see https://devtools.vuejs.org/guide/open-in-editor.html')
}
})`
if (isChrome) {
target.chrome.devtools.inspectedWindow.eval(src)
} else {
// eslint-disable-next-line no-eval
eval(src)
}
}
const ESC = {
'<': '<',
'>': '>',
'"': '"',
'&': '&',
}
export function escape (s) {
return s.replace(/[<>"&]/g, escapeChar)
}
function escapeChar (a) {
return ESC[a] || a
}
export function copyToClipboard (state) {
if (typeof document === 'undefined') return
const dummyTextArea = document.createElement('textarea')
dummyTextArea.textContent = stringify(state)
document.body.appendChild(dummyTextArea)
dummyTextArea.select()
document.execCommand('copy')
document.body.removeChild(dummyTextArea)
}
export function isEmptyObject (obj) {
return obj === UNDEFINED || !obj || Object.keys(obj).length === 0
} | the_stack |
import {
differenceWith,
filter,
find,
forEach,
isEmpty,
isEqual,
map,
} from 'lodash';
import { MergedCell } from '../../cell/merged-cell';
import { CellTypes } from '../../common/constant';
import type {
MergedCellInfo,
S2CellType,
TempMergedCell,
ViewMeta,
} from '../../common/interface';
import type { SpreadSheet } from '../../sheet-type';
/**
* according to the coordinates of the starting point of the rectangle,
* return the four sides of the rectangle in a clockwise direction.
* [TopLeft] --- [TopRight]
* | |
* [BottomLeft] -[BottomRight]
* @param x
* @param y
* @param width
* @param height
*/
export const getRectangleEdges = (
x: number,
y: number,
width: number,
height: number,
) => {
const topLeft = [x, y];
const topRight = [x + width, y];
const bottomRight = [x + width, y + height];
const bottomLeft = [x, y + height];
return [
[topLeft, topRight],
[topRight, bottomRight],
[bottomRight, bottomLeft],
[bottomLeft, topLeft],
];
};
/**
* return the edges without overlapping edges
* @param edges the collection of edges
*/
export const unique = (edges: number[][][]) => {
const result: number[][][] = [];
forEach(edges, (edge) => {
const reverseEdge = [edge[1], edge[0]];
if (!JSON.stringify(edges).includes(JSON.stringify(reverseEdge))) {
result.push(edge);
}
});
return result;
};
/**
* return the edge according to the coordinate of current edge
* eg: curEdge: [[0,0], [100,0]] then the next edge: [[100, 0 ], [100, 100]]
* @param curEdge the coordinate of current edge
* @param edges the collection of edges
*/
export const getNextEdge = (
curEdge: number[][],
edges: number[][][],
): number[][] => {
return find(edges, (edge) => isEqual(edge[0], curEdge[1]));
};
/**
* return all the points of the polygon
* @param cells the collection of information of cells which needed be merged
*/
export const getPolygonPoints = (cells: S2CellType[]) => {
let allEdges: number[][][] = [];
cells.forEach((cell) => {
const meta = cell.getMeta();
const { x, y, width, height } = meta;
allEdges = allEdges.concat(getRectangleEdges(x, y, width, height));
});
allEdges = unique(allEdges);
let allPoints: number[][] = [];
const startEdge = allEdges[0];
let curEdge = startEdge;
let nextEdge: number[][] = [];
while (!isEqual(startEdge, nextEdge)) {
allPoints = allPoints.concat(curEdge);
nextEdge = getNextEdge(curEdge, allEdges);
curEdge = nextEdge;
}
return allPoints;
};
/**
* get cells on the outside of visible area through mergeCellInfo
* @param invisibleCellInfo
* @param sheet
*/
export const getInvisibleInfo = (
invisibleCellInfo: MergedCellInfo[],
sheet: SpreadSheet,
) => {
const cells: S2CellType[] = [];
let viewMeta: ViewMeta | undefined;
forEach(invisibleCellInfo, (cellInfo) => {
const meta = sheet?.facet?.layoutResult?.getCellMeta(
cellInfo.rowIndex,
cellInfo.colIndex,
);
if (meta) {
const cell = sheet?.facet?.cfg.dataCell(meta);
viewMeta = cellInfo?.showText ? meta : viewMeta;
cells.push(cell);
}
});
return { cells, cellsMeta: viewMeta };
};
/**
* get { cells, invisibleCellInfo, cellsMeta } in the inside of visible area through mergeCellInfo
* @param cellsInfos
* @param allVisibleCells
* @returns { cells, invisibleCellInfo, cellsMeta }
*/
export const getVisibleInfo = (
cellsInfos: MergedCellInfo[],
allVisibleCells: S2CellType[],
) => {
const cells: S2CellType[] = [];
const invisibleCellInfo: MergedCellInfo[] = [];
let cellsMeta: ViewMeta | Node | undefined;
forEach(cellsInfos, (cellInfo: MergedCellInfo) => {
const findCell = find(allVisibleCells, (cell: S2CellType) => {
const meta = cell?.getMeta?.();
if (
meta?.colIndex === cellInfo?.colIndex &&
meta?.rowIndex === cellInfo?.rowIndex
) {
return cell;
}
}) as S2CellType;
if (findCell) {
cells.push(findCell);
cellsMeta = cellInfo?.showText
? (findCell?.getMeta() as ViewMeta)
: cellsMeta;
} else {
invisibleCellInfo.push(cellInfo);
}
});
return { cells, invisibleCellInfo, cellsMeta };
};
/**
* get the data cell and meta that make up the mergedCell
* @param cellsInfos
* @param allVisibleCells
* @param sheet
*/
export const getTempMergedCell = (
allVisibleCells: S2CellType[],
sheet?: SpreadSheet,
cellsInfos: MergedCellInfo[] = [],
): TempMergedCell => {
const { cellsMeta, cells, invisibleCellInfo } = getVisibleInfo(
cellsInfos,
allVisibleCells,
);
let viewMeta: ViewMeta | Node = cellsMeta;
let mergedAllCells: S2CellType[] = cells;
// some cells are invisible and some cells are visible
const isPartiallyVisible =
invisibleCellInfo?.length > 0 &&
invisibleCellInfo.length < cellsInfos.length;
// 当 MergedCell 只有部分在可视区域时,在此获取 MergedCell 不在可视区域内的 cells
if (isPartiallyVisible) {
const { cells: invisibleCells, cellsMeta: invisibleMeta } =
getInvisibleInfo(invisibleCellInfo, sheet);
viewMeta = viewMeta || invisibleMeta;
mergedAllCells = cells.concat(invisibleCells);
}
if (!isEmpty(cells) && !viewMeta) {
viewMeta = mergedAllCells[0]?.getMeta() as ViewMeta; // 如果没有指定合并后的文本绘制的位置,默认画在选择的第一个单元格内
}
return {
cells: mergedAllCells,
viewMeta: viewMeta as ViewMeta,
isPartiallyVisible,
};
};
/**
* get the active cells' info as the default info of merged cells
* @param sheet
*/
export const getActiveCellsInfo = (sheet: SpreadSheet) => {
const { interaction } = sheet;
const cells = interaction.getActiveCells();
const mergedCellsInfo: MergedCellInfo[] = [];
forEach(cells, (cell, index) => {
const meta = cell.getMeta();
// 在合并单元格中,第一个单元格被标标记为展示数据。
const showText = index === 0 ? { showText: true } : {};
mergedCellsInfo.push({
...showText,
colIndex: meta?.colIndex,
rowIndex: meta?.rowIndex,
});
});
return mergedCellsInfo;
};
/**
* draw the background of the merged cell
* @param sheet the base sheet instance
* @param cellsInfo
* @param hideData
*/
export const mergeCell = (
sheet: SpreadSheet,
cellsInfo?: MergedCellInfo[],
hideData?: boolean,
) => {
const mergeCellInfo = cellsInfo || getActiveCellsInfo(sheet);
if (mergeCellInfo?.length <= 1) {
// eslint-disable-next-line no-console
console.error('then merged cells must be more than one');
return;
}
const allVisibleCells = filter(
sheet.panelScrollGroup.getChildren(),
(child) => !(child instanceof MergedCell),
) as unknown as S2CellType[];
const { cells, viewMeta, isPartiallyVisible } = getTempMergedCell(
allVisibleCells,
sheet,
mergeCellInfo,
);
if (!isEmpty(cells)) {
const mergedCellInfoList = sheet.options?.mergedCellsInfo || [];
mergedCellInfoList.push(mergeCellInfo);
sheet.setOptions({
mergedCellsInfo: mergedCellInfoList,
});
const meta = hideData ? undefined : viewMeta;
sheet.panelScrollGroup.add(
new MergedCell(sheet, cells, meta, isPartiallyVisible),
);
}
};
/**
* remove unmergedCells Info, return new mergedCell info
* @param removeMergedCell
* @param mergedCellsInfo
*/
export const removeUnmergedCellsInfo = (
removeMergedCell: MergedCell,
mergedCellsInfo: MergedCellInfo[][],
): MergedCellInfo[][] => {
const removeCellInfo = map(removeMergedCell.cells, (cell: S2CellType) => {
return {
colIndex: cell.getMeta().colIndex,
rowIndex: cell.getMeta().rowIndex,
};
});
return filter(mergedCellsInfo, (mergedCellInfo) => {
const newMergedCellInfo = mergedCellInfo.map((info) => {
if (info.showText) {
return {
colIndex: info.colIndex,
rowIndex: info.rowIndex,
};
}
return info;
});
return !isEqual(newMergedCellInfo, removeCellInfo);
});
};
/**
* unmerge MergedCell
* @param removedCells
* @param sheet
*/
export const unmergeCell = (sheet: SpreadSheet, removedCells: MergedCell) => {
if (!removedCells || removedCells.cellType !== CellTypes.MERGED_CELL) {
// eslint-disable-next-line no-console
console.error(`unmergeCell: the ${removedCells} is not a MergedCell`);
return;
}
const newMergedCellsInfo = removeUnmergedCellsInfo(
removedCells,
sheet.options?.mergedCellsInfo,
);
if (newMergedCellsInfo?.length !== sheet.options?.mergedCellsInfo?.length) {
sheet.setOptions({
mergedCellsInfo: newMergedCellsInfo,
});
removedCells.remove(true);
}
};
/**
* 合并 TempMergedCell, 通过 cell.viewMeta.id 判断 TempMergedCell 是否是同一个。
* @param TempMergedCells
* @param otherTempMergedCells
*/
export const mergeTempMergedCell = (
TempMergedCells: TempMergedCell[],
otherTempMergedCells: TempMergedCell[],
) => {
const mergedTempMergedCells: Record<string, TempMergedCell> = {};
[...TempMergedCells, ...otherTempMergedCells].forEach((cell) => {
mergedTempMergedCells[cell.viewMeta.id] = cell;
});
return Object.values(mergedTempMergedCells);
};
/**
* 将 MergedCell 转换成 TempMergedCell
* @param oldMergedCells
* @constructor
*/
export const MergedCellConvertTempMergedCells = (
oldMergedCells: MergedCell[],
) => {
return map(oldMergedCells, (mergedCell) => {
return {
cells: mergedCell.cells,
viewMeta: mergedCell.getMeta(),
isPartiallyVisible: mergedCell.isPartiallyVisible,
};
});
};
/**
* 对比两个TempMergedCell,返回 mainTempMergedCells 中存在的,但是 otherTempMergedCells 中不存在的的 TempMergedCell
* 因为 g-base 无法渲染不在可视区域内的图形,所以 isPartiallyVisible 为 true 时也需要重新渲染
* @param mainTempMergedCells
* @param compareTempMergedCells
*/
export const differenceTempMergedCells = (
mainTempMergedCells: TempMergedCell[],
compareTempMergedCells: TempMergedCell[],
): TempMergedCell[] => {
return differenceWith(
mainTempMergedCells,
compareTempMergedCells,
(main, compare) => {
return (
isEqual(main.viewMeta.id, compare.viewMeta.id) &&
!main.isPartiallyVisible
);
},
);
};
/**
* update the mergedCell
* @param sheet the base sheet instance
*/
export const updateMergedCells = (sheet: SpreadSheet) => {
const mergedCellsInfo = sheet.options?.mergedCellsInfo;
if (isEmpty(mergedCellsInfo)) return;
// 可见区域的所有cells
const allCells = filter(
sheet.panelScrollGroup.getChildren(),
(child) => !(child instanceof MergedCell),
) as unknown as S2CellType[];
if (isEmpty(allCells)) return;
// allVisibleTempMergedCells 所有可视区域的 mergedCell
const allVisibleTempMergedCells: TempMergedCell[] = [];
mergedCellsInfo.forEach((cellsInfo: MergedCellInfo[]) => {
const tempMergedCell = getTempMergedCell(allCells, sheet, cellsInfo);
if (tempMergedCell.cells.length > 0) {
allVisibleTempMergedCells.push(tempMergedCell);
}
});
// 获取 oldTempMergedCells 便用后续进行 diff 操作
const oldMergedCells = filter(
sheet.panelScrollGroup.getChildren(),
(child) => child instanceof MergedCell,
) as unknown as MergedCell[];
const oldTempMergedCells: TempMergedCell[] =
MergedCellConvertTempMergedCells(oldMergedCells);
// compare oldTempMergedCells and allTempMergedCells, find remove MergedCells and add MergedCells
const removeTempMergedCells = differenceTempMergedCells(
oldTempMergedCells,
allVisibleTempMergedCells,
);
const addTempMergedCells = differenceTempMergedCells(
allVisibleTempMergedCells,
oldTempMergedCells,
);
// remove old MergedCells
forEach(removeTempMergedCells, (tempMergedCell) => {
const oldMergedCell = find(oldMergedCells, (mergedCell) => {
return isEqual(mergedCell.getMeta().id, tempMergedCell.viewMeta.id);
});
oldMergedCell?.remove(true);
});
// add new MergedCells
forEach(addTempMergedCells, ({ cells, viewMeta, isPartiallyVisible }) => {
sheet.panelScrollGroup.add(
new MergedCell(sheet, cells, viewMeta, isPartiallyVisible),
);
});
}; | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { ResourceGroups } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { ResourceManagementClient } from "../resourceManagementClient";
import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro";
import { LroImpl } from "../lroImpl";
import {
ResourceGroup,
ResourceGroupsListNextOptionalParams,
ResourceGroupsListOptionalParams,
ResourceGroupsCheckExistenceOptionalParams,
ResourceGroupsCheckExistenceResponse,
ResourceGroupsCreateOrUpdateOptionalParams,
ResourceGroupsCreateOrUpdateResponse,
ResourceGroupsDeleteOptionalParams,
ResourceGroupsGetOptionalParams,
ResourceGroupsGetResponse,
ResourceGroupPatchable,
ResourceGroupsUpdateOptionalParams,
ResourceGroupsUpdateResponse,
ExportTemplateRequest,
ResourceGroupsExportTemplateOptionalParams,
ResourceGroupsExportTemplateResponse,
ResourceGroupsListResponse,
ResourceGroupsListNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing ResourceGroups operations. */
export class ResourceGroupsImpl implements ResourceGroups {
private readonly client: ResourceManagementClient;
/**
* Initialize a new instance of the class ResourceGroups class.
* @param client Reference to the service client
*/
constructor(client: ResourceManagementClient) {
this.client = client;
}
/**
* Gets all the resource groups for a subscription.
* @param options The options parameters.
*/
public list(
options?: ResourceGroupsListOptionalParams
): PagedAsyncIterableIterator<ResourceGroup> {
const iter = this.listPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(options);
}
};
}
private async *listPagingPage(
options?: ResourceGroupsListOptionalParams
): AsyncIterableIterator<ResourceGroup[]> {
let result = await this._list(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listPagingAll(
options?: ResourceGroupsListOptionalParams
): AsyncIterableIterator<ResourceGroup> {
for await (const page of this.listPagingPage(options)) {
yield* page;
}
}
/**
* Checks whether a resource group exists.
* @param resourceGroupName The name of the resource group to check. The name is case insensitive.
* @param options The options parameters.
*/
checkExistence(
resourceGroupName: string,
options?: ResourceGroupsCheckExistenceOptionalParams
): Promise<ResourceGroupsCheckExistenceResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
checkExistenceOperationSpec
);
}
/**
* Creates or updates a resource group.
* @param resourceGroupName The name of the resource group to create or update. Can include
* alphanumeric, underscore, parentheses, hyphen, period (except at end), and Unicode characters that
* match the allowed characters.
* @param parameters Parameters supplied to the create or update a resource group.
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
parameters: ResourceGroup,
options?: ResourceGroupsCreateOrUpdateOptionalParams
): Promise<ResourceGroupsCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, parameters, options },
createOrUpdateOperationSpec
);
}
/**
* When you delete a resource group, all of its resources are also deleted. Deleting a resource group
* deletes all of its template deployments and currently stored operations.
* @param resourceGroupName The name of the resource group to delete. The name is case insensitive.
* @param options The options parameters.
*/
async beginDelete(
resourceGroupName: string,
options?: ResourceGroupsDeleteOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<void> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, options },
deleteOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* When you delete a resource group, all of its resources are also deleted. Deleting a resource group
* deletes all of its template deployments and currently stored operations.
* @param resourceGroupName The name of the resource group to delete. The name is case insensitive.
* @param options The options parameters.
*/
async beginDeleteAndWait(
resourceGroupName: string,
options?: ResourceGroupsDeleteOptionalParams
): Promise<void> {
const poller = await this.beginDelete(resourceGroupName, options);
return poller.pollUntilDone();
}
/**
* Gets a resource group.
* @param resourceGroupName The name of the resource group to get. The name is case insensitive.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
options?: ResourceGroupsGetOptionalParams
): Promise<ResourceGroupsGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
getOperationSpec
);
}
/**
* Resource groups can be updated through a simple PATCH operation to a group address. The format of
* the request is the same as that for creating a resource group. If a field is unspecified, the
* current value is retained.
* @param resourceGroupName The name of the resource group to update. The name is case insensitive.
* @param parameters Parameters supplied to update a resource group.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
parameters: ResourceGroupPatchable,
options?: ResourceGroupsUpdateOptionalParams
): Promise<ResourceGroupsUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, parameters, options },
updateOperationSpec
);
}
/**
* Captures the specified resource group as a template.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param parameters Parameters for exporting the template.
* @param options The options parameters.
*/
async beginExportTemplate(
resourceGroupName: string,
parameters: ExportTemplateRequest,
options?: ResourceGroupsExportTemplateOptionalParams
): Promise<
PollerLike<
PollOperationState<ResourceGroupsExportTemplateResponse>,
ResourceGroupsExportTemplateResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<ResourceGroupsExportTemplateResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, parameters, options },
exportTemplateOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs,
lroResourceLocationConfig: "location"
});
}
/**
* Captures the specified resource group as a template.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param parameters Parameters for exporting the template.
* @param options The options parameters.
*/
async beginExportTemplateAndWait(
resourceGroupName: string,
parameters: ExportTemplateRequest,
options?: ResourceGroupsExportTemplateOptionalParams
): Promise<ResourceGroupsExportTemplateResponse> {
const poller = await this.beginExportTemplate(
resourceGroupName,
parameters,
options
);
return poller.pollUntilDone();
}
/**
* Gets all the resource groups for a subscription.
* @param options The options parameters.
*/
private _list(
options?: ResourceGroupsListOptionalParams
): Promise<ResourceGroupsListResponse> {
return this.client.sendOperationRequest({ options }, listOperationSpec);
}
/**
* ListNext
* @param nextLink The nextLink from the previous successful call to the List method.
* @param options The options parameters.
*/
private _listNext(
nextLink: string,
options?: ResourceGroupsListNextOptionalParams
): Promise<ResourceGroupsListNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const checkExistenceOperationSpec: coreClient.OperationSpec = {
path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}",
httpMethod: "HEAD",
responses: {
204: {},
404: {},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.ResourceGroup
},
201: {
bodyMapper: Mappers.ResourceGroup
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.parameters6,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}",
httpMethod: "DELETE",
responses: {
200: {},
201: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion, Parameters.forceDeletionTypes],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ResourceGroup
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.ResourceGroup
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.parameters7,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const exportTemplateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/exportTemplate",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.ResourceGroupExportResult
},
201: {
bodyMapper: Mappers.ResourceGroupExportResult
},
202: {
bodyMapper: Mappers.ResourceGroupExportResult
},
204: {
bodyMapper: Mappers.ResourceGroupExportResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.parameters8,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName1
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listOperationSpec: coreClient.OperationSpec = {
path: "/subscriptions/{subscriptionId}/resourcegroups",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ResourceGroupListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion, Parameters.filter, Parameters.top],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ResourceGroupListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion, Parameters.filter, Parameters.top],
urlParameters: [
Parameters.$host,
Parameters.nextLink,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import MathHelper from './MathHelper';
import ArrayHelper from './ArrayHelper';
import Vector2 from './Vector2';
import Line from './Line';
import Edge from './Edge';
import Atom from './Atom';
import Ring from './Ring';
import RingConnection from './RingConnection';
import CanvasWrapper from './CanvasWrapper';
import Graph from './Graph';
import SSSR from './SSSR';
import ThemeManager from './ThemeManager';
export interface IThemeColols {
C: string,
O: string,
N: string,
F: string,
CL: string,
BR: string,
I: string,
P: string,
S: string,
B: string,
SI: string,
H: string,
BACKGROUND: string
};
export interface ISmilesOptionsDef {
width?: number,
height?: number,
bondThickness?: number,
bondLength?: number,
shortBondLength?: number,
bondSpacing?: number,
dCircle?: number,
atomVisualization?: string,
ringVisualization?: string, //'default', 'circle', 'aromatic'
ringAromaticVisualization?: string, // 'default', 'dashed'
isomeric?: boolean,
debug?: boolean,
terminalCarbons?: boolean,
explicitHydrogens?: boolean,
overlapSensitivity?: number,
overlapResolutionIterations?: number,
compactDrawing?: boolean,
fontSizeLarge?: number,
fontSizeSmall?: number,
padding?: number,
experimentalSSSR?: boolean,
kkThreshold?: number,
kkInnerThreshold?: number,
kkMaxIteration?: number,
kkMaxInnerIteration?: number,
kkMaxEnergy?: number,
themes?: {
dark: IThemeColols,
light: IThemeColols
}
};
export interface IOptions extends ISmilesOptionsDef {
id?: string,
theme?: string,
halfBondSpacing?: number,
bondLengthSq?: number,
halfFontSizeLarge?: number,
quarterFontSizeLarge?: number,
fifthFontSizeSmall?: number,
}
/**
* The main class of the application representing the smiles drawer
*
* @property {Graph} graph The graph associated with this SmilesDrawer.Drawer instance.
* @property {Number} ringIdCounter An internal counter to keep track of ring ids.
* @property {Number} ringConnectionIdCounter An internal counter to keep track of ring connection ids.
* @property {CanvasWrapper} canvasWrapper The CanvasWrapper associated with this SmilesDrawer.Drawer instance.
* @property {Number} totalOverlapScore The current internal total overlap score.
* @property {Object} defaultOptions The default options.
* @property {Object} opts The merged options.
* @property {Object} theme The current theme.
*/
class Drawer {
public graph: any;
public doubleBondConfigCount: any;
public doubleBondConfig: any;
public ringIdCounter: any;
public ringConnectionIdCounter: any;
public canvasWrapper: any;
public totalOverlapScore: any;
public defaultOptions: ISmilesOptionsDef;
public opts: IOptions;
public theme: any;
public infoOnly: any;
public themeManager: any;
public rings: any;
public ringConnections: any;
public bridgedRing: any;
public data: any;
public originalRings: any;
public originalRingConnections: any;
/**
* The constructor for the class SmilesDrawer.
*
* @param {Object} options An object containing custom values for different options. It is merged with the default options.
*/
constructor(options) {
this.graph = null;
this.doubleBondConfigCount = 0;
this.doubleBondConfig = null;
this.ringIdCounter = 0;
this.ringConnectionIdCounter = 0;
this.canvasWrapper = null;
this.totalOverlapScore = 0;
this.defaultOptions = {
width: 500,
height: 500,
bondThickness: 0.6,
bondLength: 15,
shortBondLength: 0.8,
bondSpacing: 0.18 * 15,
dCircle: 2,
atomVisualization: 'default',
ringVisualization: 'default',
ringAromaticVisualization: 'default',
isomeric: true,
debug: false,
terminalCarbons: false,
explicitHydrogens: true,
overlapSensitivity: 0.42,
overlapResolutionIterations: 1,
compactDrawing: false,
fontSizeLarge: 5,
fontSizeSmall: 3,
padding: 5.0,
experimentalSSSR: false,
kkThreshold: 0.1,
kkInnerThreshold: 0.1,
kkMaxIteration: 20000,
kkMaxInnerIteration: 50,
kkMaxEnergy: 1e9,
themes: {
dark: {
C: '#fff',
O: '#e74c3c',
N: '#3498db',
F: '#27ae60',
CL: '#16a085',
BR: '#d35400',
I: '#8e44ad',
P: '#d35400',
S: '#f1c40f',
B: '#e67e22',
SI: '#e67e22',
H: '#fff',
BACKGROUND: '#141414'
},
light: {
C: '#222',
O: '#e74c3c',
N: '#3498db',
F: '#27ae60',
CL: '#16a085',
BR: '#d35400',
I: '#8e44ad',
P: '#d35400',
S: '#f1c40f',
B: '#e67e22',
SI: '#e67e22',
H: '#222',
BACKGROUND: '#fff'
}
}
};
// @ts-ignore
this.opts = this.extend(true, this.defaultOptions, options);
this.opts.halfBondSpacing = this.opts.bondSpacing / 2.0;
this.opts.bondLengthSq = this.opts.bondLength * this.opts.bondLength;
this.opts.halfFontSizeLarge = this.opts.fontSizeLarge / 2.0;
this.opts.quarterFontSizeLarge = this.opts.fontSizeLarge / 4.0;
this.opts.fifthFontSizeSmall = this.opts.fontSizeSmall / 5.0;
// Set the default theme.
this.theme = this.opts.themes.dark;
}
/**
* A helper method to extend the default options with user supplied ones.
*/
extend() {
let that = this;
let extended = {};
let deep = false;
let i = 0;
let length = arguments.length;
if (Object.prototype.toString.call(arguments[0]) === '[object Boolean]') {
deep = arguments[0];
i++;
}
let merge = function (obj) {
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
if (deep && Object.prototype.toString.call(obj[prop]) === '[object Object]') {
// @ts-ignore
extended[prop] = that.extend(true, extended[prop], obj[prop]);
// extended[prop] = that.extend();
} else {
extended[prop] = obj[prop];
}
}
}
};
for (; i < length; i++) {
let obj = arguments[i];
merge(obj);
}
return extended;
};
/**
* Draws the parsed smiles data to a canvas element.
*
* @param {Object} data The tree returned by the smiles parser.
* @param {(String|HTMLElement)} target The id of the HTML canvas element the structure is drawn to - or the element itself.
* @param {String} themeName='dark' The name of the theme to use. Built-in themes are 'light' and 'dark'.
* @param {Boolean} infoOnly=false Only output info on the molecule without drawing anything to the canvas.
*/
draw(data, target, themeName = 'light', infoOnly = false) {
this.initDraw(data, themeName, infoOnly);
if (!this.infoOnly) {
this.themeManager = new ThemeManager(this.opts.themes, themeName);
this.canvasWrapper = new CanvasWrapper(target, this.themeManager, this.opts);
}
if (!infoOnly) {
this.processGraph();
// Set the canvas to the appropriate size
this.canvasWrapper.scale(this.graph.vertices);
// Do the actual drawing
this.drawEdges(this.opts.debug);
this.drawVertices(this.opts.debug);
this.canvasWrapper.reset();
if (this.opts.debug) {
console.log(this.graph);
console.log(this.rings);
console.log(this.ringConnections);
}
}
}
/**
* Returns the number of rings this edge is a part of.
*
* @param {Number} edgeId The id of an edge.
* @returns {Number} The number of rings the provided edge is part of.
*/
edgeRingCount(edgeId) {
let edge = this.graph.edges[edgeId];
let a = this.graph.vertices[edge.sourceId];
let b = this.graph.vertices[edge.targetId];
return Math.min(a.value.rings.length, b.value.rings.length);
}
/**
* Returns an array containing the bridged rings associated with this molecule.
*
* @returns {Ring[]} An array containing all bridged rings associated with this molecule.
*/
getBridgedRings() {
let bridgedRings = Array();
for (var i = 0; i < this.rings.length; i++) {
if (this.rings[i].isBridged) {
bridgedRings.push(this.rings[i]);
}
}
return bridgedRings;
}
/**
* Returns an array containing all fused rings associated with this molecule.
*
* @returns {Ring[]} An array containing all fused rings associated with this molecule.
*/
getFusedRings() {
let fusedRings = Array();
for (var i = 0; i < this.rings.length; i++) {
if (this.rings[i].isFused) {
fusedRings.push(this.rings[i]);
}
}
return fusedRings;
}
/**
* Returns an array containing all spiros associated with this molecule.
*
* @returns {Ring[]} An array containing all spiros associated with this molecule.
*/
getSpiros() {
let spiros = Array();
for (var i = 0; i < this.rings.length; i++) {
if (this.rings[i].isSpiro) {
spiros.push(this.rings[i]);
}
}
return spiros;
}
/**
* Returns a string containing a semicolon and new-line separated list of ring properties: Id; Members Count; Neighbours Count; IsSpiro; IsFused; IsBridged; Ring Count (subrings of bridged rings)
*
* @returns {String} A string as described in the method description.
*/
printRingInfo() {
let result = '';
for (var i = 0; i < this.rings.length; i++) {
const ring = this.rings[i];
result += ring.id + ';';
result += ring.members.length + ';';
result += ring.neighbours.length + ';';
result += ring.isSpiro ? 'true;' : 'false;'
result += ring.isFused ? 'true;' : 'false;'
result += ring.isBridged ? 'true;' : 'false;'
result += ring.rings.length + ';';
result += '\n';
}
return result;
}
/**
* Rotates the drawing to make the widest dimension horizontal.
*/
rotateDrawing() {
// Rotate the vertices to make the molecule align horizontally
// Find the longest distance
let a = 0;
let b = 0;
let maxDist = 0;
for (var i = 0; i < this.graph.vertices.length; i++) {
let vertexA = this.graph.vertices[i];
if (!vertexA.value.isDrawn) {
continue;
}
for (var j = i + 1; j < this.graph.vertices.length; j++) {
let vertexB = this.graph.vertices[j];
if (!vertexB.value.isDrawn) {
continue;
}
let dist = vertexA.position.distanceSq(vertexB.position);
if (dist > maxDist) {
maxDist = dist;
a = i;
b = j;
}
}
}
let angle = -Vector2.subtract(this.graph.vertices[a].position, this.graph.vertices[b].position).angle();
if (!isNaN(angle)) {
// Round to 30 degrees
let remainder = angle % 0.523599;
// Round either up or down in 30 degree steps
if (remainder < 0.2617995) {
angle = angle - remainder;
} else {
angle += 0.523599 - remainder;
}
// Finally, rotate everything
for (var i = 0; i < this.graph.vertices.length; i++) {
if (i === b) {
continue;
}
this.graph.vertices[i].position.rotateAround(angle, this.graph.vertices[b].position);
}
for (var i = 0; i < this.rings.length; i++) {
this.rings[i].center.rotateAround(angle, this.graph.vertices[b].position);
}
}
}
/**
* Returns the total overlap score of the current molecule.
*
* @returns {Number} The overlap score.
*/
getTotalOverlapScore() {
return this.totalOverlapScore;
}
/**
* Returns the ring count of the current molecule.
*
* @returns {Number} The ring count.
*/
getRingCount() {
return this.rings.length;
}
/**
* Checks whether or not the current molecule a bridged ring.
*
* @returns {Boolean} A boolean indicating whether or not the current molecule a bridged ring.
*/
hasBridgedRing() {
return this.bridgedRing;
}
/**
* Returns the number of heavy atoms (non-hydrogen) in the current molecule.
*
* @returns {Number} The heavy atom count.
*/
getHeavyAtomCount() {
let hac = 0;
for (var i = 0; i < this.graph.vertices.length; i++) {
if (this.graph.vertices[i].value.element !== 'H') {
hac++;
}
}
return hac;
}
/**
* Returns the molecular formula of the loaded molecule as a string.
*
* @returns {String} The molecular formula.
*/
getMolecularFormula() {
let molecularFormula = '';
let counts = new Map();
// Initialize element count
for (var i = 0; i < this.graph.vertices.length; i++) {
let atom = this.graph.vertices[i].value;
if (counts.has(atom.element)) {
counts.set(atom.element, counts.get(atom.element) + 1);
} else {
counts.set(atom.element, 1);
}
// Hydrogens attached to a chiral center were added as vertices,
// those in non chiral brackets are added here
if (atom.bracket && !atom.bracket.chirality) {
if (counts.has('H')) {
counts.set('H', counts.get('H') + atom.bracket.hcount);
} else {
counts.set('H', atom.bracket.hcount);
}
}
// Add the implicit hydrogens according to valency, exclude
// bracket atoms as they were handled and always have the number
// of hydrogens specified explicitly
if (!atom.bracket) {
let nHydrogens = Atom.maxBonds[atom.element] - atom.bondCount;
if (atom.isPartOfAromaticRing) {
nHydrogens--;
}
if (counts.has('H')) {
counts.set('H', counts.get('H') + nHydrogens);
} else {
counts.set('H', nHydrogens);
}
}
}
if (counts.has('C')) {
let count = counts.get('C');
molecularFormula += 'C' + (count > 1 ? count : '');
counts.delete('C');
}
if (counts.has('H')) {
let count = counts.get('H');
molecularFormula += 'H' + (count > 1 ? count : '');
counts.delete('H');
}
let elements = Object.keys(Atom.atomicNumbers).sort();
elements.map(e => {
if (counts.has(e)) {
let count = counts.get(e);
molecularFormula += e + (count > 1 ? count : '');
}
});
return molecularFormula;
}
/**
* Returns the type of the ringbond (e.g. '=' for a double bond). The ringbond represents the break in a ring introduced when creating the MST. If the two vertices supplied as arguments are not part of a common ringbond, the method returns null.
*
* @param {Vertex} vertexA A vertex.
* @param {Vertex} vertexB A vertex.
* @returns {(String|null)} Returns the ringbond type or null, if the two supplied vertices are not connected by a ringbond.
*/
getRingbondType(vertexA, vertexB) {
// Checks whether the two vertices are the ones connecting the ring
// and what the bond type should be.
if (vertexA.value.getRingbondCount() < 1 || vertexB.value.getRingbondCount() < 1) {
return null;
}
for (var i = 0; i < vertexA.value.ringbonds.length; i++) {
for (var j = 0; j < vertexB.value.ringbonds.length; j++) {
// if(i != j) continue;
if (vertexA.value.ringbonds[i].id === vertexB.value.ringbonds[j].id) {
// If the bonds are equal, it doesn't matter which bond is returned.
// if they are not equal, return the one that is not the default ("-")
if (vertexA.value.ringbonds[i]?.bondType === '-') {
return vertexB.value.ringbonds[j].bond;
} else {
return vertexA.value.ringbonds[i].bond;
}
}
}
}
return null;
}
initDraw(data, themeName, infoOnly) {
this.data = data;
this.infoOnly = infoOnly;
this.ringIdCounter = 0;
this.ringConnectionIdCounter = 0;
this.graph = new Graph(data, this.opts.isomeric);
this.rings = Array();
this.ringConnections = Array();
this.originalRings = Array();
this.originalRingConnections = Array();
this.bridgedRing = false;
// Reset those, in case the previous drawn SMILES had a dangling \ or /
this.doubleBondConfigCount = null;
this.doubleBondConfig = null;
this.initRings();
this.initHydrogens();
}
processGraph() {
this.position();
// Restore the ring information (removes bridged rings and replaces them with the original, multiple, rings)
this.restoreRingInformation();
// Atoms bonded to the same ring atom
this.resolvePrimaryOverlaps();
let overlapScore = this.getOverlapScore();
this.totalOverlapScore = this.getOverlapScore().total;
for (var o = 0; o < this.opts.overlapResolutionIterations; o++) {
for (var i = 0; i < this.graph.edges.length; i++) {
let edge = this.graph.edges[i];
if (this.isEdgeRotatable(edge)) {
let subTreeDepthA = this.graph.getTreeDepth(edge.sourceId, edge.targetId);
let subTreeDepthB = this.graph.getTreeDepth(edge.targetId, edge.sourceId);
// Only rotate the shorter subtree
let a = edge.targetId;
let b = edge.sourceId;
if (subTreeDepthA > subTreeDepthB) {
a = edge.sourceId;
b = edge.targetId;
}
let subTreeOverlap = this.getSubtreeOverlapScore(b, a, overlapScore.vertexScores);
if (subTreeOverlap.value > this.opts.overlapSensitivity) {
let vertexA = this.graph.vertices[a];
let vertexB = this.graph.vertices[b];
let neighboursB = vertexB.getNeighbours(a);
if (neighboursB.length === 1) {
let neighbour = this.graph.vertices[neighboursB[0]];
let angle = neighbour.position.getRotateAwayFromAngle(vertexA.position, vertexB.position, MathHelper.toRad(120));
this.rotateSubtree(neighbour.id, vertexB.id, angle, vertexB.position);
// If the new overlap is bigger, undo change
let newTotalOverlapScore = this.getOverlapScore().total;
if (newTotalOverlapScore > this.totalOverlapScore) {
this.rotateSubtree(neighbour.id, vertexB.id, -angle, vertexB.position);
} else {
this.totalOverlapScore = newTotalOverlapScore;
}
} else if (neighboursB.length === 2) {
// Switch places / sides
// If vertex a is in a ring, do nothing
if (vertexB.value.rings.length !== 0 && vertexA.value.rings.length !== 0) {
continue;
}
let neighbourA = this.graph.vertices[neighboursB[0]];
let neighbourB = this.graph.vertices[neighboursB[1]];
if (neighbourA.value.rings.length === 1 && neighbourB.value.rings.length === 1) {
// Both neighbours in same ring. TODO: does this create problems with wedges? (up = down and vice versa?)
if (neighbourA.value.rings[0] !== neighbourB.value.rings[0]) {
continue;
}
// TODO: Rotate circle
} else if (neighbourA.value.rings.length !== 0 || neighbourB.value.rings.length !== 0) {
continue;
} else {
let angleA = neighbourA.position.getRotateAwayFromAngle(vertexA.position, vertexB.position, MathHelper.toRad(120));
let angleB = neighbourB.position.getRotateAwayFromAngle(vertexA.position, vertexB.position, MathHelper.toRad(120));
this.rotateSubtree(neighbourA.id, vertexB.id, angleA, vertexB.position);
this.rotateSubtree(neighbourB.id, vertexB.id, angleB, vertexB.position);
let newTotalOverlapScore = this.getOverlapScore().total;
if (newTotalOverlapScore > this.totalOverlapScore) {
this.rotateSubtree(neighbourA.id, vertexB.id, -angleA, vertexB.position);
this.rotateSubtree(neighbourB.id, vertexB.id, -angleB, vertexB.position);
} else {
this.totalOverlapScore = newTotalOverlapScore;
}
}
}
overlapScore = this.getOverlapScore();
}
}
}
}
this.resolveSecondaryOverlaps(overlapScore.scores);
if (this.opts.isomeric) {
this.annotateStereochemistry();
}
// Initialize pseudo elements or shortcuts
if (this.opts.compactDrawing && this.opts.atomVisualization === 'default') {
this.initPseudoElements();
} else {
if (this.opts.atomVisualization === 'default') {
this.initPseudoElements();
}
}
this.rotateDrawing();
}
/**
* Initializes rings and ringbonds for the current molecule.
*/
initRings() {
let openBonds = new Map();
// Close the open ring bonds (spanning tree -> graph)
for (var i = this.graph.vertices.length - 1; i >= 0; i--) {
let vertex = this.graph.vertices[i];
if (vertex.value.ringbonds.length === 0) {
continue;
}
for (var j = 0; j < vertex.value.ringbonds.length; j++) {
let ringbondId = vertex.value.ringbonds[j].id;
let ringbondBond = vertex.value.ringbonds[j].bond;
// If the other ringbond id has not been discovered,
// add it to the open bonds map and continue.
// if the other ringbond id has already been discovered,
// create a bond between the two atoms.
if (!openBonds.has(ringbondId)) {
openBonds.set(ringbondId, [vertex.id, ringbondBond]);
} else {
let sourceVertexId = vertex.id;
let targetVertexId = openBonds.get(ringbondId)[0];
let targetRingbondBond = openBonds.get(ringbondId)[1];
let edge = new Edge(sourceVertexId, targetVertexId, 1);
edge.setBondType(targetRingbondBond || ringbondBond || '-');
let edgeId = this.graph.addEdge(edge);
let targetVertex = this.graph.vertices[targetVertexId];
vertex.addRingbondChild(targetVertexId, j);
vertex.value.addNeighbouringElement(targetVertex.value.element);
targetVertex.addRingbondChild(sourceVertexId, j);
targetVertex.value.addNeighbouringElement(vertex.value.element);
vertex.edges.push(edgeId);
targetVertex.edges.push(edgeId);
openBonds.delete(ringbondId);
}
}
}
// Get the rings in the graph (the SSSR)
let rings = SSSR.getRings(this.graph, this.opts.experimentalSSSR);
if (rings === null) {
return;
}
for (var i = 0; i < rings.length; i++) {
let ringVertices = [...rings[i]];
let ringId = this.addRing(new Ring(ringVertices));
// Add the ring to the atoms
for (var j = 0; j < ringVertices.length; j++) {
this.graph.vertices[ringVertices[j]].value.rings.push(ringId);
}
}
// Find connection between rings
// Check for common vertices and create ring connections. This is a bit
// ugly, but the ringcount is always fairly low (< 100)
for (var i = 0; i < this.rings.length - 1; i++) {
for (var j = i + 1; j < this.rings.length; j++) {
let a = this.rings[i];
let b = this.rings[j];
let ringConnection = new RingConnection(a, b);
// If there are no vertices in the ring connection, then there
// is no ring connection
if (ringConnection.vertices.size > 0) {
this.addRingConnection(ringConnection);
}
}
}
// Add neighbours to the rings
for (var i = 0; i < this.rings.length; i++) {
let ring = this.rings[i];
ring.neighbours = RingConnection.getNeighbours(this.ringConnections, ring.id);
}
// Anchor the ring to one of it's members, so that the ring center will always
// be tied to a single vertex when doing repositionings
for (var i = 0; i < this.rings.length; i++) {
let ring = this.rings[i];
this.graph.vertices[ring.members[0]].value.addAnchoredRing(ring.id);
}
// Backup the ring information to restore after placing the bridged ring.
// This is needed in order to identify aromatic rings and stuff like this in
// rings that are member of the superring.
this.backupRingInformation();
// Replace rings contained by a larger bridged ring with a bridged ring
while (this.rings.length > 0) {
let id = -1;
for (var i = 0; i < this.rings.length; i++) {
let ring = this.rings[i];
if (this.isPartOfBridgedRing(ring.id) && !ring.isBridged) {
id = ring.id;
}
}
if (id === -1) {
break;
}
let ring = this.getRing(id);
let involvedRings = this.getBridgedRingRings(ring.id);
this.bridgedRing = true;
this.createBridgedRing(involvedRings, ring.members[0]);
// Remove the rings
for (var i = 0; i < involvedRings.length; i++) {
this.removeRing(involvedRings[i]);
}
}
}
initHydrogens() {
// Do not draw hydrogens except when they are connected to a stereocenter connected to two or more rings.
if (!this.opts.explicitHydrogens) {
for (var i = 0; i < this.graph.vertices.length; i++) {
let vertex = this.graph.vertices[i];
if (vertex.value.element !== 'H') {
continue;
}
// Hydrogens should have only one neighbour, so just take the first
// Also set hasHydrogen true on connected atom
let neighbour = this.graph.vertices[vertex.neighbours[0]];
neighbour.value.hasHydrogen = true;
if (!neighbour.value.isStereoCenter || neighbour.value.rings.length < 2 && !neighbour.value.bridgedRing ||
neighbour.value.bridgedRing && neighbour.value.originalRings.length < 2) {
vertex.value.isDrawn = false;
}
}
}
}
/**
* Returns all rings connected by bridged bonds starting from the ring with the supplied ring id.
*
* @param {Number} ringId A ring id.
* @returns {Number[]} An array containing all ring ids of rings part of a bridged ring system.
*/
getBridgedRingRings(ringId) {
let involvedRings = Array();
let that = this;
let recurse = function (r) {
let ring = that.getRing(r);
involvedRings.push(r);
for (var i = 0; i < ring.neighbours.length; i++) {
let n = ring.neighbours[i];
if (involvedRings.indexOf(n) === -1 &&
n !== r &&
RingConnection.isBridge(that.ringConnections, that.graph.vertices, r, n)) {
recurse(n);
}
}
};
recurse(ringId);
return ArrayHelper.unique(involvedRings);
}
/**
* Checks whether or not a ring is part of a bridged ring.
*
* @param {Number} ringId A ring id.
* @returns {Boolean} A boolean indicating whether or not the supplied ring (by id) is part of a bridged ring system.
*/
isPartOfBridgedRing(ringId) {
for (var i = 0; i < this.ringConnections.length; i++) {
if (this.ringConnections[i].containsRing(ringId) &&
this.ringConnections[i].isBridge(this.graph.vertices)) {
return true;
}
}
return false;
}
/**
* Creates a bridged ring.
*
* @param {Number[]} ringIds An array of ids of rings involved in the bridged ring.
* @param {Number} sourceVertexId The vertex id to start the bridged ring discovery from.
* @returns {Ring} The bridged ring.
*/
createBridgedRing(ringIds, sourceVertexId) {
let ringMembers: any = new Set();
let vertices: any = new Set();
let neighbours: any = new Set();
for (var i = 0; i < ringIds.length; i++) {
let ring = this.getRing(ringIds[i]);
ring.isPartOfBridged = true;
for (var j = 0; j < ring.members.length; j++) {
vertices.add(ring.members[j]);
}
for (var j = 0; j < ring.neighbours.length; j++) {
let id = ring.neighbours[j];
if (ringIds.indexOf(id) === -1) {
neighbours.add(ring.neighbours[j]);
}
}
}
// A vertex is part of the bridged ring if it only belongs to
// one of the rings (or to another ring
// which is not part of the bridged ring).
let leftovers: any = new Set();
for (let id of vertices) {
let vertex = this.graph.vertices[id];
let intersection = ArrayHelper.intersection(ringIds, vertex.value.rings);
if (vertex.value.rings.length === 1 || intersection.length === 1) {
ringMembers.add(vertex.id);
} else {
leftovers.add(vertex.id);
}
}
// Vertices can also be part of multiple rings and lay on the bridged ring,
// however, they have to have at least two neighbours that are not part of
// two rings
// let tmp = Array();
let insideRing = Array();
for (let id of leftovers) {
let vertex = this.graph.vertices[id];
let onRing = false;
for (let j = 0; j < vertex.edges.length; j++) {
if (this.edgeRingCount(vertex.edges[j]) === 1) {
onRing = true;
}
}
if (onRing) {
vertex.value.isBridgeNode = true;
ringMembers.add(vertex.id);
} else {
vertex.value.isBridge = true;
ringMembers.add(vertex.id);
}
}
// Create the ring
let ring = new Ring([...ringMembers]);
this.addRing(ring);
ring.isBridged = true;
ring.neighbours = [...neighbours];
for (var i = 0; i < ringIds.length; i++) {
ring.rings.push(this.getRing(ringIds[i]).clone());
}
for (var i = 0; i < ring.members.length; i++) {
this.graph.vertices[ring.members[i]].value.bridgedRing = ring.id;
}
// Atoms inside the ring are no longer part of a ring but are now
// associated with the bridged ring
for (var i = 0; i < insideRing.length; i++) {
let vertex = this.graph.vertices[insideRing[i]];
vertex.value.rings = Array();
}
// Remove former rings from members of the bridged ring and add the bridged ring
for (let id of ringMembers) {
let vertex = this.graph.vertices[id];
vertex.value.rings = ArrayHelper.removeAll(vertex.value.rings, ringIds);
vertex.value.rings.push(ring.id);
}
// Remove all the ring connections no longer used
for (var i = 0; i < ringIds.length; i++) {
for (var j = i + 1; j < ringIds.length; j++) {
this.removeRingConnectionsBetween(ringIds[i], ringIds[j]);
}
}
// Update the ring connections and add this ring to the neighbours neighbours
for (let id of neighbours) {
let connections = this.getRingConnections(id, ringIds);
for (var j = 0; j < connections.length; j++) {
this.getRingConnection(connections[j]).updateOther(ring.id, id);
}
this.getRing(id).neighbours.push(ring.id);
}
return ring;
}
/**
* Checks whether or not two vertices are in the same ring.
*
* @param {Vertex} vertexA A vertex.
* @param {Vertex} vertexB A vertex.
* @returns {Boolean} A boolean indicating whether or not the two vertices are in the same ring.
*/
areVerticesInSameRing(vertexA, vertexB) {
// This is a little bit lighter (without the array and push) than
// getCommonRings().length > 0
for (var i = 0; i < vertexA.value.rings.length; i++) {
for (var j = 0; j < vertexB.value.rings.length; j++) {
if (vertexA.value.rings[i] === vertexB.value.rings[j]) {
return true;
}
}
}
return false;
}
/**
* Returns an array of ring ids shared by both vertices.
*
* @param {Vertex} vertexA A vertex.
* @param {Vertex} vertexB A vertex.
* @returns {Number[]} An array of ids of rings shared by the two vertices.
*/
getCommonRings(vertexA, vertexB) {
let commonRings = Array();
for (var i = 0; i < vertexA.value.rings.length; i++) {
for (var j = 0; j < vertexB.value.rings.length; j++) {
if (vertexA.value.rings[i] == vertexB.value.rings[j]) {
commonRings.push(vertexA.value.rings[i]);
}
}
}
return commonRings;
}
/**
* Returns the aromatic or largest ring shared by the two vertices.
*
* @param {Vertex} vertexA A vertex.
* @param {Vertex} vertexB A vertex.
* @returns {(Ring|null)} If an aromatic common ring exists, that ring, else the largest (non-aromatic) ring, else null.
*/
getLargestOrAromaticCommonRing(vertexA, vertexB) {
let commonRings = this.getCommonRings(vertexA, vertexB);
let maxSize = 0;
let largestCommonRing = null;
if (commonRings.length === 1) {
return this.getRing(commonRings[0]);
}
for (var i = 0; i < commonRings.length; i++) {
let ring = this.getRing(commonRings[i]);
let size = ring.getSize();
// if (ring.elements.indexOf('S') !== -1) {
// return ring;
// }
if (ring.isBenzeneLike(this.graph.vertices)) {
return ring;
} else {
if (size > maxSize) {
//NEED TO FIX
// if (( ring.edges.length < 1) //&& !ring.isHaveElements
// // && maxSize > 0
// ) {
// continue;
// }
if ( maxSize > 0) {
if (largestCommonRing.members.length === 5
&& largestCommonRing.elements.indexOf('S') !== -1
&& largestCommonRing.neighbours.length === 1
&& ring.edges.length < 1) {
continue;
}
if (largestCommonRing.members.length === 6
&& largestCommonRing.edges.length < 1 && ring.edges.length < 1
&& largestCommonRing.hasDoubleBondWithO
) {
continue;
}
}
maxSize = size;
largestCommonRing = ring;
} else {
if ( size === maxSize
// && size === 6
) {
if (largestCommonRing.elements.indexOf('O') !== -1) {
largestCommonRing = ring;
continue;
}
if (largestCommonRing.hasDoubleBondWithO && !ring.hasDoubleBondWithO) {
largestCommonRing = ring
} else {
if ( !ring.hasDoubleBondWithO &&
size === 6 &&
largestCommonRing.edges.length < 1 && ring.edges.length > 1){
largestCommonRing = ring;
}
}
}
}
}
}
return largestCommonRing;
}
/**
* Returns an array of vertices positioned at a specified location.
*
* @param {Vector2} position The position to search for vertices.
* @param {Number} radius The radius within to search.
* @param {Number} excludeVertexId A vertex id to be excluded from the search results.
* @returns {Number[]} An array containing vertex ids in a given location.
*/
getVerticesAt(position, radius, excludeVertexId) {
let locals = Array();
for (var i = 0; i < this.graph.vertices.length; i++) {
let vertex = this.graph.vertices[i];
if (vertex.id === excludeVertexId || !vertex.positioned) {
continue;
}
let distance = position.distanceSq(vertex.position);
if (distance <= radius * radius) {
locals.push(vertex.id);
}
}
return locals;
}
/**
* Returns the closest vertex (connected as well as unconnected).
*
* @param {Vertex} vertex The vertex of which to find the closest other vertex.
* @returns {Vertex} The closest vertex.
*/
getClosestVertex(vertex) {
let minDist = 99999;
let minVertex = null;
for (var i = 0; i < this.graph.vertices.length; i++) {
let v = this.graph.vertices[i];
if (v.id === vertex.id) {
continue;
}
let distSq = vertex.position.distanceSq(v.position);
if (distSq < minDist) {
minDist = distSq;
minVertex = v;
}
}
return minVertex;
}
/**
* Add a ring to this representation of a molecule.
*
* @param {Ring} ring A new ring.
* @returns {Number} The ring id of the new ring.
*/
addRing(ring) {
ring.id = this.ringIdCounter++;
this.rings.push(ring);
return ring.id;
}
/**
* Removes a ring from the array of rings associated with the current molecule.
*
* @param {Number} ringId A ring id.
*/
removeRing(ringId) {
this.rings = this.rings.filter(function (item) {
return item.id !== ringId;
});
// Also remove ring connections involving this ring
this.ringConnections = this.ringConnections.filter(function (item) {
return item.firstRingId !== ringId && item.secondRingId !== ringId;
});
// Remove the ring as neighbour of other rings
for (var i = 0; i < this.rings.length; i++) {
let r = this.rings[i];
r.neighbours = r.neighbours.filter(function (item) {
return item !== ringId;
});
}
}
/**
* Gets a ring object from the array of rings associated with the current molecule by its id. The ring id is not equal to the index, since rings can be added and removed when processing bridged rings.
*
* @param {Number} ringId A ring id.
* @returns {Ring} A ring associated with the current molecule.
*/
getRing(ringId) {
for (var i = 0; i < this.rings.length; i++) {
if (this.rings[i].id == ringId) {
return this.rings[i];
}
}
}
/**
* Add a ring connection to this representation of a molecule.
*
* @param {RingConnection} ringConnection A new ringConnection.
* @returns {Number} The ring connection id of the new ring connection.
*/
addRingConnection(ringConnection) {
ringConnection.id = this.ringConnectionIdCounter++;
this.ringConnections.push(ringConnection);
return ringConnection.id;
}
/**
* Removes a ring connection from the array of rings connections associated with the current molecule.
*
* @param {Number} ringConnectionId A ring connection id.
*/
removeRingConnection(ringConnectionId) {
this.ringConnections = this.ringConnections.filter(function (item) {
return item.id !== ringConnectionId;
});
}
/**
* Removes all ring connections between two vertices.
*
* @param {Number} vertexIdA A vertex id.
* @param {Number} vertexIdB A vertex id.
*/
removeRingConnectionsBetween(vertexIdA, vertexIdB) {
let toRemove = Array();
for (var i = 0; i < this.ringConnections.length; i++) {
let ringConnection = this.ringConnections[i];
if (ringConnection.firstRingId === vertexIdA && ringConnection.secondRingId === vertexIdB ||
ringConnection.firstRingId === vertexIdB && ringConnection.secondRingId === vertexIdA) {
toRemove.push(ringConnection.id);
}
}
for (var i = 0; i < toRemove.length; i++) {
this.removeRingConnection(toRemove[i]);
}
}
/**
* Get a ring connection with a given id.
*
* @param {Number} id
* @returns {RingConnection} The ring connection with the specified id.
*/
getRingConnection(id) {
for (var i = 0; i < this.ringConnections.length; i++) {
if (this.ringConnections[i].id == id) {
return this.ringConnections[i];
}
}
}
/**
* Get the ring connections between a ring and a set of rings.
*
* @param {Number} ringId A ring id.
* @param {Number[]} ringIds An array of ring ids.
* @returns {Number[]} An array of ring connection ids.
*/
getRingConnections(ringId, ringIds) {
let ringConnections = Array();
for (var i = 0; i < this.ringConnections.length; i++) {
let rc = this.ringConnections[i];
for (var j = 0; j < ringIds.length; j++) {
let id = ringIds[j];
if (rc.firstRingId === ringId && rc.secondRingId === id ||
rc.firstRingId === id && rc.secondRingId === ringId) {
ringConnections.push(rc.id);
}
}
}
return ringConnections;
}
/**
* Returns the overlap score of the current molecule based on its positioned vertices. The higher the score, the more overlaps occur in the structure drawing.
*
* @returns {Object} Returns the total overlap score and the overlap score of each vertex sorted by score (higher to lower). Example: { total: 99, scores: [ { id: 0, score: 22 }, ... ] }
*/
getOverlapScore() {
let total = 0.0;
let overlapScores = new Float32Array(this.graph.vertices.length);
for (var i = 0; i < this.graph.vertices.length; i++) {
overlapScores[i] = 0;
}
for (var i = 0; i < this.graph.vertices.length; i++) {
var j = this.graph.vertices.length;
while (--j > i) {
let a = this.graph.vertices[i];
let b = this.graph.vertices[j];
if (!a.value.isDrawn || !b.value.isDrawn) {
continue;
}
let dist = Vector2.subtract(a.position, b.position).lengthSq();
if (dist < this.opts.bondLengthSq) {
let weighted = (this.opts.bondLength - Math.sqrt(dist)) / this.opts.bondLength;
total += weighted;
overlapScores[i] += weighted;
overlapScores[j] += weighted;
}
}
}
let sortable = Array();
for (var i = 0; i < this.graph.vertices.length; i++) {
sortable.push({
id: i,
score: overlapScores[i]
});
}
sortable.sort(function (a, b) {
return b.score - a.score;
});
return {
total: total,
scores: sortable,
vertexScores: overlapScores
};
}
/**
* When drawing a double bond, choose the side to place the double bond. E.g. a double bond should always been drawn inside a ring.
*
* @param {Vertex} vertexA A vertex.
* @param {Vertex} vertexB A vertex.
* @param {Vector2[]} sides An array containing the two normals of the line spanned by the two provided vertices.
* @returns {Object} Returns an object containing the following information: {
totalSideCount: Counts the sides of each vertex in the molecule, is an array [ a, b ],
totalPosition: Same as position, but based on entire molecule,
sideCount: Counts the sides of each neighbour, is an array [ a, b ],
position: which side to position the second bond, is 0 or 1, represents the index in the normal array. This is based on only the neighbours
anCount: the number of neighbours of vertexA,
bnCount: the number of neighbours of vertexB
}
*/
chooseSide(vertexA, vertexB, sides) {
// Check which side has more vertices
// Get all the vertices connected to the both ends
let an = vertexA.getNeighbours(vertexB.id);
let bn = vertexB.getNeighbours(vertexA.id);
let anCount = an.length;
let bnCount = bn.length;
// All vertices connected to the edge vertexA to vertexB
let tn = ArrayHelper.merge(an, bn);
// Only considering the connected vertices
let sideCount = [0, 0];
for (var i = 0; i < tn.length; i++) {
let v = this.graph.vertices[tn[i]].position;
if (v.sameSideAs(vertexA.position, vertexB.position, sides[0])) {
sideCount[0]++;
} else {
sideCount[1]++;
}
}
// Considering all vertices in the graph, this is to resolve ties
// from the above side counts
let totalSideCount = [0, 0];
for (var i = 0; i < this.graph.vertices.length; i++) {
let v = this.graph.vertices[i].position;
if (v.sameSideAs(vertexA.position, vertexB.position, sides[0])) {
totalSideCount[0]++;
} else {
totalSideCount[1]++;
}
}
return {
totalSideCount: totalSideCount,
totalPosition: totalSideCount[0] > totalSideCount[1] ? 0 : 1,
sideCount: sideCount,
position: sideCount[0] > sideCount[1] ? 0 : 1,
anCount: anCount,
bnCount: bnCount
};
}
/**
* Sets the center for a ring.
*
* @param {Ring} ring A ring.
*/
setRingCenter(ring) {
let ringSize = ring.getSize();
let total = new Vector2(0, 0);
for (var i = 0; i < ringSize; i++) {
total.add(this.graph.vertices[ring.members[i]].position);
}
ring.center = total.divide(ringSize);
}
/**
* Gets the center of a ring contained within a bridged ring and containing a given vertex.
*
* @param {Ring} ring A bridged ring.
* @param {Vertex} vertex A vertex.
* @returns {Vector2} The center of the subring that containing the vertex.
*/
getSubringCenter(ring, vertex) {
let rings = vertex.value.originalRings;
let center = ring.center;
let smallest = Number.MAX_VALUE;
// Always get the smallest ring.
for (var i = 0; i < rings.length; i++) {
for (var j = 0; j < ring.rings.length; j++) {
if (rings[i] === ring.rings[j].id) {
if (ring.rings[j].getSize() < smallest) {
center = ring.rings[j].center;
smallest = ring.rings[j].getSize();
}
}
}
}
return center;
}
/**
* Draw the actual edges as bonds to the canvas.
*
* @param {Boolean} debug A boolean indicating whether or not to draw debug helpers.
*/
drawEdges(debug) {
let that = this;
let drawn = Array(this.graph.edges.length);
drawn.fill(false);
this.graph.traverseBF(0, function (vertex) {
let edges = that.graph.getEdges(vertex.id);
for (var i = 0; i < edges.length; i++) {
let edgeId = edges[i];
if (!drawn[edgeId]) {
drawn[edgeId] = true;
that.drawEdge(edgeId, debug);
}
}
});
// Draw ring for implicitly defined aromatic rings
if (!this.bridgedRing) {
for (var i = 0; i < this.rings.length; i++) {
let ring = this.rings[i];
if (this.isRingAromatic(ring)) {
this.canvasWrapper.drawAromaticityRing(ring);
}
}
}
}
/**
* Draw the an edge as a bonds to the canvas.
*
* @param {Number} edgeId An edge id.
* @param {Boolean} debug A boolean indicating whether or not to draw debug helpers.
*/
drawEdge(edgeId, debug) {
let that = this;
let edge = this.graph.edges[edgeId];
let vertexA = this.graph.vertices[edge.sourceId];
let vertexB = this.graph.vertices[edge.targetId];
let elementA = vertexA.value.element;
let elementB = vertexB.value.element;
if ((!vertexA.value.isDrawn || !vertexB.value.isDrawn) && this.opts.atomVisualization === 'default') {
return;
}
let a = vertexA.position;
let b = vertexB.position;
let normals = this.getEdgeNormals(edge);
// Create a point on each side of the line
let sides = ArrayHelper.clone(normals);
sides[0].multiplyScalar(10).add(a);
sides[1].multiplyScalar(10).add(a);
if (edge?.bondType === '=' || this.getRingbondType(vertexA, vertexB) === '=' ||
(edge.isPartOfAromaticRing && this.bridgedRing)) {
// Always draw double bonds inside the ring
let inRing = this.areVerticesInSameRing(vertexA, vertexB);
let s = this.chooseSide(vertexA, vertexB, sides);
if (inRing) {
// Always draw double bonds inside a ring
// if the bond is shared by two rings, it is drawn in the larger
// problem: smaller ring is aromatic, bond is still drawn in larger -> fix this
let lcr = this.getLargestOrAromaticCommonRing(vertexA, vertexB);
let center = lcr.center;
normals[0].multiplyScalar(that.opts.bondSpacing);
normals[1].multiplyScalar(that.opts.bondSpacing);
// Choose the normal that is on the same side as the center
let line = null;
if (center.sameSideAs(vertexA.position, vertexB.position, Vector2.add(a, normals[0]))) {
line = new Line(Vector2.add(a, normals[0]), Vector2.add(b, normals[0]), elementA, elementB);
} else {
line = new Line(Vector2.add(a, normals[1]), Vector2.add(b, normals[1]), elementA, elementB);
}
line.shorten(this.opts.bondLength - this.opts.shortBondLength * this.opts.bondLength);
// The shortened edge
if (edge.isPartOfAromaticRing) {
this.canvasWrapper.drawLine(line, true);
} else {
this.canvasWrapper.drawLine(line);
}
// The normal edge
this.canvasWrapper.drawLine(new Line(a, b, elementA, elementB));
} else if (edge.center || vertexA.isTerminal() && vertexB.isTerminal()) {
normals[0].multiplyScalar(that.opts.halfBondSpacing);
normals[1].multiplyScalar(that.opts.halfBondSpacing);
let lineA = new Line(Vector2.add(a, normals[0]), Vector2.add(b, normals[0]), elementA, elementB);
let lineB = new Line(Vector2.add(a, normals[1]), Vector2.add(b, normals[1]), elementA, elementB);
this.canvasWrapper.drawLine(lineA);
this.canvasWrapper.drawLine(lineB);
} else if (s.anCount == 0 && s.bnCount > 1 || s.bnCount == 0 && s.anCount > 1) {
// Both lines are the same length here
// Add the spacing to the edges (which are of unit length)
normals[0].multiplyScalar(that.opts.halfBondSpacing);
normals[1].multiplyScalar(that.opts.halfBondSpacing);
let lineA = new Line(Vector2.add(a, normals[0]), Vector2.add(b, normals[0]), elementA, elementB);
let lineB = new Line(Vector2.add(a, normals[1]), Vector2.add(b, normals[1]), elementA, elementB);
this.canvasWrapper.drawLine(lineA);
this.canvasWrapper.drawLine(lineB);
} else if (s.sideCount[0] > s.sideCount[1]) {
normals[0].multiplyScalar(that.opts.bondSpacing);
normals[1].multiplyScalar(that.opts.bondSpacing);
let line = new Line(Vector2.add(a, normals[0]), Vector2.add(b, normals[0]), elementA, elementB);
line.shorten(this.opts.bondLength - this.opts.shortBondLength * this.opts.bondLength);
this.canvasWrapper.drawLine(line);
this.canvasWrapper.drawLine(new Line(a, b, elementA, elementB));
} else if (s.sideCount[0] < s.sideCount[1]) {
normals[0].multiplyScalar(that.opts.bondSpacing);
normals[1].multiplyScalar(that.opts.bondSpacing);
let line = new Line(Vector2.add(a, normals[1]), Vector2.add(b, normals[1]), elementA, elementB);
line.shorten(this.opts.bondLength - this.opts.shortBondLength * this.opts.bondLength);
this.canvasWrapper.drawLine(line);
this.canvasWrapper.drawLine(new Line(a, b, elementA, elementB));
} else if (s.totalSideCount[0] > s.totalSideCount[1]) {
normals[0].multiplyScalar(that.opts.bondSpacing);
normals[1].multiplyScalar(that.opts.bondSpacing);
let line = new Line(Vector2.add(a, normals[0]), Vector2.add(b, normals[0]), elementA, elementB);
line.shorten(this.opts.bondLength - this.opts.shortBondLength * this.opts.bondLength);
this.canvasWrapper.drawLine(line);
this.canvasWrapper.drawLine(new Line(a, b, elementA, elementB));
} else if (s.totalSideCount[0] <= s.totalSideCount[1]) {
normals[0].multiplyScalar(that.opts.bondSpacing);
normals[1].multiplyScalar(that.opts.bondSpacing);
let line = new Line(Vector2.add(a, normals[1]), Vector2.add(b, normals[1]), elementA, elementB);
line.shorten(this.opts.bondLength - this.opts.shortBondLength * this.opts.bondLength);
this.canvasWrapper.drawLine(line);
this.canvasWrapper.drawLine(new Line(a, b, elementA, elementB));
} else {
}
} else if (edge?.bondType === '#') {
normals[0].multiplyScalar(that.opts.bondSpacing / 1.5);
normals[1].multiplyScalar(that.opts.bondSpacing / 1.5);
let lineA = new Line(Vector2.add(a, normals[0]), Vector2.add(b, normals[0]), elementA, elementB);
let lineB = new Line(Vector2.add(a, normals[1]), Vector2.add(b, normals[1]), elementA, elementB);
this.canvasWrapper.drawLine(lineA);
this.canvasWrapper.drawLine(lineB);
this.canvasWrapper.drawLine(new Line(a, b, elementA, elementB));
} else if (edge?.bondType === '.') {
// TODO: Something... maybe... version 2?
} else {
let isChiralCenterA = vertexA.value.isStereoCenter;
let isChiralCenterB = vertexB.value.isStereoCenter;
if (edge.wedge === 'up') {
this.canvasWrapper.drawWedge(new Line(a, b, elementA, elementB, isChiralCenterA, isChiralCenterB));
} else if (edge.wedge === 'down') {
this.canvasWrapper.drawDashedWedge(new Line(a, b, elementA, elementB, isChiralCenterA, isChiralCenterB));
} else {
this.canvasWrapper.drawLine(new Line(a, b, elementA, elementB, isChiralCenterA, isChiralCenterB));
}
}
if (debug) {
let midpoint = Vector2.midpoint(a, b);
this.canvasWrapper.drawDebugText(midpoint.x, midpoint.y, 'e: ' + edgeId);
}
}
/**
* Draws the vertices representing atoms to the canvas.
*
* @param {Boolean} debug A boolean indicating whether or not to draw debug messages to the canvas.
*/
drawVertices(debug) {
var i = this.graph.vertices.length;
for (var i: any = 0; i < this.graph.vertices.length; i++) {
let vertex = this.graph.vertices[i];
let atom = vertex.value;
let charge = 0;
let isotope = 0;
let bondCount = vertex.value.bondCount;
let element = atom.element;
let hydrogens = Atom.maxBonds[element] - bondCount;
let dir = vertex.getTextDirection(this.graph.vertices);
let isTerminal = this.opts.terminalCarbons || element !== 'C' || atom.hasAttachedPseudoElements ? vertex.isTerminal() : false;
let isCarbon = atom.element === 'C';
// This is a HACK to remove all hydrogens from nitrogens in aromatic rings, as this
// should be the most common state. This has to be fixed by kekulization
if (atom.element === 'N' && atom.isPartOfAromaticRing) {
hydrogens = 0;
}
if (atom.bracket) {
hydrogens = atom.bracket.hcount;
charge = atom.bracket.charge;
isotope = atom.bracket.isotope;
}
if (this.opts.atomVisualization === 'allballs') {
this.canvasWrapper.drawBall(vertex.position.x, vertex.position.y, element);
} else if ((atom.isDrawn && (!isCarbon || atom.drawExplicit || isTerminal || atom.hasAttachedPseudoElements)) || this.graph.vertices.length === 1) {
if (this.opts.atomVisualization === 'default') {
this.canvasWrapper.drawText(vertex.position.x, vertex.position.y,
element, hydrogens, dir, isTerminal, charge, isotope, atom.getAttachedPseudoElements());
} else if (this.opts.atomVisualization === 'balls') {
this.canvasWrapper.drawBall(vertex.position.x, vertex.position.y, element);
}
} else if (vertex.getNeighbourCount() === 2 && vertex.forcePositioned == true) {
// If there is a carbon which bonds are in a straight line, draw a dot
let a = this.graph.vertices[vertex.neighbours[0]].position;
let b = this.graph.vertices[vertex.neighbours[1]].position;
let angle = Vector2.threePointangle(vertex.position, a, b);
if (Math.abs(Math.PI - angle) < 0.1) {
this.canvasWrapper.drawPoint(vertex.position.x, vertex.position.y, element);
}
}
if (debug) {
let value = 'v: ' + vertex.id + ' ' + ArrayHelper.print(atom.ringbonds);
this.canvasWrapper.drawDebugText(vertex.position.x, vertex.position.y, value);
} else {
// this.canvasWrapper.drawDebugText(vertex.position.x, vertex.position.y, vertex.value.chirality);
}
}
// Draw the ring centers for debug purposes
if (this.opts.debug) {
for (var i: any = 0; i < this.rings.length; i++) {
let center = this.rings[i].center;
this.canvasWrapper.drawDebugPoint(center.x, center.y, 'r: ' + this.rings[i].id);
}
}
}
/**
* Position the vertices according to their bonds and properties.
*/
position() {
let startVertex = null;
// Always start drawing at a bridged ring if there is one
// If not, start with a ring
// else, start with 0
for (var i = 0; i < this.graph.vertices.length; i++) {
if (this.graph.vertices[i].value.bridgedRing !== null) {
startVertex = this.graph.vertices[i];
break;
}
}
for (var i = 0; i < this.rings.length; i++) {
if (this.rings[i].isBridged) {
startVertex = this.graph.vertices[this.rings[i].members[0]];
}
}
if (this.rings.length > 0 && startVertex === null) {
startVertex = this.graph.vertices[this.rings[0].members[0]];
}
if (startVertex === null) {
startVertex = this.graph.vertices[0];
}
this.createNextBond(startVertex, null, 0.0);
}
/**
* Stores the current information associated with rings.
*/
backupRingInformation() {
this.originalRings = Array();
this.originalRingConnections = Array();
for (var i = 0; i < this.rings.length; i++) {
this.originalRings.push(this.rings[i]);
}
for (var i = 0; i < this.ringConnections.length; i++) {
this.originalRingConnections.push(this.ringConnections[i]);
}
for (var i = 0; i < this.graph.vertices.length; i++) {
this.graph.vertices[i].value.backupRings();
}
}
/**
* Restores the most recently backed up information associated with rings.
*/
restoreRingInformation() {
// Get the subring centers from the bridged rings
let bridgedRings = this.getBridgedRings();
this.rings = Array();
this.ringConnections = Array();
for (var i = 0; i < bridgedRings.length; i++) {
let bridgedRing = bridgedRings[i];
for (var j = 0; j < bridgedRing.rings.length; j++) {
let ring = bridgedRing.rings[j];
this.originalRings[ring.id].center = ring.center;
}
}
for (var i = 0; i < this.originalRings.length; i++) {
this.rings.push(this.originalRings[i]);
}
for (var i = 0; i < this.originalRingConnections.length; i++) {
this.ringConnections.push(this.originalRingConnections[i]);
}
for (var i = 0; i < this.graph.vertices.length; i++) {
this.graph.vertices[i].value.restoreRings();
}
}
// TODO: This needs some cleaning up
/**
* Creates a new ring, that is, positiones all the vertices inside a ring.
*
* @param {Ring} ring The ring to position.
* @param {(Vector2|null)} [center=null] The center of the ring to be created.
* @param {(Vertex|null)} [startVertex=null] The first vertex to be positioned inside the ring.
* @param {(Vertex|null)} [previousVertex=null] The last vertex that was positioned.
* @param {Boolean} [previousVertex=false] A boolean indicating whether or not this ring was force positioned already - this is needed after force layouting a ring, in order to draw rings connected to it.
*/
createRing(ring, center = null, startVertex = null, previousVertex = null) {
if (ring.positioned) {
return;
}
center = center ? center : new Vector2(0, 0);
let orderedNeighbours = ring.getOrderedNeighbours(this.ringConnections);
let startingAngle = startVertex ? Vector2.subtract(startVertex.position, center).angle() : 0;
let radius = MathHelper.polyCircumradius(this.opts.bondLength, ring.getSize());
let angle = MathHelper.centralAngle(ring.getSize());
ring.centralAngle = angle;
let a = startingAngle;
let that = this;
let startVertexId = (startVertex) ? startVertex.id : null;
if (ring.members.indexOf(startVertexId) === -1) {
if (startVertex) {
startVertex.positioned = false;
}
startVertexId = ring.members[0];
}
// If the ring is bridged, then draw the vertices inside the ring
// using a force based approach
if (ring.isBridged) {
this.graph.kkLayout(ring.members.slice(), center, startVertex.id, ring, this.opts.bondLength,
this.opts.kkThreshold, this.opts.kkInnerThreshold, this.opts.kkMaxIteration,
this.opts.kkMaxInnerIteration, this.opts.kkMaxEnergy);
ring.positioned = true;
// Update the center of the bridged ring
this.setRingCenter(ring);
center = ring.center;
// Setting the centers for the subrings
for (var i = 0; i < ring.rings.length; i++) {
this.setRingCenter(ring.rings[i]);
}
} else {
ring.eachMember(this.graph.vertices, function (v) {
let vertex = that.graph.vertices[v];
if (!vertex.positioned) {
vertex.setPosition(center.x + Math.cos(a) * radius, center.y + Math.sin(a) * radius);
}
a += angle;
if (!ring.isBridged || ring.rings.length < 3) {
vertex.angle = a;
vertex.positioned = true;
}
}, startVertexId, (previousVertex) ? previousVertex.id : null);
}
ring.positioned = true;
ring.center = center;
// Draw neighbours in decreasing order of connectivity
for (var i = 0; i < orderedNeighbours.length; i++) {
let neighbour = this.getRing(orderedNeighbours[i].neighbour);
if (neighbour.positioned) {
continue;
}
let vertices = RingConnection.getVertices(this.ringConnections, ring.id, neighbour.id);
if (vertices.length === 2) {
// This ring is a fused ring
ring.isFused = true;
neighbour.isFused = true;
let vertexA = this.graph.vertices[vertices[0]];
let vertexB = this.graph.vertices[vertices[1]];
// Get middle between vertex A and B
let midpoint = Vector2.midpoint(vertexA.position, vertexB.position);
// Get the normals to the line between A and B
let normals = Vector2.normals(vertexA.position, vertexB.position);
// Normalize the normals
normals[0].normalize();
normals[1].normalize();
// Set length from middle of side to center (the apothem)
let r = MathHelper.polyCircumradius(this.opts.bondLength, neighbour.getSize());
let apothem = MathHelper.apothem(r, neighbour.getSize());
normals[0].multiplyScalar(apothem).add(midpoint);
normals[1].multiplyScalar(apothem).add(midpoint);
// Pick the normal which results in a larger distance to the previous center
// Also check whether it's inside another ring
let nextCenter = normals[0];
if (Vector2.subtract(center, normals[1]).lengthSq() > Vector2.subtract(center, normals[0]).lengthSq()) {
nextCenter = normals[1];
}
// Get the vertex (A or B) which is in clock-wise direction of the other
let posA = Vector2.subtract(vertexA.position, nextCenter);
let posB = Vector2.subtract(vertexB.position, nextCenter);
if (posA.clockwise(posB) === -1) {
if (!neighbour.positioned) {
this.createRing(neighbour, nextCenter, vertexA, vertexB);
}
} else {
if (!neighbour.positioned) {
this.createRing(neighbour, nextCenter, vertexB, vertexA);
}
}
} else if (vertices.length === 1) {
// This ring is a spiro
ring.isSpiro = true;
neighbour.isSpiro = true;
let vertexA = this.graph.vertices[vertices[0]];
// Get the vector pointing from the shared vertex to the new centpositioner
let nextCenter = Vector2.subtract(center, vertexA.position);
nextCenter.invert();
nextCenter.normalize();
// Get the distance from the vertex to the center
let r = MathHelper.polyCircumradius(this.opts.bondLength, neighbour.getSize());
nextCenter.multiplyScalar(r);
nextCenter.add(vertexA.position);
if (!neighbour.positioned) {
this.createRing(neighbour, nextCenter, vertexA);
}
}
}
// Next, draw atoms that are not part of a ring that are directly attached to this ring
for (var i = 0; i < ring.members.length; i++) {
let ringMember = this.graph.vertices[ring.members[i]];
let ringMemberNeighbours = ringMember.neighbours;
// If there are multiple, the ovlerap will be resolved in the appropriate step
for (var j = 0; j < ringMemberNeighbours.length; j++) {
let v = this.graph.vertices[ringMemberNeighbours[j]];
if (v.positioned) {
continue;
}
v.value.isConnectedToRing = true;
this.createNextBond(v, ringMember, 0.0);
}
}
}
/**
* Rotate an entire subtree by an angle around a center.
*
* @param {Number} vertexId A vertex id (the root of the sub-tree).
* @param {Number} parentVertexId A vertex id in the previous direction of the subtree that is to rotate.
* @param {Number} angle An angle in randians.
* @param {Vector2} center The rotational center.
*/
rotateSubtree(vertexId, parentVertexId, angle, center) {
let that = this;
this.graph.traverseTree(vertexId, parentVertexId, function (vertex) {
vertex.position.rotateAround(angle, center);
for (var i = 0; i < vertex.value.anchoredRings.length; i++) {
let ring = that.rings[vertex.value.anchoredRings[i]];
if (ring) {
ring.center.rotateAround(angle, center);
}
}
});
}
/**
* Gets the overlap score of a subtree.
*
* @param {Number} vertexId A vertex id (the root of the sub-tree).
* @param {Number} parentVertexId A vertex id in the previous direction of the subtree.
* @param {Number[]} vertexOverlapScores An array containing the vertex overlap scores indexed by vertex id.
* @returns {Object} An object containing the total overlap score and the center of mass of the subtree weighted by overlap score { value: 0.2, center: new Vector2() }.
*/
getSubtreeOverlapScore(vertexId, parentVertexId, vertexOverlapScores) {
let that = this;
let score = 0;
let center = new Vector2(0, 0);
let count = 0;
this.graph.traverseTree(vertexId, parentVertexId, function (vertex) {
if (!vertex.value.isDrawn) {
return;
}
let s = vertexOverlapScores[vertex.id];
if (s > that.opts.overlapSensitivity) {
score += s;
count++;
}
let position = that.graph.vertices[vertex.id].position.clone();
position.multiplyScalar(s)
center.add(position);
});
center.divide(score);
return {
value: score / count,
center: center
};
}
/**
* Returns the current (positioned vertices so far) center of mass.
*
* @returns {Vector2} The current center of mass.
*/
getCurrentCenterOfMass() {
let total = new Vector2(0, 0);
let count = 0;
for (var i = 0; i < this.graph.vertices.length; i++) {
let vertex = this.graph.vertices[i];
if (vertex.positioned) {
total.add(vertex.position);
count++;
}
}
return total.divide(count);
}
/**
* Returns the current (positioned vertices so far) center of mass in the neighbourhood of a given position.
*
* @param {Vector2} vec The point at which to look for neighbours.
* @param {Number} [r=currentBondLength*2.0] The radius of vertices to include.
* @returns {Vector2} The current center of mass.
*/
getCurrentCenterOfMassInNeigbourhood(vec, r = this.opts.bondLength * 2.0) {
let total = new Vector2(0, 0);
let count = 0;
let rSq = r * r;
for (var i = 0; i < this.graph.vertices.length; i++) {
let vertex = this.graph.vertices[i];
if (vertex.positioned && vec.distanceSq(vertex.position) < rSq) {
total.add(vertex.position);
count++;
}
}
return total.divide(count);
}
/**
* Resolve primary (exact) overlaps, such as two vertices that are connected to the same ring vertex.
*/
resolvePrimaryOverlaps() {
let overlaps = Array();
let done = Array(this.graph.vertices.length);
// Looking for overlaps created by two bonds coming out of a ring atom, which both point straight
// away from the ring and are thus perfectly overlapping.
for (var i = 0; i < this.rings.length; i++) {
let ring = this.rings[i];
for (var j = 0; j < ring.members.length; j++) {
let vertex = this.graph.vertices[ring.members[j]];
if (done[vertex.id]) {
continue;
}
done[vertex.id] = true;
let nonRingNeighbours = this.getNonRingNeighbours(vertex.id);
if (nonRingNeighbours.length > 1) {
// Look for rings where there are atoms with two bonds outside the ring (overlaps)
let rings = Array();
for (var k = 0; k < vertex.value.rings.length; k++) {
rings.push(vertex.value.rings[k]);
}
overlaps.push({
common: vertex,
rings: rings,
vertices: nonRingNeighbours
});
} else if (nonRingNeighbours.length === 1 && vertex.value.rings.length === 2) {
// Look for bonds coming out of joined rings to adjust the angle, an example is: C1=CC(=CC=C1)[C@]12SCCN1CC1=CC=CC=C21
// where the angle has to be adjusted to account for fused ring
let rings = Array();
for (var k = 0; k < vertex.value.rings.length; k++) {
rings.push(vertex.value.rings[k]);
}
overlaps.push({
common: vertex,
rings: rings,
vertices: nonRingNeighbours
});
}
}
}
for (var i = 0; i < overlaps.length; i++) {
let overlap = overlaps[i];
if (overlap.vertices.length === 2) {
let a = overlap.vertices[0];
let b = overlap.vertices[1];
if (!a.value.isDrawn || !b.value.isDrawn) {
continue;
}
let angle = (2 * Math.PI - this.getRing(overlap.rings[0]).getAngle()) / 6.0;
this.rotateSubtree(a.id, overlap.common.id, angle, overlap.common.position);
this.rotateSubtree(b.id, overlap.common.id, -angle, overlap.common.position);
// Decide which way to rotate the vertices depending on the effect it has on the overlap score
let overlapScore = this.getOverlapScore();
let subTreeOverlapA = this.getSubtreeOverlapScore(a.id, overlap.common.id, overlapScore.vertexScores);
let subTreeOverlapB = this.getSubtreeOverlapScore(b.id, overlap.common.id, overlapScore.vertexScores);
let total = subTreeOverlapA.value + subTreeOverlapB.value;
this.rotateSubtree(a.id, overlap.common.id, -2.0 * angle, overlap.common.position);
this.rotateSubtree(b.id, overlap.common.id, 2.0 * angle, overlap.common.position);
overlapScore = this.getOverlapScore();
subTreeOverlapA = this.getSubtreeOverlapScore(a.id, overlap.common.id, overlapScore.vertexScores);
subTreeOverlapB = this.getSubtreeOverlapScore(b.id, overlap.common.id, overlapScore.vertexScores);
if (subTreeOverlapA.value + subTreeOverlapB.value > total) {
this.rotateSubtree(a.id, overlap.common.id, 2.0 * angle, overlap.common.position);
this.rotateSubtree(b.id, overlap.common.id, -2.0 * angle, overlap.common.position);
}
} else if (overlap.vertices.length === 1) {
if (overlap.rings.length === 2) {
// TODO: Implement for more overlap resolution
// console.log(overlap);
}
}
}
}
/**
* Resolve secondary overlaps. Those overlaps are due to the structure turning back on itself.
*
* @param {Object[]} scores An array of objects sorted descending by score.
* @param {Number} scores[].id A vertex id.
* @param {Number} scores[].score The overlap score associated with the vertex id.
*/
resolveSecondaryOverlaps(scores) {
for (var i = 0; i < scores.length; i++) {
if (scores[i].score > this.opts.overlapSensitivity) {
let vertex = this.graph.vertices[scores[i].id];
if (vertex.isTerminal()) {
let closest = this.getClosestVertex(vertex);
if (closest) {
// If one of the vertices is the first one, the previous vertex is not the central vertex but the dummy
// so take the next rather than the previous, which is vertex 1
let closestPosition = null;
if (closest.isTerminal()) {
closestPosition = closest.id === 0 ? this.graph.vertices[1].position : closest.previousPosition
} else {
closestPosition = closest.id === 0 ? this.graph.vertices[1].position : closest.position
}
let vertexPreviousPosition = vertex.id === 0 ? this.graph.vertices[1].position : vertex.previousPosition;
vertex.position.rotateAwayFrom(closestPosition, vertexPreviousPosition, MathHelper.toRad(20));
}
}
}
}
}
/**
* Get the last non-null or 0 angle vertex.
* @param {Number} vertexId A vertex id.
* @returns {Vertex} The last vertex with an angle that was not 0 or null.
*/
getLastVertexWithAngle(vertexId) {
let angle = 0;
let vertex = null;
while (!angle && vertexId) {
vertex = this.graph.vertices[vertexId];
angle = vertex.angle;
vertexId = vertex.parentVertexId;
}
return vertex;
}
/**
* Positiones the next vertex thus creating a bond.
*
* @param {Vertex} vertex A vertex.
* @param {Vertex} [previousVertex=null] The previous vertex which has been positioned.
* @param {Number} [angle=0.0] The (global) angle of the vertex.
* @param {Boolean} [originShortest=false] Whether the origin is the shortest subtree in the branch.
* @param {Boolean} [skipPositioning=false] Whether or not to skip positioning and just check the neighbours.
*/
createNextBond(vertex, previousVertex = null, angle = 0.0, originShortest = false, skipPositioning = false) {
if (vertex.positioned && !skipPositioning) {
return;
}
// If the double bond config was set on this vertex, do not check later
let doubleBondConfigSet = false;
// Keeping track of configurations around double bonds
if (previousVertex) {
let edge = this.graph.getEdge(vertex.id, previousVertex.id);
if ((edge?.bondType === '/' || edge?.bondType === '\\') && ++this.doubleBondConfigCount % 2 === 1) {
if (this.doubleBondConfig === null) {
this.doubleBondConfig = edge.bondType;
doubleBondConfigSet = true;
// Switch if the bond is a branch bond and previous vertex is the first
// TODO: Why is it different with the first vertex?
if (previousVertex.parentVertexId === null && vertex.value.branchBond) {
if (this.doubleBondConfig === '/') {
this.doubleBondConfig = '\\';
} else if (this.doubleBondConfig === '\\') {
this.doubleBondConfig = '/';
}
}
}
}
}
// If the current node is the member of one ring, then point straight away
// from the center of the ring. However, if the current node is a member of
// two rings, point away from the middle of the centers of the two rings
if (!skipPositioning) {
if (!previousVertex) {
// Add a (dummy) previous position if there is no previous vertex defined
// Since the first vertex is at (0, 0), create a vector at (bondLength, 0)
// and rotate it by 90°
let dummy = new Vector2(this.opts.bondLength, 0);
dummy.rotate(MathHelper.toRad(-60));
vertex.previousPosition = dummy;
vertex.setPosition(this.opts.bondLength, 0);
vertex.angle = MathHelper.toRad(-60);
// Do not position the vertex if it belongs to a bridged ring that is positioned using a layout algorithm.
if (vertex.value.bridgedRing === null) {
vertex.positioned = true;
}
} else if (previousVertex.value.rings.length > 0) {
let neighbours = previousVertex.neighbours;
let joinedVertex = null;
let pos = new Vector2(0.0, 0.0);
if (previousVertex.value.bridgedRing === null && previousVertex.value.rings.length > 1) {
for (var i = 0; i < neighbours.length; i++) {
let neighbour = this.graph.vertices[neighbours[i]];
if (ArrayHelper.containsAll(neighbour.value.rings, previousVertex.value.rings)) {
joinedVertex = neighbour;
break;
}
}
}
if (joinedVertex === null) {
for (var i = 0; i < neighbours.length; i++) {
let v = this.graph.vertices[neighbours[i]];
if (v.positioned && this.areVerticesInSameRing(v, previousVertex)) {
pos.add(Vector2.subtract(v.position, previousVertex.position));
}
}
pos.invert().normalize().multiplyScalar(this.opts.bondLength).add(previousVertex.position);
} else {
pos = joinedVertex.position.clone().rotateAround(Math.PI, previousVertex.position);
}
vertex.previousPosition = previousVertex.position;
vertex.setPositionFromVector(pos);
vertex.positioned = true;
} else {
// If the previous vertex was not part of a ring, draw a bond based
// on the global angle of the previous bond
let v = new Vector2(this.opts.bondLength, 0);
v.rotate(angle);
v.add(previousVertex.position);
vertex.setPositionFromVector(v);
vertex.previousPosition = previousVertex.position;
vertex.positioned = true;
}
}
// Go to next vertex
// If two rings are connected by a bond ...
if (vertex.value.bridgedRing !== null) {
let nextRing = this.getRing(vertex.value.bridgedRing);
if (!nextRing.positioned) {
let nextCenter = Vector2.subtract(vertex.previousPosition, vertex.position);
nextCenter.invert();
nextCenter.normalize();
let r = MathHelper.polyCircumradius(this.opts.bondLength, nextRing.members.length);
nextCenter.multiplyScalar(r);
nextCenter.add(vertex.position);
this.createRing(nextRing, nextCenter, vertex);
}
} else if (vertex.value.rings.length > 0) {
let nextRing = this.getRing(vertex.value.rings[0]);
if (!nextRing.positioned) {
let nextCenter = Vector2.subtract(vertex.previousPosition, vertex.position);
nextCenter.invert();
nextCenter.normalize();
let r = MathHelper.polyCircumradius(this.opts.bondLength, nextRing.getSize());
nextCenter.multiplyScalar(r);
nextCenter.add(vertex.position);
this.createRing(nextRing, nextCenter, vertex);
}
} else {
// Draw the non-ring vertices connected to this one
// let isStereoCenter = vertex.value.isStereoCenter;
let tmpNeighbours = vertex.getNeighbours();
let neighbours = Array();
// Remove neighbours that are not drawn
for (var i = 0; i < tmpNeighbours.length; i++) {
if (this.graph.vertices[tmpNeighbours[i]].value.isDrawn) {
neighbours.push(tmpNeighbours[i]);
}
}
// Remove the previous vertex (which has already been drawn)
if (previousVertex) {
neighbours = ArrayHelper.remove(neighbours, previousVertex.id);
}
let previousAngle = vertex.getAngle();
if (neighbours.length === 1) {
let nextVertex = this.graph.vertices[neighbours[0]];
// Make a single chain always cis except when there's a tribble (yes, this is a Star Trek reference) bond
// or if there are successive double bonds. Added a ring check because if there is an aromatic ring the ring bond inside the ring counts as a double bond and leads to =-= being straight.
if ((vertex.value?.bondType === '#' || (previousVertex && previousVertex.value?.bondType === '#')) ||
vertex.value.bondType === '=' && previousVertex && previousVertex.value.rings.length === 0 &&
previousVertex.value.bondType === '=' && vertex.value.branchBond !== '-') {
vertex.value.drawExplicit = false;
if (previousVertex) {
let straightEdge1 = this.graph.getEdge(vertex.id, previousVertex.id);
straightEdge1.center = true;
}
let straightEdge2 = this.graph.getEdge(vertex.id, nextVertex.id);
straightEdge2.center = true;
if (vertex.value.bondType === '#' || previousVertex && previousVertex.value.bondType === '#') {
nextVertex.angle = 0.0;
}
nextVertex.drawExplicit = true;
this.createNextBond(nextVertex, vertex, previousAngle + nextVertex.angle);
} else if (previousVertex && previousVertex.value.rings.length > 0) {
// If coming out of a ring, always draw away from the center of mass
let proposedAngleA = MathHelper.toRad(60);
let proposedAngleB = -proposedAngleA;
let proposedVectorA = new Vector2(this.opts.bondLength, 0);
let proposedVectorB = new Vector2(this.opts.bondLength, 0);
proposedVectorA.rotate(proposedAngleA).add(vertex.position);
proposedVectorB.rotate(proposedAngleB).add(vertex.position);
// let centerOfMass = this.getCurrentCenterOfMassInNeigbourhood(vertex.position, 100);
let centerOfMass = this.getCurrentCenterOfMass();
let distanceA = proposedVectorA.distanceSq(centerOfMass);
let distanceB = proposedVectorB.distanceSq(centerOfMass);
nextVertex.angle = distanceA < distanceB ? proposedAngleB : proposedAngleA;
this.createNextBond(nextVertex, vertex, previousAngle + nextVertex.angle);
} else {
let a = vertex.angle;
// Take the min and max if the previous angle was in a 4-neighbourhood (90° angles)
// TODO: If a is null or zero, it should be checked whether or not this one should go cis or trans, that is,
// it should go into the oposite direction of the last non-null or 0 previous vertex / angle.
if (previousVertex && previousVertex.neighbours.length > 3) {
if (a > 0) {
a = Math.min(1.0472, a);
} else if (a < 0) {
a = Math.max(-1.0472, a);
} else {
a = 1.0472;
}
} else if (!a) {
let v = this.getLastVertexWithAngle(vertex.id);
a = v.angle;
if (!a) {
a = 1.0472;
}
}
// Handle configuration around double bonds
if (previousVertex && !doubleBondConfigSet) {
let bondType = this.graph.getEdge(vertex.id, nextVertex.id).bondType;
if (bondType === '/') {
if (this.doubleBondConfig === '/') {
// Nothing to do since it will be trans per default
} else if (this.doubleBondConfig === '\\') {
a = -a;
}
this.doubleBondConfig = null;
} else if (bondType === '\\') {
if (this.doubleBondConfig === '/') {
a = -a;
} else if (this.doubleBondConfig === '\\') {
// Nothing to do since it will be trans per default
}
this.doubleBondConfig = null;
}
}
if (originShortest) {
nextVertex.angle = a;
} else {
nextVertex.angle = -a;
}
this.createNextBond(nextVertex, vertex, previousAngle + nextVertex.angle);
}
} else if (neighbours.length === 2) {
// If the previous vertex comes out of a ring, it doesn't have an angle set
let a = vertex.angle;
if (!a) {
a = 1.0472;
}
// Check for the longer subtree - always go with cis for the longer subtree
let subTreeDepthA = this.graph.getTreeDepth(neighbours[0], vertex.id);
let subTreeDepthB = this.graph.getTreeDepth(neighbours[1], vertex.id);
let l = this.graph.vertices[neighbours[0]];
let r = this.graph.vertices[neighbours[1]];
l.value.subtreeDepth = subTreeDepthA;
r.value.subtreeDepth = subTreeDepthB;
// Also get the subtree for the previous direction (this is important when
// the previous vertex is the shortest path)
let subTreeDepthC = this.graph.getTreeDepth(previousVertex ? previousVertex.id : null, vertex.id);
if (previousVertex) {
previousVertex.value.subtreeDepth = subTreeDepthC;
}
let cis = 0;
let trans = 1;
// Carbons go always cis
if (r.value.element === 'C' && l.value.element !== 'C' && subTreeDepthB > 1 && subTreeDepthA < 5) {
cis = 1;
trans = 0;
} else if (r.value.element !== 'C' && l.value.element === 'C' && subTreeDepthA > 1 && subTreeDepthB < 5) {
cis = 0;
trans = 1;
} else if (subTreeDepthB > subTreeDepthA) {
cis = 1;
trans = 0;
}
let cisVertex = this.graph.vertices[neighbours[cis]];
let transVertex = this.graph.vertices[neighbours[trans]];
// let edgeCis = this.graph.getEdge(vertex.id, cisVertex.id);
// let edgeTrans = this.graph.getEdge(vertex.id, transVertex.id);
// If the origin tree is the shortest, make them the main chain
let originShortest = false;
if (subTreeDepthC < subTreeDepthA && subTreeDepthC < subTreeDepthB) {
originShortest = true;
}
transVertex.angle = a;
cisVertex.angle = -a;
if (this.doubleBondConfig === '\\') {
if (transVertex.value.branchBond === '\\') {
transVertex.angle = -a;
cisVertex.angle = a;
}
} else if (this.doubleBondConfig === '/') {
if (transVertex.value.branchBond === '/') {
transVertex.angle = -a;
cisVertex.angle = a;
}
}
this.createNextBond(transVertex, vertex, previousAngle + transVertex.angle, originShortest);
this.createNextBond(cisVertex, vertex, previousAngle + cisVertex.angle, originShortest);
} else if (neighbours.length === 3) {
// The vertex with the longest sub-tree should always go straight
let d1 = this.graph.getTreeDepth(neighbours[0], vertex.id);
let d2 = this.graph.getTreeDepth(neighbours[1], vertex.id);
let d3 = this.graph.getTreeDepth(neighbours[2], vertex.id);
let s = this.graph.vertices[neighbours[0]];
let l = this.graph.vertices[neighbours[1]];
let r = this.graph.vertices[neighbours[2]];
s.value.subtreeDepth = d1;
l.value.subtreeDepth = d2;
r.value.subtreeDepth = d3;
if (d2 > d1 && d2 > d3) {
s = this.graph.vertices[neighbours[1]];
l = this.graph.vertices[neighbours[0]];
r = this.graph.vertices[neighbours[2]];
} else if (d3 > d1 && d3 > d2) {
s = this.graph.vertices[neighbours[2]];
l = this.graph.vertices[neighbours[0]];
r = this.graph.vertices[neighbours[1]];
}
// Create a cross if more than one subtree is of length > 1
// or the vertex is connected to a ring
if (previousVertex &&
previousVertex.value.rings.length < 1 &&
s.value.rings.length < 1 &&
l.value.rings.length < 1 &&
r.value.rings.length < 1 &&
this.graph.getTreeDepth(l.id, vertex.id) === 1 &&
this.graph.getTreeDepth(r.id, vertex.id) === 1 &&
this.graph.getTreeDepth(s.id, vertex.id) > 1) {
s.angle = -vertex.angle;
if (vertex.angle >= 0) {
l.angle = MathHelper.toRad(30);
r.angle = MathHelper.toRad(90);
} else {
l.angle = -MathHelper.toRad(30);
r.angle = -MathHelper.toRad(90);
}
this.createNextBond(s, vertex, previousAngle + s.angle);
this.createNextBond(l, vertex, previousAngle + l.angle);
this.createNextBond(r, vertex, previousAngle + r.angle);
} else {
s.angle = 0.0;
l.angle = MathHelper.toRad(90);
r.angle = -MathHelper.toRad(90);
this.createNextBond(s, vertex, previousAngle + s.angle);
this.createNextBond(l, vertex, previousAngle + l.angle);
this.createNextBond(r, vertex, previousAngle + r.angle);
}
} else if (neighbours.length === 4) {
// The vertex with the longest sub-tree should always go to the reflected opposide direction
let d1 = this.graph.getTreeDepth(neighbours[0], vertex.id);
let d2 = this.graph.getTreeDepth(neighbours[1], vertex.id);
let d3 = this.graph.getTreeDepth(neighbours[2], vertex.id);
let d4 = this.graph.getTreeDepth(neighbours[3], vertex.id);
let w = this.graph.vertices[neighbours[0]];
let x = this.graph.vertices[neighbours[1]];
let y = this.graph.vertices[neighbours[2]];
let z = this.graph.vertices[neighbours[3]];
w.value.subtreeDepth = d1;
x.value.subtreeDepth = d2;
y.value.subtreeDepth = d3;
z.value.subtreeDepth = d4;
if (d2 > d1 && d2 > d3 && d2 > d4) {
w = this.graph.vertices[neighbours[1]];
x = this.graph.vertices[neighbours[0]];
y = this.graph.vertices[neighbours[2]];
z = this.graph.vertices[neighbours[3]];
} else if (d3 > d1 && d3 > d2 && d3 > d4) {
w = this.graph.vertices[neighbours[2]];
x = this.graph.vertices[neighbours[0]];
y = this.graph.vertices[neighbours[1]];
z = this.graph.vertices[neighbours[3]];
} else if (d4 > d1 && d4 > d2 && d4 > d3) {
w = this.graph.vertices[neighbours[3]];
x = this.graph.vertices[neighbours[0]];
y = this.graph.vertices[neighbours[1]];
z = this.graph.vertices[neighbours[2]];
}
w.angle = -MathHelper.toRad(36);
x.angle = MathHelper.toRad(36);
y.angle = -MathHelper.toRad(108);
z.angle = MathHelper.toRad(108);
this.createNextBond(w, vertex, previousAngle + w.angle);
this.createNextBond(x, vertex, previousAngle + x.angle);
this.createNextBond(y, vertex, previousAngle + y.angle);
this.createNextBond(z, vertex, previousAngle + z.angle);
}
}
}
/**
* Gets the vetex sharing the edge that is the common bond of two rings.
*
* @param {Vertex} vertex A vertex.
* @returns {(Number|null)} The id of a vertex sharing the edge that is the common bond of two rings with the vertex provided or null, if none.
*/
getCommonRingbondNeighbour(vertex) {
let neighbours = vertex.neighbours;
for (var i = 0; i < neighbours.length; i++) {
let neighbour = this.graph.vertices[neighbours[i]];
if (ArrayHelper.containsAll(neighbour.value.rings, vertex.value.rings)) {
return neighbour;
}
}
return null;
}
/**
* Check if a vector is inside any ring.
*
* @param {Vector2} vec A vector.
* @returns {Boolean} A boolean indicating whether or not the point (vector) is inside any of the rings associated with the current molecule.
*/
isPointInRing(vec) {
for (var i = 0; i < this.rings.length; i++) {
let ring = this.rings[i];
if (!ring.positioned) {
continue;
}
let radius = MathHelper.polyCircumradius(this.opts.bondLength, ring.getSize());
let radiusSq = radius * radius;
if (vec.distanceSq(ring.center) < radiusSq) {
return true;
}
}
return false;
}
/**
* Check whether or not an edge is part of a ring.
*
* @param {Edge} edge An edge.
* @returns {Boolean} A boolean indicating whether or not the edge is part of a ring.
*/
isEdgeInRing(edge) {
let source = this.graph.vertices[edge.sourceId];
let target = this.graph.vertices[edge.targetId];
return this.areVerticesInSameRing(source, target);
}
/**
* Check whether or not an edge is rotatable.
*
* @param {Edge} edge An edge.
* @returns {Boolean} A boolean indicating whether or not the edge is rotatable.
*/
isEdgeRotatable(edge) {
let vertexA = this.graph.vertices[edge.sourceId];
let vertexB = this.graph.vertices[edge.targetId];
// Only single bonds are rotatable
if (edge.bondType !== '-') {
return false;
}
// Do not rotate edges that have a further single bond to each side - do that!
// If the bond is terminal, it doesn't make sense to rotate it
// if (vertexA.getNeighbourCount() + vertexB.getNeighbourCount() < 5) {
// return false;
// }
if (vertexA.isTerminal() || vertexB.isTerminal()) {
return false;
}
// Ringbonds are not rotatable
if (vertexA.value.rings.length > 0 && vertexB.value.rings.length > 0 &&
this.areVerticesInSameRing(vertexA, vertexB)) {
return false;
}
return true;
}
/**
* Check whether or not a ring is an implicitly defined aromatic ring (lower case smiles).
*
* @param {Ring} ring A ring.
* @returns {Boolean} A boolean indicating whether or not a ring is implicitly defined as aromatic.
*/
isRingAromatic(ring) {
for (var i = 0; i < ring.members.length; i++) {
let vertex = this.graph.vertices[ring.members[i]];
if (!vertex.value.isPartOfAromaticRing) {
return false;
}
}
return true;
}
/**
* Get the normals of an edge.
*
* @param {Edge} edge An edge.
* @returns {Vector2[]} An array containing two vectors, representing the normals.
*/
getEdgeNormals(edge) {
let v1 = this.graph.vertices[edge.sourceId].position;
let v2 = this.graph.vertices[edge.targetId].position;
// Get the normalized normals for the edge
let normals = Vector2.units(v1, v2);
return normals;
}
/**
* Returns an array of vertices that are neighbouring a vertix but are not members of a ring (including bridges).
*
* @param {Number} vertexId A vertex id.
* @returns {Vertex[]} An array of vertices.
*/
getNonRingNeighbours(vertexId) {
let nrneighbours = Array();
let vertex = this.graph.vertices[vertexId];
let neighbours = vertex.neighbours;
for (var i = 0; i < neighbours.length; i++) {
let neighbour = this.graph.vertices[neighbours[i]];
let nIntersections = ArrayHelper.intersection(vertex.value.rings, neighbour.value.rings).length;
if (nIntersections === 0 && neighbour.value.isBridge == false) {
nrneighbours.push(neighbour);
}
}
return nrneighbours;
}
/**
* Annotaed stereochemistry information for visualization.
*/
annotateStereochemistry() {
let maxDepth = 10;
// For each stereo-center
for (var i = 0; i < this.graph.vertices.length; i++) {
let vertex = this.graph.vertices[i];
if (!vertex.value.isStereoCenter) {
continue;
}
let neighbours = vertex.getNeighbours();
let nNeighbours = neighbours.length;
let priorities = Array(nNeighbours);
for (var j = 0; j < nNeighbours; j++) {
let visited = new Uint8Array(this.graph.vertices.length);
let priority = Array(Array());
visited[vertex.id] = 1;
this.visitStereochemistry(neighbours[j], vertex.id, visited, priority, maxDepth, 0);
// Sort each level according to atomic number
for (var k = 0; k < priority.length; k++) {
priority[k].sort(function (a, b) {
return b - a
});
}
priorities[j] = [j, priority];
}
let maxLevels = 0;
let maxEntries = 0;
for (var j = 0; j < priorities.length; j++) {
if (priorities[j][1].length > maxLevels) {
maxLevels = priorities[j][1].length;
}
for (var k = 0; k < priorities[j][1].length; k++) {
if (priorities[j][1][k].length > maxEntries) {
maxEntries = priorities[j][1][k].length;
}
}
}
for (var j = 0; j < priorities.length; j++) {
let diff = maxLevels - priorities[j][1].length;
for (var k = 0; k < diff; k++) {
priorities[j][1].push([]);
}
// Break ties by the position in the SMILES string as per specification
priorities[j][1].push([neighbours[j]]);
// Make all same length. Fill with zeroes.
for (var k = 0; k < priorities[j][1].length; k++) {
let diff = maxEntries - priorities[j][1][k].length;
for (var l = 0; l < diff; l++) {
priorities[j][1][k].push(0);
}
}
}
priorities.sort(function (a, b) {
for (var j = 0; j < a[1].length; j++) {
for (var k = 0; k < a[1][j].length; k++) {
if (a[1][j][k] > b[1][j][k]) {
return -1;
} else if (a[1][j][k] < b[1][j][k]) {
return 1;
}
}
}
return 0;
});
let order = new Uint8Array(nNeighbours);
for (var j = 0; j < nNeighbours; j++) {
order[j] = priorities[j][0];
vertex.value.priority = j;
}
// Check the angles between elements 0 and 1, and 0 and 2 to determine whether they are
// drawn cw or ccw
// TODO: OC(Cl)=[C@]=C(C)F currently fails here, however this is, IMHO, not a valid SMILES.
let posA = this.graph.vertices[neighbours[order[0]]].position;
let posB = this.graph.vertices[neighbours[order[1]]].position;
// let posC = this.graph.vertices[neighbours[order[2]]].position;
let cwA = posA.relativeClockwise(posB, vertex.position);
// let cwB = posA.relativeClockwise(posC, vertex.position);
// If the second priority is clockwise from the first, the ligands are drawn clockwise, since
// The hydrogen can be drawn on either side
let isCw = cwA === -1;
let rotation = vertex.value.bracket.chirality === '@' ? -1 : 1;
let rs = MathHelper.parityOfPermutation(order) * rotation === 1 ? 'R' : 'S';
// Flip the hydrogen direction when the drawing doesn't match the chirality.
let wedgeA = 'down';
let wedgeB = 'up';
if (isCw && rs !== 'R' || !isCw && rs !== 'S') {
vertex.value.hydrogenDirection = 'up';
wedgeA = 'up';
wedgeB = 'down';
}
if (vertex.value.hasHydrogen) {
this.graph.getEdge(vertex.id, neighbours[order[order.length - 1]]).wedge = wedgeA;
}
// Get the shortest subtree to flip up / down. Ignore lowest priority
// The rules are following:
// 1. Do not draw wedge between two stereocenters
// 2. Heteroatoms
// 3. Draw outside ring
// 4. Shortest subtree
let wedgeOrder = new Array(neighbours.length - 1);
let showHydrogen = vertex.value.rings.length > 1 && vertex.value.hasHydrogen;
let offset = vertex.value.hasHydrogen ? 1 : 0;
for (var j = 0; j < order.length - offset; j++) {
wedgeOrder[j] = new Uint32Array(2);
let neighbour = this.graph.vertices[neighbours[order[j]]];
wedgeOrder[j][0] += neighbour.value.isStereoCenter ? 0 : 100000;
// wedgeOrder[j][0] += neighbour.value.rings.length > 0 ? 0 : 10000;
// Only add if in same ring, unlike above
wedgeOrder[j][0] += this.areVerticesInSameRing(neighbour, vertex) ? 0 : 10000;
wedgeOrder[j][0] += neighbour.value.isHeteroAtom() ? 1000 : 0;
wedgeOrder[j][0] -= neighbour.value.subtreeDepth === 0 ? 1000 : 0;
wedgeOrder[j][0] += 1000 - neighbour.value.subtreeDepth;
wedgeOrder[j][1] = neighbours[order[j]];
}
wedgeOrder.sort(function (a, b) {
if (a[0] > b[0]) {
return -1;
} else if (a[0] < b[0]) {
return 1;
}
return 0;
});
// If all neighbours are in a ring, do not draw wedge, the hydrogen will be drawn.
if (!showHydrogen) {
let wedgeId = wedgeOrder[0][1];
if (vertex.value.hasHydrogen) {
this.graph.getEdge(vertex.id, wedgeId).wedge = wedgeB;
} else {
let wedge = wedgeB;
for (var j = order.length - 1; j >= 0; j--) {
if (wedge === wedgeA) {
wedge = wedgeB;
} else {
wedge = wedgeA;
}
if (neighbours[order[j]] === wedgeId) {
break;
}
}
this.graph.getEdge(vertex.id, wedgeId).wedge = wedge;
}
}
vertex.value.chirality = rs;
}
}
/**
*
*
* @param {Number} vertexId The id of a vertex.
* @param {(Number|null)} previousVertexId The id of the parent vertex of the vertex.
* @param {Uint8Array} visited An array containing the visited flag for all vertices in the graph.
* @param {Array} priority An array of arrays storing the atomic numbers for each level.
* @param {Number} maxDepth The maximum depth.
* @param {Number} depth The current depth.
*/
visitStereochemistry(vertexId, previousVertexId, visited, priority, maxDepth, depth, parentAtomicNumber = 0) {
visited[vertexId] = 1;
let vertex = this.graph.vertices[vertexId];
let atomicNumber = vertex.value.getAtomicNumber();
if (priority.length <= depth) {
priority.push(Array());
}
for (var i = 0; i < this.graph.getEdge(vertexId, previousVertexId).weight; i++) {
priority[depth].push(parentAtomicNumber * 1000 + atomicNumber);
}
let neighbours = this.graph.vertices[vertexId].neighbours;
for (var i = 0; i < neighbours.length; i++) {
if (visited[neighbours[i]] !== 1 && depth < maxDepth - 1) {
this.visitStereochemistry(neighbours[i], vertexId, visited.slice(), priority, maxDepth, depth + 1, atomicNumber);
}
}
// Valences are filled with hydrogens and passed to the next level.
if (depth < maxDepth - 1) {
let bonds = 0;
for (var i = 0; i < neighbours.length; i++) {
bonds += this.graph.getEdge(vertexId, neighbours[i]).weight;
}
for (var i = 0; i < vertex.value.getMaxBonds() - bonds; i++) {
if (priority.length <= depth + 1) {
priority.push(Array());
}
priority[depth + 1].push(atomicNumber * 1000 + 1);
}
}
}
/**
* Creates pseudo-elements (such as Et, Me, Ac, Bz, ...) at the position of the carbon sets
* the involved atoms not to be displayed.
*/
initPseudoElements() {
for (var i = 0; i < this.graph.vertices.length; i++) {
const vertex = this.graph.vertices[i];
const neighbourIds = vertex.neighbours;
let neighbours = Array(neighbourIds.length);
for (var j = 0; j < neighbourIds.length; j++) {
neighbours[j] = this.graph.vertices[neighbourIds[j]];
}
// Ignore atoms that have less than 3 neighbours, except if
// the vertex is connected to a ring and has two neighbours
if (vertex.getNeighbourCount() < 3 || vertex.value.rings.length > 0) {
continue;
}
// TODO: This exceptions should be handled more elegantly (via config file?)
// Ignore phosphates (especially for triphosphates)
if (vertex.value.element === 'P') {
continue;
}
// Ignore also guanidine
if (vertex.value.element === 'C' && neighbours.length === 3 &&
neighbours[0].value.element === 'N' && neighbours[1].value.element === 'N' && neighbours[2].value.element === 'N') {
continue;
}
// Continue if there are less than two heteroatoms
// or if a neighbour has more than 1 neighbour
let heteroAtomCount = 0;
let ctn = 0;
for (var j = 0; j < neighbours.length; j++) {
let neighbour = neighbours[j];
let neighbouringElement = neighbour.value.element;
let neighbourCount = neighbour.getNeighbourCount();
if (neighbouringElement !== 'C' && neighbouringElement !== 'H' &&
neighbourCount === 1) {
heteroAtomCount++;
}
if (neighbourCount > 1) {
ctn++;
}
}
if (ctn > 1 || heteroAtomCount < 2) {
continue;
}
// Get the previous atom (the one which is not terminal)
let previous = null;
for (var j = 0; j < neighbours.length; j++) {
let neighbour = neighbours[j];
if (neighbour.getNeighbourCount() > 1) {
previous = neighbour;
}
}
for (var j = 0; j < neighbours.length; j++) {
let neighbour = neighbours[j];
if (neighbour.getNeighbourCount() > 1) {
continue;
}
if (this.opts.compactDrawing) {
neighbour.value.isDrawn = false;
}
let hydrogens = Atom.maxBonds[neighbour.value.element] - neighbour.value.bondCount;
let charge = '';
if (neighbour.value.bracket) {
hydrogens = neighbour.value.bracket.hcount;
charge = neighbour.value.bracket.charge || 0;
}
if (this.opts.compactDrawing) {
vertex.value.attachPseudoElement(neighbour.value.element, previous ? previous.value.element : null, hydrogens, charge);
} else {
vertex.value.hasPseudoElements = true;
}
}
}
// The second pass
for (var i = 0; i < this.graph.vertices.length; i++) {
const vertex = this.graph.vertices[i];
const atom = vertex.value;
const element = atom.element;
if (element === 'C' || element === 'H' || !atom.isDrawn) {
continue;
}
const neighbourIds = vertex.neighbours;
let neighbours = Array(neighbourIds.length);
for (var j = 0; j < neighbourIds.length; j++) {
neighbours[j] = this.graph.vertices[neighbourIds[j]];
}
for (var j = 0; j < neighbours.length; j++) {
let neighbour = neighbours[j].value;
if (!neighbour.hasAttachedPseudoElements || neighbour.getAttachedPseudoElementsCount() !== 2) {
continue;
}
const pseudoElements = neighbour.getAttachedPseudoElements();
if (pseudoElements.hasOwnProperty('0O') && pseudoElements.hasOwnProperty('3C')) {
neighbour.isDrawn = false;
vertex.value.attachPseudoElement('Ac', '', 0);
}
}
}
}
}
export default Drawer; | the_stack |
import {
ArgumentValue,
CdmAttributeReference,
CdmCorpusContext,
CdmDocumentDefinition,
CdmDataTypeDefinition,
CdmDataTypeReference,
CdmObject,
CdmObjectBase,
CdmObjectReferenceBase,
cdmObjectSimple,
cdmObjectType,
cdmLogCode,
Logger,
resolveContext,
resolveOptions,
VisitCallback
} from '../internal';
export class CdmParameterDefinition extends cdmObjectSimple implements CdmParameterDefinition {
private TAG: string = CdmParameterDefinition.name;
public explanation: string;
public name: string;
public defaultValue: ArgumentValue;
public required: boolean;
public dataTypeRef: CdmDataTypeReference;
public static get objectType(): cdmObjectType {
return cdmObjectType.parameterDef;
}
constructor(ctx: CdmCorpusContext, name: string) {
super(ctx);
// let bodyCode = () =>
{
this.name = name;
this.objectType = cdmObjectType.parameterDef;
}
// return p.measure(bodyCode);
}
public getObjectType(): cdmObjectType {
// let bodyCode = () =>
{
return cdmObjectType.parameterDef;
}
// return p.measure(bodyCode);
}
public copy(resOpt?: resolveOptions, host?: CdmObject): CdmObject {
// let bodyCode = () =>
{
if (!resOpt) {
resOpt = new resolveOptions(this, this.ctx.corpus.defaultResolutionDirectives);
}
let copy: CdmParameterDefinition;
if (!host) {
copy = new CdmParameterDefinition(this.ctx, this.name);
} else {
copy = host as CdmParameterDefinition;
copy.ctx = this.ctx;
copy.name = this.name;
}
let defVal: ArgumentValue;
if (this.defaultValue) {
if (typeof (this.defaultValue) === 'object' && 'copy' in this.defaultValue
&& typeof (this.defaultValue.copy) === 'function') {
defVal = this.defaultValue.copy(resOpt);
} else if (typeof (this.defaultValue) === 'object') {
defVal = { ...this.defaultValue };
} else {
defVal = this.defaultValue;
}
}
copy.explanation = this.explanation;
copy.defaultValue = defVal;
copy.required = this.required;
copy.dataTypeRef = this.dataTypeRef ? this.dataTypeRef.copy(resOpt) as CdmDataTypeReference : undefined;
return copy;
}
// return p.measure(bodyCode);
}
public validate(): boolean {
// let bodyCode = () =>
{
if (!this.name) {
let missingFields: string[] = ['name'];
Logger.error(this.ctx, this.TAG, this.validate.name, this.atCorpusPath, cdmLogCode.ErrValdnIntegrityCheckFailure, missingFields.map((s: string) => `'${s}'`).join(', '), this.atCorpusPath);
return false;
}
return true;
}
// return p.measure(bodyCode);
}
public getExplanation(): string {
// let bodyCode = () =>
{
return this.explanation;
}
// return p.measure(bodyCode);
}
public getName(): string {
// let bodyCode = () =>
{
return this.name;
}
// return p.measure(bodyCode);
}
public isDerivedFrom(baseDef: string, resOpt?: resolveOptions) {
return false;
}
public getDefaultValue(): ArgumentValue {
// let bodyCode = () =>
{
return this.defaultValue;
}
// return p.measure(bodyCode);
}
public getRequired(): boolean {
// let bodyCode = () =>
{
return this.required;
}
// return p.measure(bodyCode);
}
/**
* @internal
*/
public constTypeCheck(
resOpt: resolveOptions,
wrtDoc: CdmDocumentDefinition,
argumentValue: ArgumentValue
): ArgumentValue {
// let bodyCode = () =>
{
const ctx: resolveContext = this.ctx as resolveContext;
let replacement: ArgumentValue = argumentValue;
// if parameter type is entity, then the value should be an entity or ref to one
// same is true of 'dataType' dataType
if (!this.dataTypeRef) {
return replacement;
}
const dt: CdmDataTypeDefinition = this.dataTypeRef.fetchObjectDefinition(resOpt);
if (!dt) {
Logger.error(this.ctx, this.TAG, this.constTypeCheck.name, this.atCorpusPath, cdmLogCode.ErrUnrecognizedDataType, this.name);
return undefined;
}
// compare with passed in value or default for parameter
let pValue: ArgumentValue = argumentValue;
if (!pValue) {
pValue = this.getDefaultValue();
replacement = pValue;
}
if (pValue) {
if (dt.isDerivedFrom('cdmObject', resOpt)) {
const expectedTypes: cdmObjectType[] = [];
let expected: string;
if (dt.isDerivedFrom('entity', resOpt)) {
expectedTypes.push(cdmObjectType.constantEntityDef);
expectedTypes.push(cdmObjectType.entityRef);
expectedTypes.push(cdmObjectType.entityDef);
expectedTypes.push(cdmObjectType.projectionDef);
expected = 'entity';
} else if (dt.isDerivedFrom('attribute', resOpt)) {
expectedTypes.push(cdmObjectType.attributeRef);
expectedTypes.push(cdmObjectType.typeAttributeDef);
expectedTypes.push(cdmObjectType.entityAttributeDef);
expected = 'attribute';
} else if (dt.isDerivedFrom('dataType', resOpt)) {
expectedTypes.push(cdmObjectType.dataTypeRef);
expectedTypes.push(cdmObjectType.dataTypeDef);
expected = 'dataType';
} else if (dt.isDerivedFrom('purpose', resOpt)) {
expectedTypes.push(cdmObjectType.purposeRef);
expectedTypes.push(cdmObjectType.purposeDef);
expected = 'purpose';
} else if (dt.isDerivedFrom('trait', resOpt)) {
expectedTypes.push(cdmObjectType.traitRef);
expectedTypes.push(cdmObjectType.traitDef);
expected = 'trait';
} else if (dt.isDerivedFrom('traitGroup', resOpt)) {
expectedTypes.push(cdmObjectType.traitGroupRef);
expectedTypes.push(cdmObjectType.traitGroupDef);
expected = 'traitGroup';
} else if (dt.isDerivedFrom('attributeGroup', resOpt)) {
expectedTypes.push(cdmObjectType.attributeGroupRef);
expectedTypes.push(cdmObjectType.attributeGroupDef);
expected = 'attributeGroup';
}
if (expectedTypes.length === 0) {
Logger.error(this.ctx, this.TAG, this.constTypeCheck.name, wrtDoc.atCorpusPath, cdmLogCode.ErrUnexpectedDataType, this.getName());
}
// if a string constant, resolve to an object ref.
let foundType: cdmObjectType = cdmObjectType.error;
if (typeof pValue === 'object' && 'objectType' in pValue) {
foundType = pValue.objectType;
}
let foundDesc: string = ctx.relativePath;
if (!(pValue instanceof CdmObjectBase)) {
// pValue is a string or object
pValue = pValue as string;
if (pValue === 'this.attribute' && expected === 'attribute') {
// will get sorted out later when resolving traits
foundType = cdmObjectType.attributeRef;
} else {
foundDesc = pValue;
const seekResAtt: number = CdmObjectReferenceBase.offsetAttributePromise(pValue);
if (seekResAtt >= 0) {
// get an object there that will get resolved later after resolved attributes
replacement = new CdmAttributeReference(this.ctx, pValue, true);
(replacement as CdmAttributeReference).inDocument = wrtDoc;
foundType = cdmObjectType.attributeRef;
} else {
const lu: CdmObjectBase = ctx.corpus.resolveSymbolReference(
resOpt,
wrtDoc,
pValue,
cdmObjectType.error,
true
);
if (lu) {
if (expected === 'attribute') {
replacement = new CdmAttributeReference(this.ctx, pValue, true);
(replacement as CdmAttributeReference).inDocument = wrtDoc;
foundType = cdmObjectType.attributeRef;
} else {
replacement = lu;
if (typeof replacement === 'object' && 'objectType' in replacement) {
foundType = replacement.objectType;
}
}
}
}
}
}
if (expectedTypes.indexOf(foundType) === -1) {
Logger.error(this.ctx, this.TAG, this.constTypeCheck.name, wrtDoc.atCorpusPath, cdmLogCode.ErrResolutionFailure, this.getName(), foundDesc, expected);
} else {
Logger.info(ctx, this.TAG, this.constTypeCheck.name, wrtDoc.atCorpusPath, `resolved '${foundDesc}'`);
}
}
}
return replacement;
}
// return p.measure(bodyCode);
}
public visit(pathFrom: string, preChildren: VisitCallback, postChildren: VisitCallback): boolean {
// let bodyCode = () =>
{
const path: string = this.fetchDeclaredPath(pathFrom);
if (preChildren && preChildren(this, path)) {
return false;
}
if (typeof (this.defaultValue) === 'object' && 'visit' in this.defaultValue
&& typeof (this.defaultValue.visit) === 'function') {
if ((this.defaultValue).visit(`${path}/defaultValue/`, preChildren, postChildren)) {
return true;
}
}
if (this.dataTypeRef) {
if (this.dataTypeRef.visit(`${path}/dataType/`, preChildren, postChildren)) {
return true;
}
}
if (postChildren && postChildren(this, path)) {
return true;
}
return false;
}
// return p.measure(bodyCode);
}
/**
* Given an initial path, returns this object's declared path
* @internal
*/
public fetchDeclaredPath(pathFrom: string): string {
return pathFrom + this.getName() ?? '';
}
} | the_stack |
'use strict';
import {DebugSession, InitializedEvent, TerminatedEvent, StoppedEvent, BreakpointEvent, OutputEvent, Thread, StackFrame, Scope, Source, Handles, Breakpoint} from 'vscode-debugadapter';
import {DebugProtocol} from 'vscode-debugprotocol';
import {readFileSync,existsSync} from 'fs';
import {basename, dirname} from 'path';
import * as net from 'net';
import * as childProcess from 'child_process';
import * as path from 'path';
import {DOMParser} from 'xmldom';
import {RubyProcess} from './ruby';
import {LaunchRequestArguments, AttachRequestArguments, IRubyEvaluationResult, IDebugVariable} from './interface';
import {SocketClientState, Mode} from './common';
import {endsWith, startsWith} from './helper';
class CachedBreakpoint implements DebugProtocol.SourceBreakpoint {
public line: number;
public column: number;
public condition: string;
public id: number;
public constructor(line: number, column?: number, condition?: string, id?: number) {
this.line = line;
this.column = column;
this.condition = condition;
this.id = id;
}
public static fromSourceBreakpoint(sourceBreakpoint: DebugProtocol.SourceBreakpoint): CachedBreakpoint {
return new CachedBreakpoint(sourceBreakpoint.line, sourceBreakpoint.column, sourceBreakpoint.condition);
}
public convertForResponse(): DebugProtocol.Breakpoint {
var result = <DebugProtocol.Breakpoint> new Breakpoint(true, this.line, this.column);
result.id = this.id;
return result;
}
}
class RubyDebugSession extends DebugSession {
private _breakpointId = 1000;
private _threadId = 2;
private _frameId = 0;
private _firstSuspendReceived = false;
private _activeFileData = new Map<string, string[]>();
private _existingBreakpoints = new Map<string, CachedBreakpoint[]>();
private _variableHandles: Handles<IDebugVariable>;
private rubyProcess: RubyProcess;
private requestArguments: any;
private debugMode: Mode;
private skipFiles: RegExp[];
private finishFiles: RegExp[];
/**
* Creates a new debug adapter.
* We configure the default implementation of a debug adapter here
* by specifying this this 'debugger' uses zero-based lines and columns.
*/
public constructor() {
super();
this.setDebuggerLinesStartAt1(true);
this.setDebuggerColumnsStartAt1(false);
this._variableHandles = new Handles<IDebugVariable>();
}
/**
* The 'initialize' request is the first request called by the frontend
* to interrogate the features the debug adapter provides.
*/
protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
// This debug adapter implements the configurationDoneRequest.
response.body.supportsConfigurationDoneRequest = true;
//response.body.supportsFunctionBreakpoints = true;
response.body.supportsConditionalBreakpoints = true;
this.sendResponse(response);
}
protected setupProcessHanlders() {
this.rubyProcess.on('debuggerComplete', () => {
this.sendEvent(new TerminatedEvent());
}).on('debuggerProcessExit', () => {
this.sendEvent(new TerminatedEvent());
}).on('executableOutput', (data: Buffer) => {
this.sendEvent(new OutputEvent(data.toString(), 'stdout'));
}).on('executableStdErr', (error: Buffer) => {
this.sendEvent(new OutputEvent(error.toString(), 'stderr'));
}).on('nonTerminalError', (error: string) => {
this.sendEvent(new OutputEvent("Debugger error: " + error + '\n', 'stderr'));
}).on('breakpoint', result => {
this.sendEvent(new StoppedEvent('breakpoint', result.threadId));
}).on('exception', result => {
this.sendEvent(new OutputEvent("\nException raised: [" + result.type + "]: " + result.message + "\n",'stderr'));
this.sendEvent(new StoppedEvent('exception', result.threadId, result.type + ": " + result.message));
}).on('terminalError', (error: string) => {
this.sendEvent(new OutputEvent("Debugger terminal error: " + error))
this.sendEvent(new TerminatedEvent());
});
}
private printToConsole(line: String): void {
this.sendEvent(new OutputEvent(`${line}\n`, 'console'));
}
private constructRegExps(strings: string[]): RegExp[] {
if (strings === undefined || strings === null || strings.length === 0) {
return [];
} else {
return strings.map(x => new RegExp(x));
}
}
private stackFrameGetsSpecialTreatment(regexes: RegExp[], file: string): boolean {
return regexes.findIndex(re => re.test(file)) > -1;
}
protected launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments): void {
this.debugMode = Mode.launch;
this.requestArguments = args;
this.rubyProcess = new RubyProcess(Mode.launch, args);
this.setupOptionalOutputHandlers();
this.skipFiles = this.constructRegExps(args.skipFiles);
this.finishFiles = this.constructRegExps(args.finishFiles);
this.rubyProcess.on('debuggerConnect', () => {
this.sendEvent(new InitializedEvent());
this.sendResponse(response);
}).on('suspended', result => {
if ( args.stopOnEntry && !this._firstSuspendReceived ) {
this.sendEvent(new StoppedEvent('entry', result.threadId));
}
else {
this.onSuspended(result);
}
this._firstSuspendReceived = true;
});
this.setupProcessHanlders();
}
protected attachRequest(response: DebugProtocol.AttachResponse, args: AttachRequestArguments): void {
this.debugMode = Mode.attach;
this.requestArguments = args;
this.rubyProcess = new RubyProcess(Mode.attach, args);
this.setupOptionalOutputHandlers();
this.skipFiles = this.constructRegExps(args.skipFiles);
this.finishFiles = this.constructRegExps(args.finishFiles);
this.rubyProcess.on('debuggerConnect', () => {
this.sendEvent(new InitializedEvent());
this.sendResponse(response);
}).on('suspended', result => {
this.onSuspended(result);
});
this.setupProcessHanlders();
}
protected setupOptionalOutputHandlers(): void {
if (this.requestArguments.showDebuggerOutput) {
this.rubyProcess.on('debuggerOutput', (data: Buffer) => {
this.printToConsole(data.toString());
});
}
if (this.requestArguments.showDebuggerCommands) {
this.rubyProcess.on('debuggerCommands', (data: Buffer) => {
this.printToConsole(data.toString());
});
}
}
protected onSuspended(suspendMetadataFromRuby: any): void {
const currentFile = suspendMetadataFromRuby.file;
// If the file matches a regex in both, favor finish over skip.
const shouldFinish = this.stackFrameGetsSpecialTreatment(this.finishFiles, currentFile);
const shouldSkip = !shouldFinish && this.stackFrameGetsSpecialTreatment(this.skipFiles, currentFile);
if (shouldFinish || shouldSkip) {
// This will trigger a subsequent 'suspend' event - as a result, we'll keep stepping until we
// reach a non-skipped file.
this.rubyProcess.Run(shouldSkip ? 'step' : 'finish');
// Don't send the StoppedEvent - that will happen on a subsequent suspended event (one that
// doesn't get special treatment) in the else clause below.
} else {
this.sendEvent(new StoppedEvent('step', suspendMetadataFromRuby.threadId));
}
}
// Executed after all breakpints have been set by VS Code
protected configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse, args:
DebugProtocol.ConfigurationDoneArguments): void {
this.rubyProcess.Run('start');
this.sendResponse(response);
}
protected setExceptionBreakPointsRequest(response: DebugProtocol.SetExceptionBreakpointsResponse, args: DebugProtocol.SetExceptionBreakpointsArguments): void {
if (args.filters.indexOf('all') >=0){
//Exception is the root of all (Ruby) exceptions - this is the best we can do
//If someone makes their own exception class and doesn't inherit from
//Exception, then they really didn't expect things to work properly
//anyway.
//We don't do anything with the return from this, but we
//have to add an expectation for the output.
this.rubyProcess.Enqueue('catch Exception').then(()=>1);
}
else {
this.rubyProcess.Run('catch off');
}
this.sendResponse(response);
}
protected setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments): void {
var key = this.convertClientPathToKey(args.source.path);
var existingBreakpoints = this._existingBreakpoints.get(key) || [];
var requestedBreakpoints = args.breakpoints.map(bp => CachedBreakpoint.fromSourceBreakpoint(bp));
var existingLines = existingBreakpoints.map(bp => bp.line);
var requestedLines = requestedBreakpoints.map(bp => bp.line);
var breakpointsToRemove = existingBreakpoints.filter(bp => requestedLines.indexOf(bp.line) < 0);
var breakpointsToAdd = requestedBreakpoints.filter(bp => existingLines.indexOf(bp.line) < 0);
var addRemovePromises = [];
// Handle the removal of old breakpoints.
if (breakpointsToRemove.length > 0) {
var linesToRemove = breakpointsToRemove.map(bp => bp.line);
existingBreakpoints = existingBreakpoints.filter(bp => linesToRemove.indexOf(bp.line) < 0);
this._existingBreakpoints.set(key, existingBreakpoints);
var removePromises = breakpointsToRemove.map(bp => this.rubyProcess.Enqueue('delete ' + bp.id));
addRemovePromises.push(Promise.all(removePromises).then(results => {
let removedIds = results.map(attr => +attr.no);
let unremovedBreakpoints = breakpointsToRemove.filter(bp => removedIds.indexOf(bp.id) < 0);
console.assert(unremovedBreakpoints.length == 0);
}));
}
// Handle the addition of new breakpoints.
if (breakpointsToAdd.length > 0) {
var path = this.convertClientPathToDebugger(args.source.path);
var addPromises = breakpointsToAdd.map(bp => {
let command = 'break ' + path + ':' + bp.line;
if (bp.condition) command += ' if ' + bp.condition;
return this.rubyProcess.Enqueue(command);
});
addRemovePromises.push(Promise.all(addPromises).then(results => {
var addedBreakpoints = results.map(attr => {
var line = +(attr.location + '').split(':').pop();
var id = +attr.no;
return new CachedBreakpoint(line, null, null, id);
});
console.assert(addedBreakpoints.length == breakpointsToAdd.length);
for (let index = 0; index < addedBreakpoints.length; ++index) {
console.assert(addedBreakpoints[index].line == breakpointsToAdd[index].line);
breakpointsToAdd[index].id = addedBreakpoints[index].id;
}
existingBreakpoints = existingBreakpoints.concat(breakpointsToAdd);
this._existingBreakpoints.set(key, existingBreakpoints);
}));
}
// Once all requested breakpoints are added and removed (if any), send a single response.
Promise.all(addRemovePromises).then(_ => {
response.body = {
breakpoints: existingBreakpoints.map(bp => bp.convertForResponse())
};
this.sendResponse(response);
});
}
protected threadsRequest(response: DebugProtocol.ThreadsResponse): void {
this.rubyProcess.Enqueue('thread list').then(results => {
if (results && results.length > 0) {
this._threadId = results[0].id;
}
response.body = {
threads: results.map(thread => new Thread(+thread.id,'Thread ' + thread.id))
};
this.sendResponse(response);
});
}
// Called by VS Code after a StoppedEvent
/** StackTrace request; value of command field is 'stackTrace'.
The request returns a stacktrace from the current execution state.
*/
protected stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments): void {
this.rubyProcess.Enqueue('where').then(results => {
//drop rdbug frames or user-specified skipped files
let skipped = false;
results = results.filter(stack => {
// drop rdbug frames
if (endsWith(stack.file, '/rdebug-ide', null) || endsWith(stack.file, '/ruby-debug-ide.rb', null)) {
return false;
}
// drop frames from user-specified skipFiles. Don't drop frames from finishFiles - either the user
// has no breakpoints down-stack from them so they never appear, or the user does have such breakpoints
// and probably wants to see these frames.
if (this.stackFrameGetsSpecialTreatment(this.skipFiles, stack.file)) {
skipped = true;
return false;
}
return true;
});
//get the current frame
results.some(stack=> stack.current ? this._frameId = +stack.no: 0);
//only read the file if we don't have it already
results.forEach(stack=>{
const filePath = this.convertDebuggerPathToClient(stack.file);
if (!this._activeFileData.has(filePath) && existsSync(filePath)) {
this._activeFileData.set(filePath, readFileSync(filePath,'utf8').split('\n'))
}
});
response.body = {
stackFrames: results.filter(stack=>stack.file.indexOf('debug-ide')<0&&+stack.line>0)
.map(stack => {
const filePath = this.convertDebuggerPathToClient(stack.file);
const fileData = this._activeFileData.get(filePath);
const gemFilePaths = filePath.split('/gems/');
const gemFilePath = gemFilePaths[gemFilePaths.length-1];
return new StackFrame(+stack.no,
fileData ? fileData[+stack.line-1].trim() : (gemFilePath+':'+stack.line),
fileData ? new Source(basename(stack.file), filePath) : null,
this.convertDebuggerLineToClient(+stack.line), 0);
})
};
if (response.body.stackFrames.length){
this.sendResponse(response);
} else if (skipped) {
// If the stack was empty because of skipFiles, display a synthetic frame to let the user know
response.body.stackFrames = [
new StackFrame(0, "[all frames filtered by skipFiles in extension config]", null, 0)
];
this.sendResponse(response);
} else {
// If the stack was empty and we didn't honor any skipFiles, something is wrong. Give up.
this.sendEvent(new TerminatedEvent());
}
return;
});
}
protected convertClientPathToKey(localPath: string): string {
return localPath.replace(/\\/g, '/');
}
private isSubPath(subPath: string): boolean {
return subPath && !subPath.startsWith('..') && !path.isAbsolute(subPath);
}
private getPathImplementation(pathToCheck: string): any {
if (pathToCheck) {
if (pathToCheck.indexOf(path.posix.sep) >= 0) {
return path.posix;
} else if (pathToCheck.indexOf(path.win32.sep) >= 0) {
return path.win32;
}
}
return path;
}
protected convertClientPathToDebugger(localPath: string): string {
if (this.debugMode === Mode.launch) {
return localPath;
}
let relativeLocalPath = path.relative(this.requestArguments.cwd, localPath);
if (!this.isSubPath(relativeLocalPath)) {
return localPath;
}
let remoteWorkspaceRoot =
this.requestArguments.remoteWorkspaceRoot || this.requestArguments.cwd;
let remotePathImplementation = this.getPathImplementation(remoteWorkspaceRoot);
let localPathImplementation = this.getPathImplementation(this.requestArguments.cwd);
let relativePath = remotePathImplementation.join.apply(
null,
[remoteWorkspaceRoot].concat(relativeLocalPath.split(localPathImplementation.sep))
);
return relativePath;
}
protected convertDebuggerPathToClient(serverPath: string): string {
if (this.debugMode === Mode.launch) {
return serverPath;
}
let remoteWorkspaceRoot =
this.requestArguments.remoteWorkspaceRoot || this.requestArguments.cwd;
let remotePathImplementation = this.getPathImplementation(remoteWorkspaceRoot);
let localPathImplementation = this.getPathImplementation(this.requestArguments.cwd);
let relativeRemotePath = remotePathImplementation.relative(remoteWorkspaceRoot, serverPath);
if (!this.isSubPath(relativeRemotePath)) {
return serverPath;
}
let relativePath = localPathImplementation.join.apply(
null,
[this.requestArguments.cwd].concat(relativeRemotePath.split(remotePathImplementation.sep))
);
return relativePath;
}
protected switchFrame(frameId) {
if (frameId === this._frameId) return;
this._frameId = frameId;
this.rubyProcess.Run('frame ' + frameId)
}
protected varyVariable(variable){
if (variable.type === 'String') {
variable.hasChildren = false;
variable.value = "'" + variable.value.replace(/'/g,"\\'") + "'";
}
else if ( variable.value && startsWith(variable.value, '#<' + variable.type, 0)){
variable.value = variable.type;
}
return variable;
}
protected buildEvaluateName(variable, parentsPath?: string, parentType?: string) {
if (variable.kind === 'class') {
return `${parentsPath}.class.class_variable_get('${variable.name}')`;
} else if (parentType === 'Array') {
return `${parentsPath}${variable.name}`;
} else if (parentType === 'Hash') {
return `${parentsPath}[:${variable.name}]`;
} else if (parentsPath && variable.kind === 'instance') {
return `${parentsPath}.instance_variable_get('${variable.name}')`;
} else {
return variable.name;
}
}
protected createVariableReference(variables, parentsPath?: string, parentType?: string): IRubyEvaluationResult[] {
if (!Array.isArray(variables)) {
variables = [];
}
return variables.map(this.varyVariable).map(variable => {
const evaluateName = this.buildEvaluateName(variable, parentsPath, parentType);
return {
name: variable.name,
kind: variable.kind,
type: variable.type,
value: variable.value === undefined ? 'undefined' : variable.value,
id: variable.objectId,
evaluateName: evaluateName,
variablesReference:
variable.hasChildren === 'true'
? this._variableHandles.create({
objectId: variable.objectId,
variableName: evaluateName,
variableType: variable.type,
})
: 0,
};
});
}
/** Scopes request; value of command field is 'scopes'.
The request returns the variable scopes for a given stackframe ID.
*/
protected scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments): void {
//this doesn't work properly across threads.
this.switchFrame(args.frameId);
Promise.all([
this.rubyProcess.Enqueue('var local'),
this.rubyProcess.Enqueue('var global')
])
.then( results =>{
const scopes = new Array<Scope>();
scopes.push(new Scope('Local',this._variableHandles.create({variables:this.createVariableReference(results[0])}),false));
scopes.push(new Scope('Global',this._variableHandles.create({variables:this.createVariableReference(results[1])}),false));
response.body = {
scopes: scopes
};
this.sendResponse(response);
});
}
protected variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments): void {
var varRef = this._variableHandles.get(args.variablesReference);
let varPromise;
if (varRef.objectId) {
varPromise = this.rubyProcess.Enqueue('var i ' + varRef.objectId).then(results => this.createVariableReference(results, varRef.variableName, varRef.variableType));
}
else {
varPromise = Promise.resolve(varRef.variables);
}
varPromise.then(variables =>{
response.body = {
variables: variables
};
this.sendResponse(response);
});
}
protected continueRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments): void {
this.sendResponse(response);
this.rubyProcess.Run('c');
}
protected nextRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments): void {
this.sendResponse(response);
this.rubyProcess.Run('next');
}
protected stepInRequest(response: DebugProtocol.StepInResponse): void {
this.sendResponse(response);
this.rubyProcess.Run('step');
}
protected pauseRequest(response: DebugProtocol.PauseResponse): void{
this.sendResponse(response);
this.rubyProcess.Run('pause');
}
protected stepOutRequest(response: DebugProtocol.StepInResponse): void {
this.sendResponse(response);
//Not sure which command we should use, `finish` will execute all frames.
this.rubyProcess.Run('finish');
}
/** Evaluate request; value of command field is 'evaluate'.
Evaluates the given expression in the context of the top most stack frame.
The expression has access to any variables and arguments this are in scope.
*/
protected evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments): void {
// TODO: this will often not work. Will try to call
// Class.@variable which doesn't work.
// need to tie it to the existing variablesReference set
// That will required having ALL variables stored, which will also (hopefully) fix
// the variable value mismatch between threads
this.rubyProcess.Enqueue("eval " + args.expression).then(result => {
response.body = {
result: result.value
? result.value
: (result.length > 0 && result[0].value
? result[0].value
: "Not available"),
variablesReference: 0,
};
this.sendResponse(response);
});
}
protected disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments) {
if (this.rubyProcess.state !== SocketClientState.closed) {
this.rubyProcess.Run('quit');
}
this.sendResponse(response);
}
}
DebugSession.run(RubyDebugSession); | the_stack |
import { NodePath, PluginObj, Visitor, transformAsync, transformSync } from '@babel/core'
import groupBy from 'lodash.groupby'
import { InsertNodePreload, OpType, Point, RequestData } from '../../index'
import { createLineContentsByContent, LineContents, Range } from '../../utils/line-contents'
const sideEffectImportVisitor = {
ImportDeclaration(path, state) {
if (!path.get('specifiers')?.length) {
state.result.set(path.get('source').node.value, path)
}
state.startImportLoc = state.startImportLoc ?? path.node.loc
state.endImportLoc = path.node.loc
path.skip()
}
} as Visitor<SideEffectImportVisitorState>
type SideEffectImportVisitorState = { result: Map<string, NodePath>; startImportLoc: Range; endImportLoc: Range }
type DeepPartial<T> = {
[P in keyof T]?: DeepPartial<T[P]>
}
type Config = {
esModule?: boolean
}
const parserOptsPlugins: any[] = [
'jsx',
'asyncDoExpressions',
'asyncGenerators',
'bigInt',
'classPrivateMethods',
'classPrivateProperties',
'classProperties',
'classStaticBlock',
'decimal',
'decorators-legacy',
'doExpressions',
'dynamicImport',
'exportDefaultFrom',
'exportNamespaceFrom',
'functionBind',
'functionSent',
'importMeta',
'logicalAssignment',
'importAssertions',
'moduleBlocks',
'moduleStringNames',
'nullishCoalescingOperator',
'numericSeparator',
'objectRestSpread',
'optionalCatchBinding',
'optionalChaining',
'partialApplication',
'placeholders',
'privateIn',
'throwExpressions',
'topLevelAwait',
'typescript'
]
const replaceCodePlugin = ({ types: t }) => {
const handleIdentifier = (path: NodePath<any>, opts: any, rawCode: string) => {
opts.output.code = opts.output.code ?? rawCode
opts.state = opts.state ?? {
deltaOffset: 0
}
const prevCode = opts.output.code
if (opts.input.validData && Reflect.has(opts.input.validData, path.node.name)) {
const oldVal = path.node.name
const newVal = opts.input.validData[path.node.name]
const deltaOffset = opts.state.deltaOffset
opts.output.code =
prevCode.slice(0, path.node.start + deltaOffset) +
opts.input.validData[path.node.name] +
prevCode.slice(path.node.end + deltaOffset)
opts.state.deltaOffset += newVal.length - oldVal.length
}
}
return {
visitor: {
Program(p, { opts }) {},
JSXIdentifier(path, { opts }) {
// @ts-ignore
handleIdentifier(path, opts, this.file.code)
},
Identifier(path, { opts }) {
// @ts-ignore
handleIdentifier(path, opts, this.file.code)
}
}
} as PluginObj<{
opts: {
input: {
validData: Record<string, string>
}
output: {
code?: string
}
}
}>
}
const importPlugin = ({ types: t }) =>
({
visitor: {
Program(path, state) {
const { material, pos, ops, config } = state.opts
const { esModule = true } = config || {}
// @ts-ignore
const rawCode = this.file.code
// @ts-ignore
const lineContents = createLineContentsByContent(rawCode, { filename: this.filename })
const getText = ({ start, end }) => {
const arr = lineContents.locateByRange({
start,
end
})
return arr
.map(({ lineNumber, line, start, end }) => {
return line.toString()
})
.join('\n')
}
const sideEffectImportVisitorState = {
result: new Map(),
endImportLoc: { end: { line: 1, column: 0 }, start: { line: 1, column: 0 } }
} as SideEffectImportVisitorState
path.traverse(sideEffectImportVisitor, sideEffectImportVisitorState)
if (material.sideEffectDependencies) {
material.sideEffectDependencies.forEach((depName) => {
if (!sideEffectImportVisitorState.result.has(depName)) {
ops.insertDeps.push({
type: OpType.INSERT_NODE,
preload: {
to: sideEffectImportVisitorState.endImportLoc.end,
data: {
newText: esModule ? `;import ${JSON.stringify(depName)};` : `;require(${JSON.stringify(depName)});`
}
}
})
}
})
}
if (material.dependencies && Object.keys(material.dependencies)?.length) {
const map = new Map<string, { path?: NodePath; name: any }>()
const namedUnionMap = new Map<string, NodePath[]>()
for (const [name, binding] of Object.entries(path.scope.bindings)) {
if (binding.kind === 'module') {
const importDecPath = binding.path.findParent((x) => x.isImportDeclaration())
if (importDecPath && (importDecPath.get('source') as any).node?.value) {
const source = (importDecPath.get('source') as any).node?.value
// @ts-ignore
const imported = binding.path.node?.imported as any
if (binding.path.isImportSpecifier() && (imported?.name ?? imported?.value) !== 'default') {
map.set(`${source}#named:${imported.name ?? imported.value}`, {
name: binding.path.node.local.name,
path: importDecPath
})
namedUnionMap.set(
source,
namedUnionMap.get(source) ? namedUnionMap.get(source).concat(importDecPath) : [importDecPath]
)
} else if (
binding.path.isImportDefaultSpecifier() ||
(imported?.name ?? imported?.value) === 'default'
) {
map.set(`${source}#default`, {
// @ts-ignore
name: binding.path.node.local.name,
path: importDecPath
})
} else if (binding.path.isImportNamespaceSpecifier()) {
map.set(`${source}#namespace`, {
name: binding.path.node.local.name,
path: importDecPath
})
}
}
}
}
const namedCache = new Map()
const getValidName = (name = 'Unknown') => {
name = name.replace(/[\/@]/g, '$')
// @ts-ignore
while (true === path.scope?.references?.[name] || namedCache.has(name)) {
name = `_${name}`
}
namedCache.set(name, true)
return name
}
const tplData = {}
const list = Object.keys(material.dependencies).map((tplName) => ({
...material.dependencies[tplName],
tplName
}))
const sourceMap = groupBy(list, 'source')
for (const [source, dataList] of Object.entries(sourceMap)) {
const modeMap = groupBy(dataList, (d) =>
d.imported === 'default' || d.mode === 'default' ? 'default' : d.mode
)
for (const [mode, dataList] of Object.entries(modeMap)) {
// @ts-ignore
if (!dataList.length) return
const cachedKey = `${source}#${mode}`
const cached = map.get(cachedKey)
if (mode === 'default') {
if (cached?.name) {
tplData[dataList[0].tplName] = cached?.name
} else {
const name = getValidName(dataList[0].local ?? dataList[0].imported ?? source)
map.set(cachedKey, { name })
tplData[dataList[0].tplName] = name
ops.insertDeps.push({
type: OpType.INSERT_NODE,
preload: {
to: sideEffectImportVisitorState.endImportLoc.end,
data: {
newText: esModule
? `;import ${name} from ${JSON.stringify(source)};`
: `;var ${name} = (function () {
var mod = require(${JSON.stringify(source)});
return mod.__esModule ? mod.default : mod
})();`
}
}
})
}
} else if (mode === 'namespace') {
if (cached?.name) {
tplData[dataList[0].tplName] = cached?.name
} else {
const name = getValidName(dataList[0].local ?? dataList[0].imported ?? source)
map.set(cachedKey, { name })
tplData[dataList[0].tplName] = name
ops.insertDeps.push({
type: OpType.INSERT_NODE,
preload: {
to: sideEffectImportVisitorState.endImportLoc.end,
data: {
newText: esModule
? `;import * as ${name} from ${JSON.stringify(source)};`
: `;var ${name} = require(${JSON.stringify(source)});`
}
}
})
}
} else if (mode === 'named') {
const newNamedPathSet = new Set<NodePath>()
const newNamedSet = new Set<{ local: string; imported: string }>()
;(dataList as any).forEach((data) => {
const key = `${cachedKey}:${data.imported}`
const cached = map.get(key)
if (cached?.name) {
tplData[data.tplName] = cached?.name
} else {
let importPath
// insert into the last importPath
if (namedUnionMap.get(source)?.length) {
importPath = namedUnionMap.get(source)[namedUnionMap.get(source)?.length - 1]
}
const name = getValidName(data.local ?? data.imported)
if (importPath) {
importPath.node.specifiers.push(
t.importSpecifier(t.identifier(name), t.identifier(data.imported))
)
}
map.set(key, { name, path: importPath })
tplData[data.tplName] = name
if (importPath) {
newNamedPathSet.add(importPath)
} else {
newNamedSet.add({
local: name,
imported: data.imported
})
}
}
})
// 在已有的 import 中进行替换
if (newNamedPathSet.size) {
for (const importPath of newNamedPathSet.values()) {
let cjsCodes = []
// @ts-ignore
importPath.node?.specifiers?.forEach((x) => {
if (x.local.name === x.imported.name) {
cjsCodes.push(x.local.name)
} else {
cjsCodes.push(`${x.imported.name}: ${x.local.name}`)
}
})
ops.insertDeps.push({
type: OpType.REPLACE_NODE,
preload: {
...importPath.node.loc,
text: getText(importPath.node.loc),
data: {
newText: (esModule
? `;${importPath.toString()};`
: // @ts-ignore
`;var { ${cjsCodes.join(',')} } = require(${importPath.node.source.value});`
).replace(/;+$/, ';')
}
}
})
}
}
if (newNamedSet.size) {
const stringifiedSource = JSON.stringify(source)
const values = []
newNamedSet.forEach(({ local, imported }) => {
if (local === imported) {
values.push(local)
return
}
if (esModule) {
values.push(`${imported} as ${local}`)
} else {
values.push(`${imported} : ${local}`)
}
})
ops.insertDeps.push({
type: OpType.INSERT_NODE,
preload: {
to: sideEffectImportVisitorState.endImportLoc.end,
data: {
newText: esModule
? `;import { ${values.join(',')} } from ${stringifiedSource};`
: `;var { ${values.join(',')} } = require(${stringifiedSource});`
}
}
})
}
}
}
}
let newCode: string = material.code
if (newCode) {
const validData = Object.create(null)
Object.keys(tplData).forEach((tplName) => {
if (newCode && tplName !== tplData[tplName]) {
validData[tplName] = tplData[tplName]
}
})
if (Object.keys(validData)?.length) {
const output: any = {}
transformSync(newCode, {
parserOpts: {
plugins: parserOptsPlugins
},
babelrc: false,
plugins: [[replaceCodePlugin, { input: { validData }, output }]],
ast: false,
code: false
})
newCode = output.code ?? newCode
}
}
ops.insertCode = {
type: OpType.INSERT_NODE,
preload: {
to: pos,
data: {
newText: newCode
}
}
}
}
path.stop()
}
}
} as PluginObj<{
opts: {
config?: Config
pos: Point
material: InsertNodePreload['data']['material']
lineContents: LineContents
ops: {
insertDeps: Array<DeepPartial<RequestData>>
insertCode: DeepPartial<RequestData>
}
}
}>)
export async function getAddMaterialOps(
lineContents: LineContents,
pos: Point,
material: InsertNodePreload['data']['material'],
config?: Config
) {
const ops: {
insertDeps: Array<RequestData>
insertCode?: RequestData
} = {
insertDeps: [],
insertCode: null
}
if (material?.dependencies) {
const dependencies = material?.dependencies
material = {
...material,
dependencies: Object.keys(dependencies).reduce((acc, name) => {
const vo = dependencies[name]
acc[name] = {
...vo,
local: vo.local ?? name,
imported: vo.mode === 'named' ? vo.imported ?? name : vo.imported
}
return acc
}, {})
}
}
await transformAsync(lineContents.toString(false), {
filename: lineContents.options?.filename,
parserOpts: {
plugins: parserOptsPlugins
},
babelrc: false,
plugins: [[importPlugin, { lineContents, material, pos, ops, config }]],
ast: false,
code: false
})
;(ops.insertDeps.concat(ops.insertCode) as any).forEach((op) => {
if (op?.preload && lineContents?.options) {
op.preload.filename = lineContents?.options.filename
}
})
return ops
} | the_stack |
import { Range } from '@sourcegraph/extension-api-types'
import { isEqual } from 'lodash'
import { EMPTY, NEVER, Observable, of, Subject, Subscription } from 'rxjs'
import { delay, distinctUntilChanged, filter, first, map, takeWhile } from 'rxjs/operators'
import { TestScheduler } from 'rxjs/testing'
import { ErrorLike } from './errors'
import { isDefined, propertyIsDefined } from './helpers'
import {
AdjustmentDirection,
createHoverifier,
LOADER_DELAY,
MOUSEOVER_DELAY,
PositionAdjuster,
PositionJump,
TOOLTIP_DISPLAY_DELAY,
} from './hoverifier'
import { findPositionsFromEvents, SupportedMouseEvent } from './positions'
import { CodeViewProps, DOM } from './testutils/dom'
import {
createHoverAttachment,
createStubActionsProvider,
createStubHoverProvider,
createStubDocumentHighlightProvider,
} from './testutils/fixtures'
import { dispatchMouseEventAtPositionImpure } from './testutils/mouse'
import { HoverAttachment } from './types'
import { LOADING } from './loading'
const { assert } = chai
describe('Hoverifier', () => {
const dom = new DOM()
after(dom.cleanup)
let testcases: CodeViewProps[] = []
before(() => {
testcases = dom.createCodeViews()
})
let subscriptions = new Subscription()
afterEach(() => {
subscriptions.unsubscribe()
subscriptions = new Subscription()
})
it('highlights token when hover is fetched (not before)', () => {
for (const codeView of testcases) {
const scheduler = new TestScheduler((a, b) => chai.assert.deepEqual(a, b))
const delayTime = 100
const hoverRange = { start: { line: 1, character: 2 }, end: { line: 3, character: 4 } }
const hoverRange1Indexed = { start: { line: 2, character: 3 }, end: { line: 4, character: 5 } }
scheduler.run(({ cold, expectObservable }) => {
const hoverifier = createHoverifier({
closeButtonClicks: NEVER,
hoverOverlayElements: of(null),
hoverOverlayRerenders: EMPTY,
getHover: createStubHoverProvider({ range: hoverRange }, LOADER_DELAY + delayTime),
getDocumentHighlights: createStubDocumentHighlightProvider(),
getActions: () => of(null),
pinningEnabled: true,
})
const positionJumps = new Subject<PositionJump>()
const positionEvents = of(codeView.codeView).pipe(findPositionsFromEvents({ domFunctions: codeView }))
const subscriptions = new Subscription()
subscriptions.add(hoverifier)
subscriptions.add(
hoverifier.hoverify({
dom: codeView,
positionEvents,
positionJumps,
resolveContext: () => codeView.revSpec,
})
)
const highlightedRangeUpdates = hoverifier.hoverStateUpdates.pipe(
map(hoverOverlayProps => (hoverOverlayProps ? hoverOverlayProps.highlightedRange : null)),
distinctUntilChanged((a, b) => isEqual(a, b))
)
const inputDiagram = 'a'
const outputDiagram = `${MOUSEOVER_DELAY}ms a ${LOADER_DELAY + delayTime - 1}ms b`
const outputValues: {
[key: string]: Range | undefined
} = {
a: undefined, // highlightedRange is undefined when the hover is loading
b: hoverRange1Indexed,
}
// Hover over https://sourcegraph.sgdev.org/github.com/gorilla/mux@cb4698366aa625048f3b815af6a0dea8aef9280a/-/blob/mux.go#L24:6
cold(inputDiagram).subscribe(() =>
dispatchMouseEventAtPositionImpure('mouseover', codeView, {
line: 24,
character: 6,
})
)
expectObservable(highlightedRangeUpdates).toBe(outputDiagram, outputValues)
})
}
})
it('pins the overlay without it disappearing temporarily on mouseover then click', () => {
for (const codeView of testcases) {
const scheduler = new TestScheduler((a, b) => chai.assert.deepEqual(a, b))
const hover = {}
const delayTime = 10
scheduler.run(({ cold, expectObservable }) => {
const hoverifier = createHoverifier({
closeButtonClicks: NEVER,
hoverOverlayElements: of(null),
hoverOverlayRerenders: EMPTY,
getHover: createStubHoverProvider(hover, delayTime),
getDocumentHighlights: createStubDocumentHighlightProvider(),
getActions: createStubActionsProvider(['foo', 'bar'], delayTime),
pinningEnabled: true,
})
const positionJumps = new Subject<PositionJump>()
const positionEvents = of(codeView.codeView).pipe(findPositionsFromEvents({ domFunctions: codeView }))
const subscriptions = new Subscription()
subscriptions.add(hoverifier)
subscriptions.add(
hoverifier.hoverify({
dom: codeView,
positionEvents,
positionJumps,
resolveContext: () => codeView.revSpec,
})
)
const hoverAndDefinitionUpdates = hoverifier.hoverStateUpdates.pipe(
map(hoverState => !!hoverState.hoverOverlayProps),
distinctUntilChanged(isEqual)
)
// If you need to debug this test, the following might help. Append this to the `outputDiagram`
// string below:
//
// ` ${delayAfterMouseover - 1}ms c ${delayTime - 1}ms d`
//
// Also, add these properties to `outputValues`:
//
// c: true, // the most important instant, right after the click to pin (must be true, meaning it doesn't disappear)
// d: true,
//
// There should be no emissions at "c" or "d", so this will cause the test to fail. But those are
// the most likely instants where there would be an emission if pinning is causing a temporary
// disappearance of the overlay.
const delayAfterMouseover = 100
const outputDiagram = `${MOUSEOVER_DELAY}ms a ${delayTime - 1}ms b`
const outputValues: {
[key: string]: boolean
} = {
a: false,
b: true,
}
// Mouseover https://sourcegraph.sgdev.org/github.com/gorilla/mux@cb4698366aa625048f3b815af6a0dea8aef9280a/-/blob/mux.go#L24:6
cold('a').subscribe(() =>
dispatchMouseEventAtPositionImpure('mouseover', codeView, {
line: 24,
character: 6,
})
)
// Click (to pin) https://sourcegraph.sgdev.org/github.com/gorilla/mux@cb4698366aa625048f3b815af6a0dea8aef9280a/-/blob/mux.go#L24:6
cold(`${MOUSEOVER_DELAY + delayTime + delayAfterMouseover}ms c`).subscribe(() =>
dispatchMouseEventAtPositionImpure('click', codeView, {
line: 24,
character: 6,
})
)
// Mouseover something else and ensure it remains pinned.
cold(`${MOUSEOVER_DELAY + delayTime + delayAfterMouseover + 100}ms d`).subscribe(() =>
dispatchMouseEventAtPositionImpure('mouseover', codeView, {
line: 25,
character: 3,
})
)
expectObservable(hoverAndDefinitionUpdates).toBe(outputDiagram, outputValues)
})
}
})
it('does not pin the overlay on click when pinningEnabled is false', () => {
for (const codeView of testcases) {
const scheduler = new TestScheduler((a, b) => chai.assert.deepEqual(a, b))
const hover = {}
const delayTime = 10
scheduler.run(({ cold, expectObservable }) => {
const hoverifier = createHoverifier({
closeButtonClicks: NEVER,
hoverOverlayElements: of(null),
hoverOverlayRerenders: EMPTY,
getHover: createStubHoverProvider(hover, delayTime),
getDocumentHighlights: createStubDocumentHighlightProvider(),
getActions: createStubActionsProvider(['foo', 'bar'], delayTime),
pinningEnabled: false,
})
const positionJumps = new Subject<PositionJump>()
const positionEvents = of(codeView.codeView).pipe(findPositionsFromEvents({ domFunctions: codeView }))
const subscriptions = new Subscription()
subscriptions.add(hoverifier)
subscriptions.add(
hoverifier.hoverify({
dom: codeView,
positionEvents,
positionJumps,
resolveContext: () => codeView.revSpec,
})
)
const hoverAndDefinitionUpdates = hoverifier.hoverStateUpdates.pipe(
map(hoverState => !!hoverState.hoverOverlayProps),
distinctUntilChanged(isEqual)
)
const delayAfterMouseover = 100
const outputDiagram = `${MOUSEOVER_DELAY}ms a ${delayTime - 1}ms b ${
MOUSEOVER_DELAY + delayAfterMouseover + 100 - 1
}ms c ${delayTime - 1}ms d`
const outputValues: {
[key: string]: boolean
} = {
a: false,
b: true,
c: false,
d: true,
}
// Mouseover https://sourcegraph.sgdev.org/github.com/gorilla/mux@cb4698366aa625048f3b815af6a0dea8aef9280a/-/blob/mux.go#L24:6
cold('a').subscribe(() =>
dispatchMouseEventAtPositionImpure('mouseover', codeView, {
line: 24,
character: 6,
})
)
// Click (should not get pinned) https://sourcegraph.sgdev.org/github.com/gorilla/mux@cb4698366aa625048f3b815af6a0dea8aef9280a/-/blob/mux.go#L24:6
cold(`${MOUSEOVER_DELAY + delayTime + delayAfterMouseover}ms c`).subscribe(() =>
dispatchMouseEventAtPositionImpure('click', codeView, {
line: 24,
character: 6,
})
)
// Mouseover something else and ensure it doesn't get pinned.
cold(`${MOUSEOVER_DELAY + delayTime + delayAfterMouseover + 100}ms d`).subscribe(() =>
dispatchMouseEventAtPositionImpure('mouseover', codeView, {
line: 25,
character: 3,
})
)
expectObservable(hoverAndDefinitionUpdates).toBe(outputDiagram, outputValues)
})
}
})
it('emits the currently hovered token', () => {
for (const codeView of testcases) {
const scheduler = new TestScheduler((a, b) => chai.assert.deepEqual(a, b))
const hover = {}
const delayTime = 10
scheduler.run(({ cold, expectObservable }) => {
const hoverifier = createHoverifier({
closeButtonClicks: NEVER,
hoverOverlayElements: of(null),
hoverOverlayRerenders: EMPTY,
getHover: createStubHoverProvider(hover, delayTime),
getDocumentHighlights: createStubDocumentHighlightProvider(),
getActions: createStubActionsProvider(['foo', 'bar'], delayTime),
pinningEnabled: false,
})
const positionJumps = new Subject<PositionJump>()
const positionEvents = of(codeView.codeView).pipe(findPositionsFromEvents({ domFunctions: codeView }))
const subscriptions = new Subscription()
subscriptions.add(hoverifier)
subscriptions.add(
hoverifier.hoverify({
dom: codeView,
positionEvents,
positionJumps,
resolveContext: () => codeView.revSpec,
})
)
const hoverAndDefinitionUpdates = hoverifier.hoverStateUpdates.pipe(
map(hoverState => hoverState.hoveredTokenElement && hoverState.hoveredTokenElement.textContent),
distinctUntilChanged(isEqual)
)
const outputDiagram = `${MOUSEOVER_DELAY}ms a ${delayTime - 1}ms b`
const outputValues: {
[key: string]: string | undefined
} = {
a: undefined,
b: 'Router',
}
// Mouseover https://sourcegraph.sgdev.org/github.com/gorilla/mux@cb4698366aa625048f3b815af6a0dea8aef9280a/-/blob/mux.go#L24:6
cold('a').subscribe(() =>
dispatchMouseEventAtPositionImpure('mouseover', codeView, {
line: 48,
character: 10,
})
)
expectObservable(hoverAndDefinitionUpdates).toBe(outputDiagram, outputValues)
})
}
})
it('highlights document highlights', async () => {
for (const codeViewProps of testcases) {
const hoverifier = createHoverifier({
closeButtonClicks: NEVER,
hoverOverlayElements: of(null),
hoverOverlayRerenders: EMPTY,
getHover: createStubHoverProvider(),
getDocumentHighlights: createStubDocumentHighlightProvider([
{ range: { start: { line: 24, character: 9 }, end: { line: 4, character: 15 } } },
{ range: { start: { line: 45, character: 5 }, end: { line: 45, character: 11 } } },
{ range: { start: { line: 120, character: 9 }, end: { line: 120, character: 15 } } },
]),
getActions: () => of(null),
pinningEnabled: true,
documentHighlightClassName: 'test-highlight',
})
const positionJumps = new Subject<PositionJump>()
const positionEvents = of(codeViewProps.codeView).pipe(
findPositionsFromEvents({ domFunctions: codeViewProps })
)
hoverifier.hoverify({
dom: codeViewProps,
positionEvents,
positionJumps,
resolveContext: () => codeViewProps.revSpec,
})
dispatchMouseEventAtPositionImpure('mouseover', codeViewProps, {
line: 24,
character: 6,
})
await hoverifier.hoverStateUpdates
.pipe(
filter(state => !!state.hoverOverlayProps),
first()
)
.toPromise()
await of(null).pipe(delay(200)).toPromise()
const selected = codeViewProps.codeView.querySelectorAll('.test-highlight')
assert.equal(selected.length, 3)
for (const e of selected) {
assert.equal(e.textContent, 'Router')
}
}
})
it('hides the hover overlay when the hovered token intersects with a scrollBoundary', async () => {
const gitHubCodeView = testcases[1]
const hoverifier = createHoverifier({
closeButtonClicks: NEVER,
hoverOverlayElements: of(null),
hoverOverlayRerenders: EMPTY,
getHover: createStubHoverProvider({
range: {
start: { line: 4, character: 9 },
end: { line: 4, character: 9 },
},
}),
getDocumentHighlights: createStubDocumentHighlightProvider(),
getActions: createStubActionsProvider(['foo', 'bar']),
pinningEnabled: true,
})
subscriptions.add(hoverifier)
subscriptions.add(
hoverifier.hoverify({
dom: gitHubCodeView,
positionEvents: of(gitHubCodeView.codeView).pipe(
findPositionsFromEvents({ domFunctions: gitHubCodeView })
),
positionJumps: new Subject<PositionJump>(),
resolveContext: () => gitHubCodeView.revSpec,
scrollBoundaries: [gitHubCodeView.codeView.querySelector<HTMLElement>('.sticky-file-header')!],
})
)
gitHubCodeView.codeView.scrollIntoView()
// Click https://sourcegraph.sgdev.org/github.com/gorilla/mux@cb4698366aa625048f3b815af6a0dea8aef9280a/-/blob/mux.go#L5:9
// and wait for the hovered token to be defined.
const hasHoveredToken = hoverifier.hoverStateUpdates
.pipe(takeWhile(({ hoveredTokenElement }) => !isDefined(hoveredTokenElement)))
.toPromise()
dispatchMouseEventAtPositionImpure('click', gitHubCodeView, {
line: 5,
character: 9,
})
await hasHoveredToken
// Scroll down: the hover overlay should get hidden.
const hoverIsHidden = hoverifier.hoverStateUpdates
.pipe(takeWhile(({ hoverOverlayProps }) => isDefined(hoverOverlayProps)))
.toPromise()
gitHubCodeView.getCodeElementFromLineNumber(gitHubCodeView.codeView, 2)!.scrollIntoView({ behavior: 'smooth' })
await hoverIsHidden
})
describe('pinning', () => {
it('unpins upon clicking on a different position', () => {
for (const codeView of testcases) {
const scheduler = new TestScheduler((a, b) => chai.assert.deepEqual(a, b))
const delayTime = 10
scheduler.run(({ cold, expectObservable }) => {
const hoverifier = createHoverifier({
closeButtonClicks: NEVER,
hoverOverlayElements: of(null),
hoverOverlayRerenders: EMPTY,
// Only show on line 24, not line 25 (which is the 2nd click event below).
getHover: position =>
position.line === 24
? createStubHoverProvider({}, delayTime)(position)
: of({ isLoading: false, result: null }),
getDocumentHighlights: createStubDocumentHighlightProvider(),
getActions: position =>
position.line === 24
? createStubActionsProvider(['foo', 'bar'], delayTime)(position)
: of(null),
pinningEnabled: true,
})
const positionJumps = new Subject<PositionJump>()
const positionEvents = of(codeView.codeView).pipe(
findPositionsFromEvents({ domFunctions: codeView })
)
const subscriptions = new Subscription()
subscriptions.add(hoverifier)
subscriptions.add(
hoverifier.hoverify({
dom: codeView,
positionEvents,
positionJumps,
resolveContext: () => codeView.revSpec,
})
)
const isPinned = hoverifier.hoverStateUpdates.pipe(
map(
hoverState =>
!!hoverState.hoverOverlayProps && !!hoverState.hoverOverlayProps.showCloseButton
),
distinctUntilChanged()
)
const outputDiagram = `${delayTime}ms a-c`
const outputValues: {
[key: string]: boolean
} = {
a: true,
c: false,
}
// Click (to pin) https://sourcegraph.sgdev.org/github.com/gorilla/mux@cb4698366aa625048f3b815af6a0dea8aef9280a/-/blob/mux.go#L24:6
cold('a').subscribe(() => {
dispatchMouseEventAtPositionImpure('click', codeView, {
line: 24,
character: 6,
})
})
// Click to another position and ensure the hover is no longer pinned.
cold(`${delayTime}ms --c`).subscribe(() =>
positionJumps.next({
codeView: codeView.codeView,
scrollElement: codeView.container,
position: { line: 1, character: 1 },
})
)
expectObservable(isPinned).toBe(outputDiagram, outputValues)
})
}
})
it('unpins upon navigation to an invalid or undefined position (such as a file with no particular position)', () => {
for (const codeView of testcases) {
const scheduler = new TestScheduler((a, b) => chai.assert.deepEqual(a, b))
scheduler.run(({ cold, expectObservable }) => {
const hoverifier = createHoverifier({
closeButtonClicks: NEVER,
hoverOverlayElements: of(null),
hoverOverlayRerenders: EMPTY,
// Only show on line 24, not line 25 (which is the 2nd click event below).
getHover: position =>
position.line === 24
? createStubHoverProvider({})(position)
: of({ isLoading: false, result: null }),
getDocumentHighlights: createStubDocumentHighlightProvider(),
getActions: position =>
position.line === 24 ? createStubActionsProvider(['foo', 'bar'])(position) : of(null),
pinningEnabled: true,
})
const positionJumps = new Subject<PositionJump>()
const positionEvents = of(codeView.codeView).pipe(
findPositionsFromEvents({ domFunctions: codeView })
)
const subscriptions = new Subscription()
subscriptions.add(hoverifier)
subscriptions.add(
hoverifier.hoverify({
dom: codeView,
positionEvents,
positionJumps,
resolveContext: () => codeView.revSpec,
})
)
const isPinned = hoverifier.hoverStateUpdates.pipe(
map(hoverState => {
if (!hoverState.hoverOverlayProps) {
return 'hidden'
}
if (hoverState.hoverOverlayProps.showCloseButton) {
return 'pinned'
}
return 'visible'
}),
distinctUntilChanged()
)
const outputDiagram = 'ab'
const outputValues: {
[key: string]: 'hidden' | 'pinned' | 'visible'
} = {
a: 'pinned',
b: 'hidden',
}
// Click (to pin) https://sourcegraph.sgdev.org/github.com/gorilla/mux@cb4698366aa625048f3b815af6a0dea8aef9280a/-/blob/mux.go#L24:6
cold('a').subscribe(() =>
dispatchMouseEventAtPositionImpure('click', codeView, {
line: 24,
character: 6,
})
)
// Click to another position and ensure the hover is no longer pinned.
cold('-b').subscribe(() =>
positionJumps.next({
codeView: codeView.codeView,
scrollElement: codeView.container,
position: { line: undefined, character: undefined },
})
)
expectObservable(isPinned).toBe(outputDiagram, outputValues)
})
}
})
})
it('emits loading and then state on click events', () => {
for (const codeView of testcases) {
const scheduler = new TestScheduler((a, b) => chai.assert.deepEqual(a, b))
const hoverDelayTime = 100
const actionsDelayTime = 150
const hover = {}
const actions = ['foo', 'bar']
scheduler.run(({ cold, expectObservable }) => {
const hoverifier = createHoverifier({
closeButtonClicks: new Observable<MouseEvent>(),
hoverOverlayElements: of(null),
hoverOverlayRerenders: EMPTY,
getHover: createStubHoverProvider(hover, LOADER_DELAY + hoverDelayTime),
getDocumentHighlights: createStubDocumentHighlightProvider(),
getActions: createStubActionsProvider(actions, LOADER_DELAY + actionsDelayTime),
pinningEnabled: true,
})
const positionJumps = new Subject<PositionJump>()
const positionEvents = of(codeView.codeView).pipe(findPositionsFromEvents({ domFunctions: codeView }))
const subscriptions = new Subscription()
subscriptions.add(hoverifier)
subscriptions.add(
hoverifier.hoverify({
dom: codeView,
positionEvents,
positionJumps,
resolveContext: () => codeView.revSpec,
})
)
const hoverAndActionsUpdates = hoverifier.hoverStateUpdates.pipe(
filter(propertyIsDefined('hoverOverlayProps')),
map(({ hoverOverlayProps: { actionsOrError, hoverOrError } }) => ({
actionsOrError,
hoverOrError,
})),
distinctUntilChanged((a, b) => isEqual(a, b))
)
const inputDiagram = 'a'
// Subtract 1ms before "b" because "a" takes up 1ms.
const outputDiagram = `${LOADER_DELAY}ms ${hoverDelayTime}ms a ${
actionsDelayTime - hoverDelayTime - 1
}ms b`
const outputValues: {
[key: string]: {
hoverOrError: typeof LOADING | HoverAttachment | null | ErrorLike
actionsOrError: typeof LOADING | string[] | null | ErrorLike
}
} = {
// No hover is shown if it would just consist of LOADING.
a: { hoverOrError: createHoverAttachment(hover), actionsOrError: LOADING },
b: { hoverOrError: createHoverAttachment(hover), actionsOrError: actions },
}
// Click https://sourcegraph.sgdev.org/github.com/gorilla/mux@cb4698366aa625048f3b815af6a0dea8aef9280a/-/blob/mux.go#L24:6
cold(inputDiagram).subscribe(() =>
dispatchMouseEventAtPositionImpure('click', codeView, {
line: 24,
character: 6,
})
)
expectObservable(hoverAndActionsUpdates).toBe(outputDiagram, outputValues)
})
}
})
it('debounces mousemove events before showing overlay', () => {
for (const codeView of testcases) {
const scheduler = new TestScheduler((a, b) => chai.assert.deepEqual(a, b))
const hover = {}
scheduler.run(({ cold, expectObservable }) => {
const hoverifier = createHoverifier({
closeButtonClicks: new Observable<MouseEvent>(),
hoverOverlayElements: of(null),
hoverOverlayRerenders: EMPTY,
getHover: createStubHoverProvider(hover),
getDocumentHighlights: createStubDocumentHighlightProvider(),
getActions: () => of(null),
pinningEnabled: true,
})
const positionJumps = new Subject<PositionJump>()
const positionEvents = of(codeView.codeView).pipe(findPositionsFromEvents({ domFunctions: codeView }))
const subscriptions = new Subscription()
subscriptions.add(hoverifier)
subscriptions.add(
hoverifier.hoverify({
dom: codeView,
positionEvents,
positionJumps,
resolveContext: () => codeView.revSpec,
})
)
const hoverAndDefinitionUpdates = hoverifier.hoverStateUpdates.pipe(
filter(propertyIsDefined('hoverOverlayProps')),
map(({ hoverOverlayProps }) => !!hoverOverlayProps),
distinctUntilChanged(isEqual)
)
const mousemoveDelay = 25
const outputDiagram = `${TOOLTIP_DISPLAY_DELAY + mousemoveDelay}ms a`
const outputValues: { [key: string]: boolean } = {
a: true,
}
// Mousemove on https://sourcegraph.sgdev.org/github.com/gorilla/mux@cb4698366aa625048f3b815af6a0dea8aef9280a/-/blob/mux.go#L24:6
cold(`a b ${mousemoveDelay - 2}ms c ${TOOLTIP_DISPLAY_DELAY - 1}ms`, {
a: 'mouseover',
b: 'mousemove',
c: 'mousemove',
} as Record<string, SupportedMouseEvent>).subscribe(eventType =>
dispatchMouseEventAtPositionImpure(eventType, codeView, {
line: 24,
character: 6,
})
)
expectObservable(hoverAndDefinitionUpdates).toBe(outputDiagram, outputValues)
})
}
})
it('dedupes mouseover and mousemove event on same token', () => {
for (const codeView of testcases) {
const scheduler = new TestScheduler((a, b) => chai.assert.deepEqual(a, b))
const hover = {}
scheduler.run(({ cold, expectObservable }) => {
const hoverifier = createHoverifier({
closeButtonClicks: new Observable<MouseEvent>(),
hoverOverlayElements: of(null),
hoverOverlayRerenders: EMPTY,
getHover: createStubHoverProvider(hover),
getDocumentHighlights: createStubDocumentHighlightProvider(),
getActions: () => of(null),
pinningEnabled: true,
})
const positionJumps = new Subject<PositionJump>()
const positionEvents = of(codeView.codeView).pipe(findPositionsFromEvents({ domFunctions: codeView }))
const subscriptions = new Subscription()
subscriptions.add(hoverifier)
subscriptions.add(
hoverifier.hoverify({
dom: codeView,
positionEvents,
positionJumps,
resolveContext: () => codeView.revSpec,
})
)
const hoverAndDefinitionUpdates = hoverifier.hoverStateUpdates.pipe(
filter(propertyIsDefined('hoverOverlayProps')),
map(({ hoverOverlayProps }) => !!hoverOverlayProps),
distinctUntilChanged(isEqual)
)
// Add 2 for 1 tick each for "c" and "d" below.
const outputDiagram = `${TOOLTIP_DISPLAY_DELAY + MOUSEOVER_DELAY + 2}ms a`
const outputValues: { [key: string]: boolean } = {
a: true,
}
// Mouse on https://sourcegraph.sgdev.org/github.com/gorilla/mux@cb4698366aa625048f3b815af6a0dea8aef9280a/-/blob/mux.go#L24:6
cold(
`a b ${MOUSEOVER_DELAY - 2}ms c d e`,
((): Record<string, SupportedMouseEvent> => ({
a: 'mouseover',
b: 'mousemove',
// Now perform repeated mousemove/mouseover events on the same token.
c: 'mousemove',
d: 'mouseover',
e: 'mousemove',
}))()
).subscribe(eventType =>
dispatchMouseEventAtPositionImpure(eventType, codeView, {
line: 24,
character: 6,
})
)
expectObservable(hoverAndDefinitionUpdates).toBe(outputDiagram, outputValues)
})
}
})
/**
* This test ensures that the adjustPosition options is being called in the ways we expect. This test is actually not the best way to ensure the feature
* works as expected. This is a good example of a bad side effect of how the main `hoverifier.ts` file is too tightly integrated with itself. Ideally, I'd be able to assert
* that the effected positions have actually been adjusted as intended but this is impossible with the current implementation. We can assert that the `HoverProvider` and `ActionsProvider`s
* have the adjusted positions (AdjustmentDirection.CodeViewToActual). However, we cannot reliably assert that the code "highlighting" the token has the position adjusted (AdjustmentDirection.ActualToCodeView).
*/
/**
* This test is skipped because its flakey. I'm unsure how to reliably test this feature in hoverifiers current state.
*/
it.skip('PositionAdjuster gets called when expected', () => {
for (const codeView of testcases) {
const scheduler = new TestScheduler((a, b) => chai.assert.deepEqual(a, b))
scheduler.run(({ cold, expectObservable }) => {
const adjustmentDirections = new Subject<AdjustmentDirection>()
const getHover = createStubHoverProvider({})
const getDocumentHighlights = createStubDocumentHighlightProvider()
const getActions = createStubActionsProvider(['foo', 'bar'])
const adjustPosition: PositionAdjuster<{}> = ({ direction, position }) => {
adjustmentDirections.next(direction)
return of(position)
}
const hoverifier = createHoverifier({
closeButtonClicks: new Observable<MouseEvent>(),
hoverOverlayElements: of(null),
hoverOverlayRerenders: EMPTY,
getHover,
getDocumentHighlights,
getActions,
pinningEnabled: true,
})
const positionJumps = new Subject<PositionJump>()
const positionEvents = of(codeView.codeView).pipe(findPositionsFromEvents({ domFunctions: codeView }))
const subscriptions = new Subscription()
subscriptions.add(hoverifier)
subscriptions.add(
hoverifier.hoverify({
dom: codeView,
positionEvents,
positionJumps,
adjustPosition,
resolveContext: () => codeView.revSpec,
})
)
const inputDiagram = 'ab'
// There is probably a bug in code that is unrelated to this feature that is causing the
// PositionAdjuster to be called an extra time. It should look like '-(ba)'. That is, we adjust the
// position from CodeViewToActual for the fetches and then back from CodeViewToActual for
// highlighting the token in the DOM.
const outputDiagram = 'a(ba)'
const outputValues: {
[key: string]: AdjustmentDirection
} = {
a: AdjustmentDirection.ActualToCodeView,
b: AdjustmentDirection.CodeViewToActual,
}
cold(inputDiagram).subscribe(() =>
dispatchMouseEventAtPositionImpure('click', codeView, {
line: 1,
character: 1,
})
)
expectObservable(adjustmentDirections).toBe(outputDiagram, outputValues)
})
}
})
describe('unhoverify', () => {
it('hides the hover overlay when the code view is unhoverified', async () => {
for (const codeView of testcases) {
const hoverifier = createHoverifier({
closeButtonClicks: NEVER,
hoverOverlayElements: of(null),
hoverOverlayRerenders: EMPTY,
// It's important that getHover() and getActions() emit something
getHover: createStubHoverProvider({}),
getDocumentHighlights: createStubDocumentHighlightProvider(),
getActions: () => of([{}]).pipe(delay(50)),
pinningEnabled: true,
})
const positionJumps = new Subject<PositionJump>()
const positionEvents = of(codeView.codeView).pipe(findPositionsFromEvents({ domFunctions: codeView }))
const codeViewSubscription = hoverifier.hoverify({
dom: codeView,
positionEvents,
positionJumps,
resolveContext: () => codeView.revSpec,
})
dispatchMouseEventAtPositionImpure('mouseover', codeView, {
line: 24,
character: 6,
})
await hoverifier.hoverStateUpdates
.pipe(
filter(state => !!state.hoverOverlayProps),
first()
)
.toPromise()
codeViewSubscription.unsubscribe()
assert.strictEqual(hoverifier.hoverState.hoverOverlayProps, undefined)
await of(null).pipe(delay(200)).toPromise()
assert.strictEqual(hoverifier.hoverState.hoverOverlayProps, undefined)
}
})
it('does not hide the hover overlay when a different code view is unhoverified', async () => {
for (const codeViewProps of testcases) {
const hoverifier = createHoverifier({
closeButtonClicks: NEVER,
hoverOverlayElements: of(null),
hoverOverlayRerenders: EMPTY,
getHover: createStubHoverProvider(),
getDocumentHighlights: createStubDocumentHighlightProvider(),
getActions: () => of(null),
pinningEnabled: true,
})
const positionJumps = new Subject<PositionJump>()
const positionEvents = of(codeViewProps.codeView).pipe(
findPositionsFromEvents({ domFunctions: codeViewProps })
)
const codeViewSubscription = hoverifier.hoverify({
dom: codeViewProps,
positionEvents: NEVER,
positionJumps: NEVER,
resolveContext: () => {
throw new Error('not called')
},
})
hoverifier.hoverify({
dom: codeViewProps,
positionEvents,
positionJumps,
resolveContext: () => codeViewProps.revSpec,
})
dispatchMouseEventAtPositionImpure('mouseover', codeViewProps, {
line: 24,
character: 6,
})
await hoverifier.hoverStateUpdates
.pipe(
filter(state => !!state.hoverOverlayProps),
first()
)
.toPromise()
codeViewSubscription.unsubscribe()
assert.isDefined(hoverifier.hoverState.hoverOverlayProps)
await of(null).pipe(delay(200)).toPromise()
assert.isDefined(hoverifier.hoverState.hoverOverlayProps)
}
})
})
}) | the_stack |
import Rectangle from '../geometry/Rectangle';
import CellHighlight from '../cell/CellHighlight';
import {
getDocumentScrollOrigin,
getOffset,
getScrollOrigin,
setOpacity,
} from '../../util/styleUtils';
import InternalEvent from '../event/InternalEvent';
import Client from '../../Client';
import Guide from './Guide';
import { DROP_TARGET_COLOR } from '../../util/Constants';
import Point from '../geometry/Point';
import {
getClientX,
getClientY,
getSource,
isConsumed,
isMouseEvent,
isPenEvent,
isTouchEvent,
} from '../../util/EventUtils';
import EventSource from '../event/EventSource';
import EventObject from '../event/EventObject';
import { Graph } from '../Graph';
import Cell from '../cell/Cell';
import SelectionHandler from '../handler/SelectionHandler';
export type DropHandler = (
graph: Graph,
evt: MouseEvent,
cell: Cell | null,
x?: number,
y?: number
) => void;
/**
* @class DragSource
*
* Wrapper to create a drag source from a DOM element so that the element can
* be dragged over a graph and dropped into the graph as a new cell.
*
* Problem is that in the dropHandler the current preview location is not
* available, so the preview and the dropHandler must match.
*
*/
class DragSource {
constructor(element: EventTarget, dropHandler: DropHandler) {
this.element = element;
this.dropHandler = dropHandler;
// Handles a drag gesture on the element
InternalEvent.addGestureListeners(element, (evt) => {
this.mouseDown(evt);
});
// Prevents native drag and drop
InternalEvent.addListener(element, 'dragstart', (evt: MouseEvent) => {
InternalEvent.consume(evt);
});
this.eventConsumer = (sender: EventSource, evt: EventObject) => {
const evtName = evt.getProperty('eventName');
const me = evt.getProperty('event');
if (evtName !== InternalEvent.MOUSE_DOWN) {
me.consume();
}
};
}
/**
* Reference to the DOM node which was made draggable.
*/
element: EventTarget;
/**
* Holds the DOM node that is used to represent the drag preview. If this is
* null then the source element will be cloned and used for the drag preview.
*/
dropHandler: DropHandler;
eventConsumer: (sender: EventSource, evt: EventObject) => void;
/**
* {@link Point} that specifies the offset of the {@link dragElement}. Default is null.
*/
dragOffset: Point | null = null;
/**
* Holds the DOM node that is used to represent the drag preview. If this is
* null then the source element will be cloned and used for the drag preview.
*/
dragElement: HTMLElement | null = null;
/**
* TODO - wrong description
* Optional {@link Rectangle} that specifies the unscaled size of the preview.
*/
previewElement: HTMLElement | null = null;
/**
* Optional {@link Point} that specifies the offset of the preview in pixels.
*/
previewOffset: Point | null = null;
/**
* Specifies if this drag source is enabled. Default is true.
*/
enabled = true;
/**
* Reference to the {@link mxGraph} that is the current drop target.
*/
currentGraph: Graph | null = null;
/**
* Holds the current drop target under the mouse.
*/
currentDropTarget: Cell | null = null;
/**
* Holds the current drop location.
*/
currentPoint: Point | null = null;
/**
* Holds an {@link mxGuide} for the {@link currentGraph} if {@link dragPreview} is not null.
*/
currentGuide: Guide | null = null;
/**
* Holds an {@link mxGuide} for the {@link currentGraph} if {@link dragPreview} is not null.
* @note wrong doc
*/
currentHighlight: CellHighlight | null = null;
/**
* Specifies if the graph should scroll automatically. Default is true.
*/
autoscroll = true;
/**
* Specifies if {@link mxGuide} should be enabled. Default is true.
*/
guidesEnabled = true;
/**
* Specifies if the grid should be allowed. Default is true.
*/
gridEnabled = true;
/**
* Specifies if drop targets should be highlighted. Default is true.
*/
highlightDropTargets = true;
/**
* ZIndex for the drag element. Default is 100.
*/
dragElementZIndex = 100;
/**
* Opacity of the drag element in %. Default is 70.
*/
dragElementOpacity = 70;
/**
* Whether the event source should be checked in {@link graphContainerEvent}. Default
* is true.
*/
checkEventSource = true;
mouseMoveHandler: ((evt: MouseEvent) => void) | null = null;
mouseUpHandler: ((evt: MouseEvent) => void) | null = null;
eventSource: EventTarget | null = null;
/**
* Returns {@link enabled}.
*/
isEnabled() {
return this.enabled;
}
/**
* Sets {@link enabled}.
*/
setEnabled(value: boolean) {
this.enabled = value;
}
/**
* Returns {@link guidesEnabled}.
*/
isGuidesEnabled() {
return this.guidesEnabled;
}
/**
* Sets {@link guidesEnabled}.
*/
setGuidesEnabled(value: boolean) {
this.guidesEnabled = value;
}
/**
* Returns {@link gridEnabled}.
*/
isGridEnabled() {
return this.gridEnabled;
}
/**
* Sets {@link gridEnabled}.
*/
setGridEnabled(value: boolean) {
this.gridEnabled = value;
}
/**
* Returns the graph for the given mouse event. This implementation returns
* null.
*/
getGraphForEvent(evt: MouseEvent) {
return null;
}
/**
* Returns the drop target for the given graph and coordinates. This
* implementation uses {@link mxGraph.getCellAt}.
*/
getDropTarget(graph: Graph, x: number, y: number, evt: MouseEvent) {
return graph.getCellAt(x, y);
}
/**
* Creates and returns a clone of the {@link dragElementPrototype} or the {@link element}
* if the former is not defined.
*/
createDragElement(evt: MouseEvent) {
return (this.element as HTMLElement).cloneNode(true) as HTMLElement;
}
/**
* Creates and returns an element which can be used as a preview in the given
* graph.
*/
createPreviewElement(graph: Graph): HTMLElement | null {
return null;
}
/**
* Returns true if this drag source is active.
*/
isActive() {
return !!this.mouseMoveHandler;
}
/**
* Stops and removes everything and restores the state of the object.
*/
reset() {
if (this.currentGraph) {
this.dragExit(this.currentGraph);
this.currentGraph = null;
}
this.removeDragElement();
this.removeListeners();
this.stopDrag();
}
/**
* Returns the drop target for the given graph and coordinates. This
* implementation uses {@link mxGraph.getCellAt}.
*
* To ignore popup menu events for a drag source, this function can be
* overridden as follows.
*
* @example
* ```javascript
* var mouseDown = dragSource.mouseDown;
*
* dragSource.mouseDown(evt)
* {
* if (!mxEvent.isPopupTrigger(evt))
* {
* mouseDown.apply(this, arguments);
* }
* };
* ```
*/
mouseDown(evt: MouseEvent) {
if (this.enabled && !isConsumed(evt) && this.mouseMoveHandler == null) {
this.startDrag(evt);
this.mouseMoveHandler = this.mouseMove.bind(this);
this.mouseUpHandler = this.mouseUp.bind(this);
InternalEvent.addGestureListeners(
document,
null,
this.mouseMoveHandler,
this.mouseUpHandler
);
if (Client.IS_TOUCH && !isMouseEvent(evt)) {
this.eventSource = getSource(evt);
if (this.eventSource) {
InternalEvent.addGestureListeners(
this.eventSource,
null,
this.mouseMoveHandler,
this.mouseUpHandler
);
}
}
}
}
/**
* Creates the {@link dragElement} using {@link createDragElement}.
*/
startDrag(evt: MouseEvent) {
this.dragElement = this.createDragElement(evt);
this.dragElement.style.position = 'absolute';
this.dragElement.style.zIndex = String(this.dragElementZIndex);
setOpacity(this.dragElement, this.dragElementOpacity);
if (this.checkEventSource && Client.IS_SVG) {
this.dragElement.style.pointerEvents = 'none';
}
}
/**
* Invokes {@link removeDragElement}.
*/
stopDrag() {
// LATER: This used to have a mouse event. If that is still needed we need to add another
// final call to the DnD protocol to add a cleanup step in the case of escape press, which
// is not associated with a mouse event and which currently calles this method.
this.removeDragElement();
}
/**
* Removes and destroys the {@link dragElement}.
*/
removeDragElement() {
if (this.dragElement) {
if (this.dragElement.parentNode) {
this.dragElement.parentNode.removeChild(this.dragElement);
}
this.dragElement = null;
}
}
/**
* Returns the topmost element under the given event.
*/
getElementForEvent(evt: MouseEvent) {
return isTouchEvent(evt) || isPenEvent(evt)
? document.elementFromPoint(getClientX(evt), getClientY(evt))
: getSource(evt);
}
/**
* Returns true if the given graph contains the given event.
*/
graphContainsEvent(graph: Graph, evt: MouseEvent) {
const x = getClientX(evt);
const y = getClientY(evt);
const offset = getOffset(graph.container);
const origin = getScrollOrigin();
let elt = this.getElementForEvent(evt);
if (this.checkEventSource) {
while (elt && elt !== graph.container) {
// @ts-ignore parentNode may exist
elt = elt.parentNode;
}
}
// Checks if event is inside the bounds of the graph container
return (
!!elt &&
x >= offset.x - origin.x &&
y >= offset.y - origin.y &&
x <= offset.x - origin.x + graph.container.offsetWidth &&
y <= offset.y - origin.y + graph.container.offsetHeight
);
}
/**
* Gets the graph for the given event using {@link getGraphForEvent}, updates the
* {@link currentGraph}, calling {@link dragEnter} and {@link dragExit} on the new and old graph,
* respectively, and invokes {@link dragOver} if {@link currentGraph} is not null.
*/
mouseMove(evt: MouseEvent) {
let graph = this.getGraphForEvent(evt);
// Checks if event is inside the bounds of the graph container
if (graph && !this.graphContainsEvent(graph, evt)) {
graph = null;
}
if (graph !== this.currentGraph) {
if (this.currentGraph) {
this.dragExit(this.currentGraph, evt);
}
this.currentGraph = graph;
if (this.currentGraph) {
this.dragEnter(this.currentGraph, evt);
}
}
if (this.currentGraph) {
this.dragOver(this.currentGraph, evt);
}
if (
this.dragElement &&
(!this.previewElement || this.previewElement.style.visibility !== 'visible')
) {
let x = getClientX(evt);
let y = getClientY(evt);
if (this.dragElement.parentNode == null) {
document.body.appendChild(this.dragElement);
}
this.dragElement.style.visibility = 'visible';
if (this.dragOffset) {
x += this.dragOffset.x;
y += this.dragOffset.y;
}
const offset = getDocumentScrollOrigin(document);
this.dragElement.style.left = `${x + offset.x}px`;
this.dragElement.style.top = `${y + offset.y}px`;
} else if (this.dragElement) {
this.dragElement.style.visibility = 'hidden';
}
InternalEvent.consume(evt);
}
/**
* Processes the mouse up event and invokes {@link drop}, {@link dragExit} and {@link stopDrag}
* as required.
*/
mouseUp(evt: MouseEvent) {
if (this.currentGraph) {
if (
this.currentPoint &&
(!this.previewElement || this.previewElement.style.visibility !== 'hidden')
) {
const { scale } = this.currentGraph.view;
const tr = this.currentGraph.view.translate;
const x = this.currentPoint.x / scale - tr.x;
const y = this.currentPoint.y / scale - tr.y;
this.drop(this.currentGraph, evt, this.currentDropTarget, x, y);
}
this.dragExit(this.currentGraph);
this.currentGraph = null;
}
this.stopDrag();
this.removeListeners();
InternalEvent.consume(evt);
}
/**
* Actives the given graph as a drop target.
*/
// removeListeners(): void;
removeListeners() {
if (this.eventSource) {
InternalEvent.removeGestureListeners(
this.eventSource,
null,
this.mouseMoveHandler,
this.mouseUpHandler
);
this.eventSource = null;
}
InternalEvent.removeGestureListeners(
document,
null,
this.mouseMoveHandler,
this.mouseUpHandler
);
this.mouseMoveHandler = null;
this.mouseUpHandler = null;
}
/**
* Actives the given graph as a drop target.
*/
dragEnter(graph: Graph, evt: MouseEvent) {
graph.isMouseDown = true;
graph.isMouseTrigger = isMouseEvent(evt);
this.previewElement = this.createPreviewElement(graph);
if (this.previewElement && this.checkEventSource && Client.IS_SVG) {
this.previewElement.style.pointerEvents = 'none';
}
// Guide is only needed if preview element is used
if (this.isGuidesEnabled() && this.previewElement) {
const graphHandler = graph.getPlugin('SelectionHandler') as SelectionHandler;
this.currentGuide = new Guide(graph, graphHandler.getGuideStates());
}
if (this.highlightDropTargets) {
this.currentHighlight = new CellHighlight(graph, DROP_TARGET_COLOR);
}
// Consumes all events in the current graph before they are fired
graph.addListener(InternalEvent.FIRE_MOUSE_EVENT, this.eventConsumer);
}
/**
* Deactivates the given graph as a drop target.
*/
dragExit(graph: Graph, evt?: MouseEvent) {
this.currentDropTarget = null;
this.currentPoint = null;
graph.isMouseDown = false;
// Consumes all events in the current graph before they are fired
graph.removeListener(this.eventConsumer);
if (this.previewElement) {
if (this.previewElement.parentNode) {
this.previewElement.parentNode.removeChild(this.previewElement);
}
this.previewElement = null;
}
if (this.currentGuide) {
this.currentGuide.destroy();
this.currentGuide = null;
}
if (this.currentHighlight) {
this.currentHighlight.destroy();
this.currentHighlight = null;
}
}
/**
* Implements autoscroll, updates the {@link currentPoint}, highlights any drop
* targets and updates the preview.
*/
dragOver(graph: Graph, evt: MouseEvent) {
const offset = getOffset(graph.container);
const origin = getScrollOrigin(graph.container);
let x = getClientX(evt) - offset.x + origin.x - graph.getPanDx();
let y = getClientY(evt) - offset.y + origin.y - graph.getPanDy();
if (graph.isAutoScroll() && (!this.autoscroll || this.autoscroll)) {
graph.scrollPointToVisible(x, y, graph.isAutoExtend());
}
// Highlights the drop target under the mouse
if (this.currentHighlight && graph.isDropEnabled()) {
this.currentDropTarget = this.getDropTarget(graph, x, y, evt);
if (this.currentDropTarget) {
const state = graph.getView().getState(this.currentDropTarget);
this.currentHighlight.highlight(state);
}
}
// Updates the location of the preview
if (this.previewElement) {
if (!this.previewElement.parentNode) {
graph.container.appendChild(this.previewElement);
this.previewElement.style.zIndex = '3';
this.previewElement.style.position = 'absolute';
}
const gridEnabled = this.isGridEnabled() && graph.isGridEnabledEvent(evt);
let hideGuide = true;
// Grid and guides
if (this.currentGuide && this.currentGuide.isEnabledForEvent(evt)) {
// LATER: HTML preview appears smaller than SVG preview
const w = parseInt(this.previewElement.style.width);
const h = parseInt(this.previewElement.style.height);
const bounds = new Rectangle(0, 0, w, h);
let delta = new Point(x, y);
delta = this.currentGuide.move(bounds, delta, gridEnabled, true);
hideGuide = false;
x = delta.x;
y = delta.y;
} else if (gridEnabled) {
const { scale } = graph.view;
const tr = graph.view.translate;
const off = graph.getGridSize() / 2;
x = (graph.snap(x / scale - tr.x - off) + tr.x) * scale;
y = (graph.snap(y / scale - tr.y - off) + tr.y) * scale;
}
if (this.currentGuide && hideGuide) {
this.currentGuide.hide();
}
if (this.previewOffset) {
x += this.previewOffset.x;
y += this.previewOffset.y;
}
this.previewElement.style.left = `${Math.round(x)}px`;
this.previewElement.style.top = `${Math.round(y)}px`;
this.previewElement.style.visibility = 'visible';
}
this.currentPoint = new Point(x, y);
}
/**
* Returns the drop target for the given graph and coordinates. This
* implementation uses {@link mxGraph.getCellAt}.
*/
drop(
graph: Graph,
evt: MouseEvent,
dropTarget: Cell | null = null,
x: number,
y: number
) {
this.dropHandler(graph, evt, dropTarget, x, y);
// Had to move this to after the insert because it will
// affect the scrollbars of the window in IE to try and
// make the complete container visible.
// LATER: Should be made optional.
if (graph.container.style.visibility !== 'hidden') {
graph.container.focus();
}
}
}
export default DragSource; | the_stack |
import FormControl from '@material-ui/core/FormControl';
import FormHelperText from '@material-ui/core/FormHelperText';
import IconButton from '@material-ui/core/IconButton';
import Input from '@material-ui/core/Input';
import InputAdornment from '@material-ui/core/InputAdornment';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import Paper from '@material-ui/core/Paper';
import { WithStyles, withStyles } from '@material-ui/core/styles';
import Close from '@material-ui/icons/Close';
import ArrowDown from '@material-ui/icons/KeyboardArrowDown';
import Debug from 'debug';
import Downshift from 'downshift';
import { inject, observer } from 'mobx-react';
import { IModelType, IStateTreeNode, flow, getEnv, getIdentifier, getSnapshot, types } from 'mobx-state-tree';
import * as React from 'react';
const debug = new Debug('selecter');
const renderSuggestion = ({ suggestion, index, itemProps, highlightedIndex, selectedItem }) => {
const isHighlighted = highlightedIndex === index;
const isSelected = selectedItem && selectedItem === suggestion.label;
return (
<MenuItem
{...itemProps}
key={suggestion.id}
selected={isHighlighted}
component='div'
style={{
fontWeight: isSelected ? 'bold' : 'normal',
}}
>
{suggestion.label}
</MenuItem>
);
};
interface SelectStore {
entries: Map<string, any>;
loading: boolean;
list: (term: string, id?: string) => Promise<{}>;
clear: () => void;
add: (model: any) => void;
readonly projection: { id: string, label: string }[];
}
interface SelectProps {
id: string;
required?: boolean;
label: string;
error?: any;
type?: string;
value?: any;
disabled?: boolean;
onChange?: (newVal: any) => void;
fieldProps?: any;
selectStore?: IModelType<any, SelectStore>;
addComponent?: React.ComponentType<{ onChange: (newVal: any) => void }>;
// injected
store?: SelectType;
}
interface SelectType {
selected?: string;
readonly selection: { id: string, label: string };
term: string;
readonly loading: boolean;
readonly records: {id: string, label: string}[];
list: (id?: string) => Promise<{}>;
updateTerm: (newVal: string) => Promise<{}>;
reset: () => Promise<{}>;
selectItem: (id: string) => Promise<{}>;
findById: (id: string) => {id: string, label: string};
modelById: (id: string) => any;
addModel: (model: any) => void;
}
const selectModel = types
.model(
{
selected: types.maybe(types.string),
term: types.optional(types.string, ''),
})
.views(self => ({
get loading() {
const select = getEnv(self).store as SelectStore;
return select.loading;
},
get records() {
const select = getEnv(self).store as SelectStore;
return select.projection;
}
}))
.actions(self => {
const list: (id?: string) => Promise<{}> = flow(function*(id?: string) {
const select = getEnv(self).store as SelectStore;
try {
yield select.list(self.term, id);
} catch (e) {
debug('error fetching: ', e);
}
});
const updateTerm = flow(function*(newVal: string) {
self.term = newVal;
yield list();
});
const reset = flow(function*() {
const select = getEnv(self).store as SelectStore;
select.clear();
self.selected = '';
self.term = '';
yield list();
});
const selectItem = flow(function*(id: string | IStateTreeNode) {
// when a value is already set, we need to 'select' it to display in the control
// the existing value could be a string Id or a model. Assume an 'id' value exists
if (typeof id !== 'string') {
id = getIdentifier(id);
}
if (!findById(id)) {
yield list(id);
}
self.selected = id;
});
const findById = (id: string) => {
return self.records.find(x => x.id === id);
};
const modelById = (id: string) => {
const select = getEnv(self).store as SelectStore;
return select.entries.get(id);
};
const addModel = (model: any) => {
const select = getEnv(self).store as SelectStore;
select.add(model);
};
return { findById, modelById, selectItem, list, updateTerm, reset, addModel };
})
.views(self => ({
get selection() {
if (!self.selected) {
return undefined;
}
const model = self.findById(self.selected);
return model == null ? undefined : model;
}
}));
// Double observer to observe the props received and the props used by the component (weird I know)
@observer
@inject((stores, props: SelectProps) => {
const modelStore = props.selectStore.create({}, { api: stores['store'].api });
props['store'] = selectModel.create({}, { store: modelStore });
return props;
})
@observer
class IntegrationDownshift extends React.Component<SelectProps & WithStyles<'paper' | 'root' | 'container' | 'formControl'>, {}> {
private _value: string;
private _clearSelection: () => void;
public componentDidMount() {
const { value, store } = this.props;
if (value) {
if (typeof value !== 'string') {
const snapshot = getSnapshot(value);
store.addModel(snapshot);
}
store.selectItem(value);
}
}
public async componentDidUpdate() {
const { value, store, onChange } = this.props;
if (!value && this._value) {
this._value = undefined;
this._clearSelection();
}
if (value) {
if (typeof value !== 'string') {
const snapshot = getSnapshot(value);
store.addModel(snapshot);
}
await store.selectItem(value);
onChange(getSnapshot(store.modelById(store.selection.id)));
}
}
// Called when input element changes
private onInput = (e: any) => {
const { store, onChange } = this.props;
const newVal = e.target.value;
const selectedValue = this._value && store.findById(this._value);
if (selectedValue && selectedValue.label !== newVal) {
onChange(undefined);
}
store.updateTerm(newVal);
}
// Called when downshift selects something
private selectionChanged = (selection?: {id: string, label: string}) => {
const { store, onChange } = this.props;
if (!selection) {
this._value = undefined;
onChange(undefined);
store.reset();
this._clearSelection();
return;
}
onChange(getSnapshot(store.modelById(selection.id)));
store.selectItem(selection.id);
this._value = selection.id;
}
private modelAdded = (model: any) => {
const { store, onChange } = this.props;
try {
onChange(model);
store.addModel(model);
const selected = store.records[0];
this._value = selected.id;
} catch (error) {
debug('failed to add model', error);
}
}
private openMenu = async (open: () => void) => {
const { store } = this.props;
await store.list();
open();
}
private _renderDownshift = (classes, error, required, label, id, fieldProps, store, value, disabled, addComponent) => ({ getInputProps, getItemProps, isOpen, inputValue, selectedItem, highlightedIndex, clearSelection, openMenu }) => {
this._clearSelection = clearSelection;
return (
<div className={classes.container}>
<FormControl required={required} className={classes.formControl} fullWidth disabled={disabled} error={error && error[id] ? true : false} aria-describedby={id + '-text'}>
<InputLabel htmlFor={id}>{label}</InputLabel>
<Input id={id} onInput={this.onInput} type='text' fullWidth {...fieldProps} {...getInputProps()} value={inputValue || ''} endAdornment={
value ?
<InputAdornment position='end'>
<IconButton
aria-label='Clear'
onClick={() => this.selectionChanged()}
disabled={disabled}
>
<Close />
</IconButton>
</InputAdornment>
:
<InputAdornment position='end'>
<IconButton
aria-label='Open'
onClick={() => this.openMenu(openMenu)}
disabled={disabled}
>
<ArrowDown />
</IconButton>
{addComponent && !disabled && React.createElement(addComponent, { onChange: this.modelAdded })}
</InputAdornment>
} />
{error && error[id] ? error[id].map((e, key) => (<FormHelperText key={key} id={id + '-' + key + '-text'}>{e}</FormHelperText>)) : undefined}
</FormControl>
{isOpen ? (
<Paper className={classes.paper} elevation={3} square>
{Array.from(store.records.values()).map((suggestion, index) =>
renderSuggestion({
suggestion,
index,
itemProps: getItemProps({ item: suggestion }),
highlightedIndex,
selectedItem,
}),
)}
</Paper>
) : null}
</div>
);
}
public render() {
const { classes, error, required, label, id, fieldProps, store, value, addComponent, disabled, onChange } = this.props;
return (
<div className={classes.root}>
<Downshift selectedItem={store.selection} onChange={this.selectionChanged} itemToString={item => item && item.label}>
{this._renderDownshift(classes, error, required, label, id, fieldProps, store, value, disabled, addComponent)}
</Downshift>
</div>
);
}
}
const styles = theme => ({
root: {
flexGrow: 1,
},
container: {
flexGrow: 1,
position: 'relative',
},
paper: {
position: 'absolute',
zIndex: 1,
marginTop: theme.spacing.unit,
left: 0,
right: 0,
},
formControl: {
marginLeft: theme.spacing.unit,
marginRight: theme.spacing.unit,
maxWidth: 400
},
});
export default withStyles(styles as any)<SelectProps>(IntegrationDownshift); | the_stack |
import * as msRest from "@azure/ms-rest-js";
export const QueryContext: msRest.CompositeMapper = {
serializedName: "QueryContext",
type: {
name: "Composite",
className: "QueryContext",
modelProperties: {
originalQuery: {
required: true,
serializedName: "originalQuery",
type: {
name: "String"
}
},
alteredQuery: {
readOnly: true,
serializedName: "alteredQuery",
type: {
name: "String"
}
},
alterationOverrideQuery: {
readOnly: true,
serializedName: "alterationOverrideQuery",
type: {
name: "String"
}
},
adultIntent: {
readOnly: true,
serializedName: "adultIntent",
type: {
name: "Boolean"
}
},
askUserForLocation: {
readOnly: true,
serializedName: "askUserForLocation",
type: {
name: "Boolean"
}
}
}
}
};
export const ResponseBase: msRest.CompositeMapper = {
serializedName: "ResponseBase",
type: {
name: "Composite",
polymorphicDiscriminator: {
serializedName: "_type",
clientName: "_type"
},
uberParent: "ResponseBase",
className: "ResponseBase",
modelProperties: {
_type: {
required: true,
serializedName: "_type",
type: {
name: "String"
}
}
}
}
};
export const Identifiable: msRest.CompositeMapper = {
serializedName: "Identifiable",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "Identifiable",
modelProperties: {
...ResponseBase.type.modelProperties,
id: {
readOnly: true,
serializedName: "id",
type: {
name: "String"
}
}
}
}
};
export const Response: msRest.CompositeMapper = {
serializedName: "Response",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "Response",
modelProperties: {
...Identifiable.type.modelProperties,
contractualRules: {
readOnly: true,
serializedName: "contractualRules",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ContractualRulesContractualRule"
}
}
}
},
webSearchUrl: {
readOnly: true,
serializedName: "webSearchUrl",
type: {
name: "String"
}
}
}
}
};
export const Thing: msRest.CompositeMapper = {
serializedName: "Thing",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "Thing",
modelProperties: {
...Response.type.modelProperties,
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
url: {
readOnly: true,
serializedName: "url",
type: {
name: "String"
}
},
image: {
readOnly: true,
serializedName: "image",
type: {
name: "Composite",
className: "ImageObject"
}
},
description: {
readOnly: true,
serializedName: "description",
type: {
name: "String"
}
},
entityPresentationInfo: {
readOnly: true,
serializedName: "entityPresentationInfo",
type: {
name: "Composite",
className: "EntitiesEntityPresentationInfo"
}
},
bingId: {
readOnly: true,
serializedName: "bingId",
type: {
name: "String"
}
}
}
}
};
export const CreativeWork: msRest.CompositeMapper = {
serializedName: "CreativeWork",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "CreativeWork",
modelProperties: {
...Thing.type.modelProperties,
thumbnailUrl: {
readOnly: true,
serializedName: "thumbnailUrl",
type: {
name: "String"
}
},
provider: {
readOnly: true,
serializedName: "provider",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Thing"
}
}
}
},
text: {
readOnly: true,
serializedName: "text",
type: {
name: "String"
}
}
}
}
};
export const MediaObject: msRest.CompositeMapper = {
serializedName: "MediaObject",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "MediaObject",
modelProperties: {
...CreativeWork.type.modelProperties,
contentUrl: {
readOnly: true,
serializedName: "contentUrl",
type: {
name: "String"
}
},
hostPageUrl: {
readOnly: true,
serializedName: "hostPageUrl",
type: {
name: "String"
}
},
width: {
readOnly: true,
serializedName: "width",
type: {
name: "Number"
}
},
height: {
readOnly: true,
serializedName: "height",
type: {
name: "Number"
}
}
}
}
};
export const ImageObject: msRest.CompositeMapper = {
serializedName: "ImageObject",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "ImageObject",
modelProperties: {
...MediaObject.type.modelProperties,
thumbnail: {
readOnly: true,
serializedName: "thumbnail",
type: {
name: "Composite",
className: "ImageObject"
}
}
}
}
};
export const EntitiesEntityPresentationInfo: msRest.CompositeMapper = {
serializedName: "Entities/EntityPresentationInfo",
type: {
name: "Composite",
className: "EntitiesEntityPresentationInfo",
modelProperties: {
entityScenario: {
required: true,
serializedName: "entityScenario",
defaultValue: 'DominantEntity',
type: {
name: "String"
}
},
entityTypeHints: {
readOnly: true,
serializedName: "entityTypeHints",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
},
entityTypeDisplayHint: {
readOnly: true,
serializedName: "entityTypeDisplayHint",
type: {
name: "String"
}
}
}
}
};
export const Answer: msRest.CompositeMapper = {
serializedName: "Answer",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "Answer",
modelProperties: {
...Response.type.modelProperties
}
}
};
export const SearchResultsAnswer: msRest.CompositeMapper = {
serializedName: "SearchResultsAnswer",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "SearchResultsAnswer",
modelProperties: {
...Answer.type.modelProperties,
queryContext: {
readOnly: true,
serializedName: "queryContext",
type: {
name: "Composite",
className: "QueryContext"
}
}
}
}
};
export const Entities: msRest.CompositeMapper = {
serializedName: "Entities",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "Entities",
modelProperties: {
...SearchResultsAnswer.type.modelProperties,
queryScenario: {
readOnly: true,
serializedName: "queryScenario",
defaultValue: 'DominantEntity',
type: {
name: "String"
}
},
value: {
required: true,
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Thing"
}
}
}
}
}
}
};
export const Places: msRest.CompositeMapper = {
serializedName: "Places",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "Places",
modelProperties: {
...SearchResultsAnswer.type.modelProperties,
value: {
required: true,
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Thing"
}
}
}
}
}
}
};
export const SearchResponse: msRest.CompositeMapper = {
serializedName: "SearchResponse",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "SearchResponse",
modelProperties: {
...Response.type.modelProperties,
queryContext: {
readOnly: true,
serializedName: "queryContext",
type: {
name: "Composite",
className: "QueryContext"
}
},
entities: {
readOnly: true,
serializedName: "entities",
type: {
name: "Composite",
className: "Entities"
}
},
places: {
readOnly: true,
serializedName: "places",
type: {
name: "Composite",
className: "Places"
}
}
}
}
};
export const ContractualRulesContractualRule: msRest.CompositeMapper = {
serializedName: "ContractualRules/ContractualRule",
type: {
name: "Composite",
polymorphicDiscriminator: {
serializedName: "_type",
clientName: "_type"
},
uberParent: "ContractualRulesContractualRule",
className: "ContractualRulesContractualRule",
modelProperties: {
targetPropertyName: {
readOnly: true,
serializedName: "targetPropertyName",
type: {
name: "String"
}
},
_type: {
required: true,
serializedName: "_type",
type: {
name: "String"
}
}
}
}
};
export const ErrorModel: msRest.CompositeMapper = {
serializedName: "Error",
type: {
name: "Composite",
className: "ErrorModel",
modelProperties: {
code: {
required: true,
serializedName: "code",
defaultValue: 'None',
type: {
name: "String"
}
},
subCode: {
readOnly: true,
serializedName: "subCode",
type: {
name: "String"
}
},
message: {
required: true,
serializedName: "message",
type: {
name: "String"
}
},
moreDetails: {
readOnly: true,
serializedName: "moreDetails",
type: {
name: "String"
}
},
parameter: {
readOnly: true,
serializedName: "parameter",
type: {
name: "String"
}
},
value: {
readOnly: true,
serializedName: "value",
type: {
name: "String"
}
}
}
}
};
export const ErrorResponse: msRest.CompositeMapper = {
serializedName: "ErrorResponse",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "ErrorResponse",
modelProperties: {
...Response.type.modelProperties,
errors: {
required: true,
serializedName: "errors",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ErrorModel"
}
}
}
}
}
}
};
export const Intangible: msRest.CompositeMapper = {
serializedName: "Intangible",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "Intangible",
modelProperties: {
...Thing.type.modelProperties
}
}
};
export const StructuredValue: msRest.CompositeMapper = {
serializedName: "StructuredValue",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "StructuredValue",
modelProperties: {
...Intangible.type.modelProperties
}
}
};
export const PostalAddress: msRest.CompositeMapper = {
serializedName: "PostalAddress",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "PostalAddress",
modelProperties: {
...StructuredValue.type.modelProperties,
streetAddress: {
readOnly: true,
serializedName: "streetAddress",
type: {
name: "String"
}
},
addressLocality: {
readOnly: true,
serializedName: "addressLocality",
type: {
name: "String"
}
},
addressSubregion: {
readOnly: true,
serializedName: "addressSubregion",
type: {
name: "String"
}
},
addressRegion: {
readOnly: true,
serializedName: "addressRegion",
type: {
name: "String"
}
},
postalCode: {
readOnly: true,
serializedName: "postalCode",
type: {
name: "String"
}
},
postOfficeBoxNumber: {
readOnly: true,
serializedName: "postOfficeBoxNumber",
type: {
name: "String"
}
},
addressCountry: {
readOnly: true,
serializedName: "addressCountry",
type: {
name: "String"
}
},
countryIso: {
readOnly: true,
serializedName: "countryIso",
type: {
name: "String"
}
},
neighborhood: {
readOnly: true,
serializedName: "neighborhood",
type: {
name: "String"
}
},
addressRegionAbbreviation: {
readOnly: true,
serializedName: "addressRegionAbbreviation",
type: {
name: "String"
}
},
text: {
readOnly: true,
serializedName: "text",
type: {
name: "String"
}
}
}
}
};
export const Place: msRest.CompositeMapper = {
serializedName: "Place",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "Place",
modelProperties: {
...Thing.type.modelProperties,
address: {
readOnly: true,
serializedName: "address",
type: {
name: "Composite",
className: "PostalAddress"
}
},
telephone: {
readOnly: true,
serializedName: "telephone",
type: {
name: "String"
}
}
}
}
};
export const Organization: msRest.CompositeMapper = {
serializedName: "Organization",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "Organization",
modelProperties: {
...Thing.type.modelProperties
}
}
};
export const LocalBusiness: msRest.CompositeMapper = {
serializedName: "LocalBusiness",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "LocalBusiness",
modelProperties: {
...Place.type.modelProperties,
priceRange: {
readOnly: true,
serializedName: "priceRange",
type: {
name: "String"
}
},
panoramas: {
readOnly: true,
serializedName: "panoramas",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ImageObject"
}
}
}
},
isPermanentlyClosed: {
readOnly: true,
serializedName: "isPermanentlyClosed",
type: {
name: "Boolean"
}
},
tagLine: {
readOnly: true,
serializedName: "tagLine",
type: {
name: "String"
}
}
}
}
};
export const EntertainmentBusiness: msRest.CompositeMapper = {
serializedName: "EntertainmentBusiness",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "EntertainmentBusiness",
modelProperties: {
...LocalBusiness.type.modelProperties
}
}
};
export const MovieTheater: msRest.CompositeMapper = {
serializedName: "MovieTheater",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "MovieTheater",
modelProperties: {
...EntertainmentBusiness.type.modelProperties,
screenCount: {
readOnly: true,
serializedName: "screenCount",
type: {
name: "Number"
}
}
}
}
};
export const ContractualRulesAttribution: msRest.CompositeMapper = {
serializedName: "ContractualRules/Attribution",
type: {
name: "Composite",
polymorphicDiscriminator: ContractualRulesContractualRule.type.polymorphicDiscriminator,
uberParent: "ContractualRulesContractualRule",
className: "ContractualRulesAttribution",
modelProperties: {
...ContractualRulesContractualRule.type.modelProperties,
mustBeCloseToContent: {
readOnly: true,
serializedName: "mustBeCloseToContent",
type: {
name: "Boolean"
}
}
}
}
};
export const CivicStructure: msRest.CompositeMapper = {
serializedName: "CivicStructure",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "CivicStructure",
modelProperties: {
...Place.type.modelProperties
}
}
};
export const TouristAttraction: msRest.CompositeMapper = {
serializedName: "TouristAttraction",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "TouristAttraction",
modelProperties: {
...Place.type.modelProperties
}
}
};
export const Airport: msRest.CompositeMapper = {
serializedName: "Airport",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "Airport",
modelProperties: {
...CivicStructure.type.modelProperties,
iataCode: {
readOnly: true,
serializedName: "iataCode",
type: {
name: "String"
}
},
icaoCode: {
readOnly: true,
serializedName: "icaoCode",
type: {
name: "String"
}
}
}
}
};
export const License: msRest.CompositeMapper = {
serializedName: "License",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "License",
modelProperties: {
...CreativeWork.type.modelProperties
}
}
};
export const ContractualRulesLicenseAttribution: msRest.CompositeMapper = {
serializedName: "ContractualRules/LicenseAttribution",
type: {
name: "Composite",
polymorphicDiscriminator: ContractualRulesContractualRule.type.polymorphicDiscriminator,
uberParent: "ContractualRulesContractualRule",
className: "ContractualRulesLicenseAttribution",
modelProperties: {
...ContractualRulesAttribution.type.modelProperties,
license: {
readOnly: true,
serializedName: "license",
type: {
name: "Composite",
className: "License"
}
},
licenseNotice: {
readOnly: true,
serializedName: "licenseNotice",
type: {
name: "String"
}
}
}
}
};
export const ContractualRulesLinkAttribution: msRest.CompositeMapper = {
serializedName: "ContractualRules/LinkAttribution",
type: {
name: "Composite",
polymorphicDiscriminator: ContractualRulesContractualRule.type.polymorphicDiscriminator,
uberParent: "ContractualRulesContractualRule",
className: "ContractualRulesLinkAttribution",
modelProperties: {
...ContractualRulesAttribution.type.modelProperties,
text: {
required: true,
serializedName: "text",
type: {
name: "String"
}
},
url: {
required: true,
serializedName: "url",
type: {
name: "String"
}
},
optionalForListDisplay: {
readOnly: true,
serializedName: "optionalForListDisplay",
type: {
name: "Boolean"
}
}
}
}
};
export const ContractualRulesMediaAttribution: msRest.CompositeMapper = {
serializedName: "ContractualRules/MediaAttribution",
type: {
name: "Composite",
polymorphicDiscriminator: ContractualRulesContractualRule.type.polymorphicDiscriminator,
uberParent: "ContractualRulesContractualRule",
className: "ContractualRulesMediaAttribution",
modelProperties: {
...ContractualRulesAttribution.type.modelProperties,
url: {
readOnly: true,
serializedName: "url",
type: {
name: "String"
}
}
}
}
};
export const ContractualRulesTextAttribution: msRest.CompositeMapper = {
serializedName: "ContractualRules/TextAttribution",
type: {
name: "Composite",
polymorphicDiscriminator: ContractualRulesContractualRule.type.polymorphicDiscriminator,
uberParent: "ContractualRulesContractualRule",
className: "ContractualRulesTextAttribution",
modelProperties: {
...ContractualRulesAttribution.type.modelProperties,
text: {
required: true,
serializedName: "text",
type: {
name: "String"
}
},
optionalForListDisplay: {
readOnly: true,
serializedName: "optionalForListDisplay",
type: {
name: "Boolean"
}
}
}
}
};
export const FoodEstablishment: msRest.CompositeMapper = {
serializedName: "FoodEstablishment",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "FoodEstablishment",
modelProperties: {
...LocalBusiness.type.modelProperties
}
}
};
export const LodgingBusiness: msRest.CompositeMapper = {
serializedName: "LodgingBusiness",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "LodgingBusiness",
modelProperties: {
...LocalBusiness.type.modelProperties
}
}
};
export const Restaurant: msRest.CompositeMapper = {
serializedName: "Restaurant",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "Restaurant",
modelProperties: {
...FoodEstablishment.type.modelProperties,
acceptsReservations: {
readOnly: true,
serializedName: "acceptsReservations",
type: {
name: "Boolean"
}
},
reservationUrl: {
readOnly: true,
serializedName: "reservationUrl",
type: {
name: "String"
}
},
servesCuisine: {
readOnly: true,
serializedName: "servesCuisine",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
},
menuUrl: {
readOnly: true,
serializedName: "menuUrl",
type: {
name: "String"
}
}
}
}
};
export const Hotel: msRest.CompositeMapper = {
serializedName: "Hotel",
type: {
name: "Composite",
polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator,
uberParent: "ResponseBase",
className: "Hotel",
modelProperties: {
...LodgingBusiness.type.modelProperties,
hotelClass: {
readOnly: true,
serializedName: "hotelClass",
type: {
name: "String"
}
},
amenities: {
readOnly: true,
serializedName: "amenities",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
}
}
}
};
export const discriminators = {
'ResponseBase.ImageObject' : ImageObject,
'ResponseBase.Thing' : Thing,
'ResponseBase.Entities' : Entities,
'ResponseBase.Places' : Places,
'ResponseBase.SearchResponse' : SearchResponse,
'ContractualRules/ContractualRule' : ContractualRulesContractualRule,
'ResponseBase.Response' : Response,
'ResponseBase.SearchResultsAnswer' : SearchResultsAnswer,
'ResponseBase.Identifiable' : Identifiable,
'ResponseBase.Answer' : Answer,
'ResponseBase.ErrorResponse' : ErrorResponse,
'ResponseBase.PostalAddress' : PostalAddress,
'ResponseBase.Place' : Place,
'ResponseBase.Organization' : Organization,
'ResponseBase' : ResponseBase,
'ResponseBase.CreativeWork' : CreativeWork,
'ResponseBase.Intangible' : Intangible,
'ResponseBase.MovieTheater' : MovieTheater,
'ContractualRulesContractualRule.ContractualRules/Attribution' : ContractualRulesAttribution,
'ResponseBase.MediaObject' : MediaObject,
'ResponseBase.CivicStructure' : CivicStructure,
'ResponseBase.LocalBusiness' : LocalBusiness,
'ResponseBase.TouristAttraction' : TouristAttraction,
'ResponseBase.Airport' : Airport,
'ResponseBase.License' : License,
'ResponseBase.StructuredValue' : StructuredValue,
'ResponseBase.EntertainmentBusiness' : EntertainmentBusiness,
'ContractualRulesContractualRule.ContractualRules/LicenseAttribution' : ContractualRulesLicenseAttribution,
'ContractualRulesContractualRule.ContractualRules/LinkAttribution' : ContractualRulesLinkAttribution,
'ContractualRulesContractualRule.ContractualRules/MediaAttribution' : ContractualRulesMediaAttribution,
'ContractualRulesContractualRule.ContractualRules/TextAttribution' : ContractualRulesTextAttribution,
'ResponseBase.FoodEstablishment' : FoodEstablishment,
'ResponseBase.LodgingBusiness' : LodgingBusiness,
'ResponseBase.Restaurant' : Restaurant,
'ResponseBase.Hotel' : Hotel
}; | the_stack |
import { expect } from 'chai';
import { SinonStub, stub } from 'sinon';
import Volume from '../../../src/compose/volume';
import * as logTypes from '../../../src/lib/log-types';
import * as logger from '../../../src/logger';
import { createVolume, withMockerode } from '../../lib/mockerode';
describe('compose/volume', () => {
describe('creating a volume from a compose object', () => {
it('should use proper defaults when no compose configuration is provided', () => {
const volume = Volume.fromComposeObject(
'my_volume',
1234,
'deadbeef',
{},
);
expect(volume.name).to.equal('my_volume');
expect(volume.appId).to.equal(1234);
expect(volume.appUuid).to.equal('deadbeef');
expect(volume.config).to.deep.equal({
driver: 'local',
driverOpts: {},
labels: {
'io.balena.supervised': 'true',
'io.balena.app-uuid': 'deadbeef',
},
});
});
it('should correctly parse compose volumes without an explicit driver', () => {
const volume = Volume.fromComposeObject(
'one_volume',
1032480,
'deadbeef',
{
driver_opts: {
opt1: 'test',
},
labels: {
'my-label': 'test-label',
},
},
);
expect(volume).to.have.property('appId').that.equals(1032480);
expect(volume).to.have.property('name').that.equals('one_volume');
expect(volume)
.to.have.property('config')
.that.has.property('labels')
.that.deep.equals({
'io.balena.supervised': 'true',
'io.balena.app-uuid': 'deadbeef',
'my-label': 'test-label',
});
expect(volume)
.to.have.property('config')
.that.has.property('driverOpts')
.that.deep.equals({
opt1: 'test',
});
expect(volume)
.to.have.property('config')
.that.has.property('driver')
.that.equals('local');
});
it('should correctly parse compose volumes with an explicit driver', () => {
const volume = Volume.fromComposeObject(
'one_volume',
1032480,
'deadbeef',
{
driver: 'other',
driver_opts: {
opt1: 'test',
},
labels: {
'my-label': 'test-label',
},
},
);
expect(volume).to.have.property('appId').that.equals(1032480);
expect(volume).to.have.property('name').that.equals('one_volume');
expect(volume)
.to.have.property('config')
.that.has.property('labels')
.that.deep.equals({
'io.balena.supervised': 'true',
'io.balena.app-uuid': 'deadbeef',
'my-label': 'test-label',
});
expect(volume)
.to.have.property('config')
.that.has.property('driverOpts')
.that.deep.equals({
opt1: 'test',
});
expect(volume)
.to.have.property('config')
.that.has.property('driver')
.that.equals('other');
});
});
describe('creating a volume instance from a docker volume', () => {
it('should correctly parse app id from volume name', () => {
const volume = Volume.fromDockerVolume({
Driver: 'local',
Name: '1234_my_volume',
Mountpoint: '/var/lib/docker/volumes/1032480_one_volume/_data',
Labels: {},
Options: {},
Scope: 'local',
});
expect(volume.name).to.equal('my_volume');
expect(volume.appId).to.equal(1234);
});
it('should fail if volume name is not properly formatted', () => {
expect(() =>
Volume.fromDockerVolume({
Driver: 'local',
Name: 'non_supervised_volume',
Mountpoint: '/var/lib/docker/volumes/1032480_one_volume/_data',
Labels: {},
Options: {},
Scope: 'local',
}),
).to.throw;
});
it('should correctly parse docker volumes', () => {
const volume = Volume.fromDockerVolume({
Driver: 'local',
Labels: {
'io.balena.supervised': 'true',
'io.balena.app-uuid': 'deadbeef',
},
Mountpoint: '/var/lib/docker/volumes/1032480_one_volume/_data',
Name: '1032480_one_volume',
Options: {},
Scope: 'local',
});
expect(volume).to.have.property('appId').that.equals(1032480);
expect(volume).to.have.property('name').that.equals('one_volume');
expect(volume).to.have.property('appUuid').that.equals('deadbeef');
expect(volume)
.to.have.property('config')
.that.has.property('labels')
.that.deep.equals({
'io.balena.supervised': 'true',
'io.balena.app-uuid': 'deadbeef',
});
expect(volume)
.to.have.property('config')
.that.has.property('driverOpts')
.that.deep.equals({});
expect(volume)
.to.have.property('config')
.that.has.property('driver')
.that.equals('local');
});
});
describe('creating a docker volume from options', () => {
before(() => {
stub(logger, 'logSystemEvent');
});
afterEach(() => {
(logger.logSystemEvent as SinonStub).reset();
});
after(() => {
(logger.logSystemEvent as SinonStub).restore();
});
it('should use defaults to create the volume when no options are given', async () => {
await withMockerode(async (mockerode) => {
const volume = Volume.fromComposeObject(
'one_volume',
1032480,
'deadbeef',
);
await volume.create();
expect(mockerode.createVolume).to.have.been.calledOnceWith({
Name: '1032480_one_volume',
Driver: 'local',
Labels: {
'io.balena.supervised': 'true',
'io.balena.app-uuid': 'deadbeef',
},
DriverOpts: {},
});
});
});
it('should pass configuration options to the engine', async () => {
await withMockerode(async (mockerode) => {
const volume = Volume.fromComposeObject(
'one_volume',
1032480,
'deadbeef',
{
driver_opts: {
opt1: 'test',
},
labels: {
'my-label': 'test-label',
},
},
);
await volume.create();
expect(mockerode.createVolume).to.have.been.calledOnceWith({
Name: '1032480_one_volume',
Driver: 'local',
Labels: {
'my-label': 'test-label',
'io.balena.supervised': 'true',
'io.balena.app-uuid': 'deadbeef',
},
DriverOpts: {
opt1: 'test',
},
});
expect(logger.logSystemEvent).to.have.been.calledOnceWith(
logTypes.createVolume,
);
});
});
it('should log successful volume creation to the cloud', async () => {
await withMockerode(async (mockerode) => {
const volume = Volume.fromComposeObject(
'one_volume',
1032480,
'deadbeef',
);
await volume.create();
expect(mockerode.createVolume).to.have.been.calledOnce;
expect(logger.logSystemEvent).to.have.been.calledOnceWith(
logTypes.createVolume,
);
});
});
});
describe('comparing volume configuration', () => {
it('should ignore name and supervisor labels in the comparison', () => {
expect(
Volume.fromComposeObject('aaa', 1234, 'deadbeef').isEqualConfig(
Volume.fromComposeObject('bbb', 4567, 'deadbeef', {
driver: 'local',
driver_opts: {},
}),
),
).to.be.true;
expect(
Volume.fromComposeObject('aaa', 1234, 'deadbeef').isEqualConfig(
Volume.fromComposeObject('bbb', 4567, 'deadc0de'),
),
).to.be.true;
expect(
Volume.fromComposeObject('aaa', 1234, 'deadbeef').isEqualConfig(
Volume.fromDockerVolume({
Name: '1234_aaa',
Driver: 'local',
Labels: {
'io.balena.supervised': 'true',
'io.balena.app-uuid': 'deadbeef',
},
Options: {},
Mountpoint: '/var/lib/docker/volumes/1032480_one_volume/_data',
Scope: 'local',
}),
),
).to.be.true;
// the app-uuid should be omitted from the comparison
expect(
Volume.fromComposeObject('aaa', 1234, 'deadbeef').isEqualConfig(
Volume.fromDockerVolume({
Name: '1234_aaa',
Driver: 'local',
Labels: {
'io.balena.supervised': 'true',
},
Options: {},
Mountpoint: '/var/lib/docker/volumes/1032480_one_volume/_data',
Scope: 'local',
}),
),
).to.be.true;
expect(
Volume.fromComposeObject('aaa', 1234, null as any).isEqualConfig(
Volume.fromDockerVolume({
Name: '4567_bbb',
Driver: 'local',
Labels: {
'io.balena.supervised': 'true',
},
Options: {},
Mountpoint: '/var/lib/docker/volumes/1032480_one_volume/_data',
Scope: 'local',
}),
),
).to.be.true;
expect(
Volume.fromComposeObject('aaa', 1234, 'deadbeef').isEqualConfig(
Volume.fromDockerVolume({
Name: '1234_aaa',
Driver: 'local',
Labels: {
'some.other.label': '123',
'io.balena.supervised': 'true',
'io.balena.app-uuid': 'deadbeef',
},
Options: {},
Mountpoint: '/var/lib/docker/volumes/1032480_one_volume/_data',
Scope: 'local',
}),
),
).to.be.false;
});
it('should compare based on driver configuration and options', () => {
expect(
Volume.fromComposeObject('aaa', 1234, 'deadbeef').isEqualConfig(
Volume.fromComposeObject('aaa', 1234, 'deadbeef', {
driver: 'other',
driver_opts: {},
}),
),
).to.be.false;
expect(
Volume.fromComposeObject('aaa', 1234, 'deadbeef', {
driver: 'other',
}).isEqualConfig(
Volume.fromComposeObject('aaa', 1234, 'deadbeef', {
driver: 'other',
driver_opts: {},
}),
),
).to.be.true;
expect(
Volume.fromComposeObject('aaa', 1234, 'deadbeef', {}).isEqualConfig(
Volume.fromComposeObject('aaa', 1234, 'deadbeef', {
driver_opts: { opt: '123' },
}),
),
).to.be.false;
expect(
Volume.fromComposeObject('aaa', 1234, 'deadbeef', {
driver: 'other',
labels: { 'some.other.label': '123' },
driver_opts: { 'some-opt': '123' },
}).isEqualConfig(
Volume.fromDockerVolume({
Name: '1234_aaa',
Driver: 'other',
Labels: {
'some.other.label': '123',
'io.balena.supervised': 'true',
},
Options: {},
Mountpoint: '/var/lib/docker/volumes/1032480_one_volume/_data',
Scope: 'local',
}),
),
).to.be.false;
expect(
Volume.fromComposeObject('aaa', 1234, 'deadbeef', {
driver: 'other',
labels: { 'some.other.label': '123' },
driver_opts: { 'some-opt': '123' },
}).isEqualConfig(
Volume.fromDockerVolume({
Name: '1234_aaa',
Driver: 'other',
Labels: {
'some.other.label': '123',
'io.balena.supervised': 'true',
},
Options: { 'some-opt': '123' },
Mountpoint: '/var/lib/docker/volumes/1032480_one_volume/_data',
Scope: 'local',
}),
),
).to.be.true;
});
});
describe('removing volumes', () => {
before(() => {
stub(logger, 'logSystemEvent');
});
afterEach(() => {
(logger.logSystemEvent as SinonStub).reset();
});
after(() => {
(logger.logSystemEvent as SinonStub).restore();
});
it('should remove the volume from the engine if it exists', async () => {
const dockerVolume = createVolume({
Name: '1234_aaa',
});
await withMockerode(
async (mockerode) => {
const volume = Volume.fromComposeObject('aaa', 1234, 'deadbeef');
// Check engine state before (this is really to test that mockerode is doing its job)
expect((await mockerode.listVolumes()).Volumes).to.have.lengthOf(1);
expect(await mockerode.getVolume('1234_aaa').inspect()).to.deep.equal(
dockerVolume.inspectInfo,
);
// Remove the volume
await volume.remove();
// Check that the remove method was called
expect(mockerode.removeVolume).to.have.been.calledOnceWith(
'1234_aaa',
);
},
{ volumes: [dockerVolume] },
);
});
it('should report the volume removal as a system event', async () => {
const dockerVolume = createVolume({
Name: '1234_aaa',
});
await withMockerode(
async (mockerode) => {
const volume = Volume.fromComposeObject('aaa', 1234, 'deadbeef');
// Check engine state before
expect((await mockerode.listVolumes()).Volumes).to.have.lengthOf(1);
// Remove the volume
await volume.remove();
// Check that the remove method was called
expect(mockerode.removeVolume).to.have.been.calledOnceWith(
'1234_aaa',
);
// Check that log entry was generated
expect(logger.logSystemEvent).to.have.been.calledOnceWith(
logTypes.removeVolume,
);
},
{ volumes: [dockerVolume] },
);
});
it('should report an error if the volume does not exist', async () => {
const dockerVolume = createVolume({
Name: '4567_bbb',
});
await withMockerode(
async (mockerode) => {
const volume = Volume.fromComposeObject('aaa', 1234, 'deadbeef');
// Check engine state before
expect((await mockerode.listVolumes()).Volumes).to.have.lengthOf(1);
// Remove the volume, this should not throw
await expect(volume.remove()).to.not.be.rejected;
// Check that the remove method was called
expect(mockerode.removeVolume).to.not.have.been.called;
// Check that log entry was generated
expect(logger.logSystemEvent).to.have.been.calledWith(
logTypes.removeVolumeError,
);
},
{ volumes: [dockerVolume] },
);
});
it('should report an error if a problem happens while removing the volume', async () => {
const dockerVolume = createVolume({
Name: '1234_aaa',
});
await withMockerode(
async (mockerode) => {
const volume = Volume.fromComposeObject('aaa', 1234, 'deadbeef');
// Stub the mockerode method to fail
mockerode.removeVolume.rejects('Something bad happened');
// Check engine state before
expect((await mockerode.listVolumes()).Volumes).to.have.lengthOf(1);
// Remove the volume, this should not throw
await expect(volume.remove()).to.not.be.rejected;
// Check that log entry was generated
expect(logger.logSystemEvent).to.have.been.calledWith(
logTypes.removeVolumeError,
);
},
{ volumes: [dockerVolume] },
);
});
});
}); | the_stack |
import test, { Macro } from 'ava';
import * as fc from 'fast-check';
import {
attemptCashAddressFormatErrorCorrection,
CashAddressAvailableSizesInBits,
CashAddressAvailableTypes,
CashAddressCorrectionError,
CashAddressDecodingError,
CashAddressEncodingError,
CashAddressNetworkPrefix,
CashAddressType,
CashAddressVersionByte,
CashAddressVersionByteDecodingError,
decodeBase58AddressFormat,
decodeCashAddress,
decodeCashAddressFormat,
decodeCashAddressFormatWithoutPrefix,
decodeCashAddressVersionByte,
encodeCashAddress,
encodeCashAddressFormat,
encodeCashAddressVersionByte,
hexToBin,
instantiateSha256,
maskCashAddressPrefix,
splitEvery,
} from '../lib';
import * as cashAddrJson from './fixtures/cashaddr.json';
const maxUint8Number = 255;
const fcUint8Array = (length: number) =>
fc
.array(fc.integer(0, maxUint8Number), length, length)
.map((a) => Uint8Array.from(a));
const lowercaseLetter = () =>
fc.integer(97, 122).map((i) => String.fromCharCode(i));
const cashAddressTestVectors = Object.values(cashAddrJson).filter(
(item) => !Array.isArray(item)
);
test('maskCashAddressPrefix', (t) => {
// prettier-ignore
const payloadPrefix = [2, 9, 20, 3, 15, 9, 14, 3, 1, 19, 8];
t.deepEqual(maskCashAddressPrefix('bitcoincash'), payloadPrefix);
});
test('encodeCashAddressVersionByte', (t) => {
t.deepEqual(
encodeCashAddressVersionByte(0, 160),
CashAddressVersionByte.P2PKH
);
t.deepEqual(
encodeCashAddressVersionByte(1, 160),
CashAddressVersionByte.P2SH
);
});
test('decodeCashAddressVersionByte', (t) => {
t.deepEqual(decodeCashAddressVersionByte(CashAddressVersionByte.P2PKH), {
bitLength: 160,
type: 0,
});
t.deepEqual(decodeCashAddressVersionByte(CashAddressVersionByte.P2SH), {
bitLength: 160,
type: 1,
});
t.deepEqual(
decodeCashAddressVersionByte(0b10000000),
CashAddressVersionByteDecodingError.reservedBitSet
);
t.deepEqual(decodeCashAddressVersionByte(0b01000011), {
bitLength: 256,
type: 8,
});
t.deepEqual(decodeCashAddressVersionByte(0b01111111), {
bitLength: 512,
type: 15,
});
});
test('encodeCashAddress: works', (t) => {
const hash = hexToBin('15d16c84669ab46059313bf0747e781f1d13936d');
t.deepEqual(
encodeCashAddress(
CashAddressNetworkPrefix.testnet,
CashAddressVersionByte.P2PKH,
hash
),
'bchtest:qq2azmyyv6dtgczexyalqar70q036yund53jvfde0x'
);
t.deepEqual(
encodeCashAddress('bchtest', 0, hash),
'bchtest:qq2azmyyv6dtgczexyalqar70q036yund53jvfde0x'
);
t.deepEqual(
encodeCashAddress(
CashAddressNetworkPrefix.mainnet,
CashAddressVersionByte.P2PKH,
hash
),
'bitcoincash:qq2azmyyv6dtgczexyalqar70q036yund54qgw0wg6'
);
t.deepEqual(
encodeCashAddress('bitcoincash', 0, hash),
'bitcoincash:qq2azmyyv6dtgczexyalqar70q036yund54qgw0wg6'
);
t.deepEqual(
encodeCashAddress(
CashAddressNetworkPrefix.regtest,
CashAddressVersionByte.P2PKH,
hash
),
'bchreg:qq2azmyyv6dtgczexyalqar70q036yund5tw6gw2vq'
);
t.deepEqual(
encodeCashAddress('bchreg', 0, hash),
'bchreg:qq2azmyyv6dtgczexyalqar70q036yund5tw6gw2vq'
);
t.deepEqual(
encodeCashAddressFormat(
'bitauth',
encodeCashAddressVersionByte(0, 256),
hexToBin(
'978306aa4e02fd06e251b38d2e961f78f4af2ea6524a3e4531126776276a6af1'
)
),
'bitauth:qwtcxp42fcp06phz2xec6t5krau0ftew5efy50j9xyfxwa38df40zp58z6t5w'
);
t.deepEqual(
encodeCashAddress('broken', 0, hexToBin('97')),
CashAddressEncodingError.unsupportedHashLength
);
});
test('decodeCashAddress: works', (t) => {
const hash = hexToBin('15d16c84669ab46059313bf0747e781f1d13936d');
const result = decodeCashAddress(
'bchtest:qq2azmyyv6dtgczexyalqar70q036yund53jvfde0x'
);
// eslint-disable-next-line functional/no-conditional-statement
if (typeof result === 'string') {
t.log(result);
t.fail();
}
t.deepEqual(result, { hash, prefix: 'bchtest', type: 0 });
t.deepEqual(
decodeCashAddress('bchtest:qq2azmyyv6dtgczexyalqar70q036yund53jvfde0x'),
{
hash,
prefix: CashAddressNetworkPrefix.testnet,
type: CashAddressType.P2PKH,
}
);
t.deepEqual(
decodeCashAddress('bitcoincash:qq2azmyyv6dtgczexyalqar70q036yund54qgw0wg6'),
{
hash,
prefix: CashAddressNetworkPrefix.mainnet,
type: CashAddressType.P2PKH,
}
);
t.deepEqual(
decodeCashAddress('bitcoincash:qq2azmyyv6dtgczexyalqar70q036yund54qgw0wg6'),
{ hash, prefix: 'bitcoincash', type: 0 }
);
t.deepEqual(
decodeCashAddress('bchreg:qq2azmyyv6dtgczexyalqar70q036yund5tw6gw2vq'),
{
hash,
prefix: CashAddressNetworkPrefix.regtest,
type: CashAddressType.P2PKH,
}
);
t.deepEqual(
decodeCashAddress('bchreg:qq2azmyyv6dtgczexyalqar70q036yund5tw6gw2vq'),
{ hash, prefix: 'bchreg', type: 0 }
);
t.deepEqual(
decodeCashAddressFormat(
'bitauth:qwtcxp42fcp06phz2xec6t5krau0ftew5efy50j9xyfxwa38df40zp58z6t5w'
),
{
hash: hexToBin(
'978306aa4e02fd06e251b38d2e961f78f4af2ea6524a3e4531126776276a6af1'
),
prefix: 'bitauth',
version: encodeCashAddressVersionByte(0, 256),
}
);
t.deepEqual(
decodeCashAddressFormat(
':qwtcxp42fcp06phz2xec6t5krau0ftew5efy50j9xyfxwa38df40zp58z6t5w'
),
CashAddressDecodingError.invalidFormat
);
t.deepEqual(
decodeCashAddress('prefix:broken'),
CashAddressDecodingError.invalidCharacters
);
t.deepEqual(
decodeCashAddressFormat('prefix:broken'),
CashAddressDecodingError.invalidCharacters
);
t.deepEqual(
// cspell: disable-next-line
decodeCashAddressFormat('verybroken:lll30n6j98m5'),
CashAddressDecodingError.improperPadding
);
t.deepEqual(
// cspell: disable-next-line
decodeCashAddressFormat('bchtest:testnetaddress4d6njnut'),
CashAddressDecodingError.improperPadding
);
t.deepEqual(
decodeCashAddress(
'bchreg:555555555555555555555555555555555555555555555udxmlmrz'
),
CashAddressDecodingError.reservedByte
);
t.deepEqual(
decodeCashAddress('bitcoincash:qu2azmyyv6dtgczexyalqar70q036yund53an46hf6'),
CashAddressDecodingError.mismatchedHashLength
);
});
test('CashAddress test vectors', (t) => {
cashAddressTestVectors.forEach((vector) => {
const { cashaddr } = vector;
const [prefix] = cashaddr.split(':');
const payload = hexToBin(vector.payload);
const type = vector.type as CashAddressAvailableTypes;
const encodeResult = encodeCashAddress(prefix, type, payload);
// eslint-disable-next-line functional/no-conditional-statement
if (cashaddr !== encodeResult) {
t.log('expected vector', vector.cashaddr);
t.log('type', type);
t.log('prefix', prefix);
t.log('payload', payload);
t.log('encodeResult', encodeResult);
}
t.deepEqual(vector.cashaddr, encodeResult);
const decodeResult = decodeCashAddress(cashaddr);
// eslint-disable-next-line functional/no-conditional-statement
if (typeof decodeResult === 'string') {
t.log(decodeResult);
t.fail();
}
t.deepEqual(decodeResult, { hash: payload, prefix, type });
});
});
test('decodeCashAddressWithoutPrefix', (t) => {
const hash = hexToBin('15d16c84669ab46059313bf0747e781f1d13936d');
t.deepEqual(
decodeCashAddressFormatWithoutPrefix(
'qq2azmyyv6dtgczexyalqar70q036yund53jvfde0x'
),
{ hash, prefix: 'bchtest', version: 0 }
);
t.deepEqual(
decodeCashAddressFormatWithoutPrefix(
'qq2azmyyv6dtgczexyalqar70q036yund54qgw0wg6'
),
{ hash, prefix: 'bitcoincash', version: 0 }
);
t.deepEqual(
decodeCashAddressFormatWithoutPrefix(
'qq2azmyyv6dtgczexyalqar70q036yund5tw6gw2vq'
),
{ hash, prefix: 'bchreg', version: 0 }
);
t.deepEqual(
decodeCashAddressFormatWithoutPrefix(
'qwtcxp42fcp06phz2xec6t5krau0ftew5efy50j9xyfxwa38df40zp58z6t5w',
['bitauth']
),
{
hash: hexToBin(
'978306aa4e02fd06e251b38d2e961f78f4af2ea6524a3e4531126776276a6af1'
),
prefix: 'bitauth',
version: encodeCashAddressVersionByte(0, 256),
}
);
t.deepEqual(
// cspell: disable-next-line
decodeCashAddressFormatWithoutPrefix('qwtcxp42fcp06phz', ['bitauth']),
CashAddressDecodingError.invalidChecksum
);
});
test('[fast-check] encodeCashAddress <-> decodeCashAddress', (t) => {
const roundTripWithHashLength = (
hashLength: CashAddressAvailableSizesInBits
) =>
fc.property(
fc.array(lowercaseLetter(), 1, 50).map((arr) => arr.join('')),
fc.nat(15),
fcUint8Array(hashLength / 8),
(prefix, type, hash) => {
// t.log(decodeCashAddressVersionByte(version));
t.deepEqual(
decodeCashAddress(
encodeCashAddress(prefix, type as CashAddressAvailableTypes, hash)
),
{ hash, prefix, type }
);
}
);
t.notThrows(() => {
fc.assert(roundTripWithHashLength(160));
fc.assert(roundTripWithHashLength(192));
fc.assert(roundTripWithHashLength(224));
fc.assert(roundTripWithHashLength(256));
fc.assert(roundTripWithHashLength(320));
fc.assert(roundTripWithHashLength(384));
fc.assert(roundTripWithHashLength(448));
fc.assert(roundTripWithHashLength(512));
});
});
test('attemptCashAddressErrorCorrection', (t) => {
t.deepEqual(
attemptCashAddressFormatErrorCorrection(
// cspell: disable-next-line
':qq2azmyyv6dtgczexyalqar70q036yund53jvfde0c'
),
CashAddressDecodingError.invalidFormat
);
t.deepEqual(
attemptCashAddressFormatErrorCorrection(
// cspell: disable-next-line
'broken:broken'
),
CashAddressDecodingError.invalidCharacters
);
t.deepEqual(
attemptCashAddressFormatErrorCorrection(
// cspell: disable-next-line
'achtest:qq2azmyyv6dtgczexyalqar70q036yund53jvfde0c'
),
{
address: 'bchtest:qq2azmyyv6dtgczexyalqar70q036yund53jvfde0x',
corrections: [0, 49],
}
);
t.deepEqual(
attemptCashAddressFormatErrorCorrection(
// cspell: disable-next-line
'btcbest:qq2azmyyv6dtgczexyalqar70q036yund53jvfde0x'
),
CashAddressCorrectionError.tooManyErrors
);
});
test('[fast-check] attemptCashAddressErrorCorrection', (t) => {
const correctsUpToTwoErrors = (hashLength: CashAddressAvailableSizesInBits) =>
fc.property(
fc.array(lowercaseLetter(), 1, 50).map((arr) => arr.join('')),
fc.nat(15),
fcUint8Array(hashLength / 8),
fc.array(fc.nat(hashLength / 8), 0, 2),
// eslint-disable-next-line max-params
(prefix, type, hash, randomErrors) => {
const address = encodeCashAddress(
prefix,
type as CashAddressAvailableTypes,
hash
);
const addressChars = splitEvery(address, 1);
const errors = [
...new Set(
randomErrors
.filter((i) => i !== prefix.length)
.sort((a, b) => a - b)
),
];
const broken = addressChars
.map((char, i) =>
errors.includes(i) ? (char === 'q' ? 'p' : 'q') : char
)
.join('');
t.deepEqual(attemptCashAddressFormatErrorCorrection(broken), {
address,
corrections: errors,
});
}
);
t.notThrows(() => {
fc.assert(correctsUpToTwoErrors(160));
fc.assert(correctsUpToTwoErrors(192));
fc.assert(correctsUpToTwoErrors(224));
fc.assert(correctsUpToTwoErrors(256));
fc.assert(correctsUpToTwoErrors(320));
fc.assert(correctsUpToTwoErrors(384));
fc.assert(correctsUpToTwoErrors(448));
fc.assert(correctsUpToTwoErrors(512));
});
});
const sha256Promise = instantiateSha256();
const legacyVectors: Macro<[string, string]> = async (
t,
base58Address,
cashAddress
) => {
const sha256 = await sha256Promise;
const decodedBase58Address = decodeBase58AddressFormat(sha256, base58Address);
const decodedCashAddress = decodeCashAddress(cashAddress);
if (
typeof decodedCashAddress === 'string' ||
typeof decodedBase58Address === 'string'
) {
t.fail();
return undefined;
}
t.deepEqual(decodedBase58Address.payload, decodedCashAddress.hash);
return undefined;
};
// eslint-disable-next-line functional/immutable-data
legacyVectors.title = (_, base58Address) =>
`CashAddress <-> Legacy Base58 Vectors: ${base58Address}`;
test(
legacyVectors,
// cspell: disable-next-line
'1BpEi6DfDAUFd7GtittLSdBeYJvcoaVggu',
'bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a'
);
test(
legacyVectors,
// cspell: disable-next-line
'1KXrWXciRDZUpQwQmuM1DbwsKDLYAYsVLR',
'bitcoincash:qr95sy3j9xwd2ap32xkykttr4cvcu7as4y0qverfuy'
);
test(
legacyVectors,
// cspell: disable-next-line
'16w1D5WRVKJuZUsSRzdLp9w3YGcgoxDXb',
'bitcoincash:qqq3728yw0y47sqn6l2na30mcw6zm78dzqre909m2r'
);
test(
legacyVectors,
// cspell: disable-next-line
'3CWFddi6m4ndiGyKqzYvsFYagqDLPVMTzC',
'bitcoincash:ppm2qsznhks23z7629mms6s4cwef74vcwvn0h829pq'
);
test(
legacyVectors,
// cspell: disable-next-line
'3LDsS579y7sruadqu11beEJoTjdFiFCdX4',
'bitcoincash:pr95sy3j9xwd2ap32xkykttr4cvcu7as4yc93ky28e'
);
test(
legacyVectors,
// cspell: disable-next-line
'31nwvkZwyPdgzjBJZXfDmSWsC4ZLKpYyUw',
'bitcoincash:pqq3728yw0y47sqn6l2na30mcw6zm78dzq5ucqzc37'
); | the_stack |
import * as conv_util from '../math/conv_util';
import * as util from '../util';
import * as concat3d_util from './concat3d_util';
import * as copy2D_util from './copy2d_util';
import {MatrixOrientation, NDArrayMath} from './math';
import {Array1D, Array2D, Array3D, Array4D, NDArray, Scalar} from './ndarray';
export class NDArrayMathCPU extends NDArrayMath {
constructor(safeMode = false) {
super(safeMode);
}
protected cloneInternal<T extends NDArray>(ndarray: T): T {
return NDArray.make<T>(
ndarray.shape, {values: new Float32Array(ndarray.getValues())});
}
protected reshapeInternal<T1 extends NDArray, T2 extends NDArray>(
ndarray: T1, newShape: number[]): T2 {
return this.cloneInternal(ndarray).reshape<T2>(newShape);
}
protected slice2DInternal(
input: Array2D, beginRowCol: [number, number],
sizeRowCol: [number, number]): Array2D {
const result = Array2D.zeros(sizeRowCol);
this.copy2DInternal(
input, beginRowCol, sizeRowCol, result, [0, 0], sizeRowCol);
return result;
}
protected copy2DInternal(
source: Array2D, sourceBeginRowCol: [number, number],
sourceSizeRowCol: [number, number], dest: Array2D,
destBeginRowCol: [number, number],
destSizeRowCol: [number, number]): void {
copy2D_util.validateShapes(sourceSizeRowCol, destSizeRowCol);
const srcValues = source.getValues();
const dstValues = dest.getValues();
const n = sourceSizeRowCol[0] * sourceSizeRowCol[1];
for (let i = 0; i < n; ++i) {
const srcRow = sourceBeginRowCol[0] + Math.floor(i / sourceSizeRowCol[1]);
const srcCol = sourceBeginRowCol[1] + (i % sourceSizeRowCol[1]);
const srcOff = srcRow * source.shape[1] + srcCol;
const dstRow = destBeginRowCol[0] + Math.floor(i / destSizeRowCol[1]);
const dstCol = destBeginRowCol[1] + (i % destSizeRowCol[1]);
const dstOff = dstRow * dest.shape[1] + dstCol;
dstValues[dstOff] = srcValues[srcOff];
}
}
protected concat3DInternal(x1: Array3D, x2: Array3D, axis: number): Array3D {
const outputShape =
concat3d_util.computeConcat3DOutputShape(x1.shape, x2.shape, axis);
const values = Array3D.zeros(outputShape);
for (let i = 0; i < outputShape[0]; i++) {
for (let j = 0; j < outputShape[1]; j++) {
for (let k = 0; k < outputShape[2]; k++) {
// Shader begins.
const index: [number, number, number] = [i, j, k];
let value: number;
if (index[axis] < x1.shape[axis]) {
value = x1.get(i, j, k);
} else {
index[axis] -= x1.shape[axis];
const [i2, j2, k2] = index;
value = x2.get(i2, j2, k2);
}
values.set(value, i, j, k);
}
}
}
return values;
}
protected scaledArrayAddInternal<T extends NDArray>(
c1: Scalar, a: T, c2: Scalar, b: T) {
const newShape = util.assertAndGetBroadcastedShape(a.shape, b.shape);
const newValues = new Float32Array(util.sizeFromShape(newShape));
const aValues = a.getValues();
const bValues = b.getValues();
const c1Val = c1.get();
const c2Val = c2.get();
for (let i = 0; i < newValues.length; ++i) {
newValues[i] = c1Val * aValues[i % a.size] + c2Val * bValues[i % b.size];
}
return NDArray.make<T>(newShape, {values: newValues});
}
protected negInternal<T extends NDArray>(a: T): T {
return this.scalarTimesArray(Scalar.NEG_ONE, a);
}
protected addInternal<T extends NDArray>(a: T, b: T): T {
return this.scaledArrayAddInternal<T>(Scalar.ONE, a, Scalar.ONE, b);
}
protected subInternal<T extends NDArray>(a: T, b: T): T {
return this.scaledArrayAddInternal<T>(Scalar.ONE, a, Scalar.NEG_ONE, b);
}
protected matMulInternal(
a: Array2D, b: Array2D, aOrientation = MatrixOrientation.REGULAR,
bOrientation = MatrixOrientation.REGULAR): Array2D {
const sharedDim =
(aOrientation === MatrixOrientation.REGULAR) ? a.shape[1] : a.shape[0];
const leftDim =
(aOrientation === MatrixOrientation.REGULAR) ? a.shape[0] : a.shape[1];
const rightDim =
(bOrientation === MatrixOrientation.REGULAR) ? b.shape[1] : b.shape[0];
const normalGetter = (matrix: Array2D, i: number, j: number) =>
matrix.get(i, j);
const transposedGetter = (matrix: Array2D, i: number, j: number) =>
matrix.get(j, i);
const aGetter = (aOrientation === MatrixOrientation.REGULAR) ?
normalGetter :
transposedGetter;
const bGetter = (bOrientation === MatrixOrientation.REGULAR) ?
normalGetter :
transposedGetter;
const values = new Float32Array(leftDim * rightDim);
let index = 0;
for (let i = 0; i < leftDim; ++i) {
for (let j = 0; j < rightDim; ++j) {
let sum = 0;
for (let k = 0; k < sharedDim; ++k) {
// TODO: optimize CPU matmul.
sum += aGetter(a, i, k) * bGetter(b, k, j);
}
values[index++] = sum;
}
}
return Array2D.new([leftDim, rightDim], values);
}
protected multiplyInternal<T extends NDArray>(a: T, b: T): T {
const newShape = util.assertAndGetBroadcastedShape(a.shape, b.shape);
const newValues = new Float32Array(util.sizeFromShape(newShape));
const aValues = a.getValues();
const bValues = b.getValues();
for (let i = 0; i < newValues.length; ++i) {
newValues[i] = aValues[i % a.size] * bValues[i % b.size];
}
return NDArray.make<T>(newShape, {values: newValues});
}
protected divideInternal<T extends NDArray>(a: T, b: T): T {
const newShape = util.assertAndGetBroadcastedShape(a.shape, b.shape);
const newValues = new Float32Array(util.sizeFromShape(newShape));
const aValues = a.getValues();
const bValues = b.getValues();
for (let i = 0; i < newValues.length; ++i) {
newValues[i] = aValues[i % a.size] / bValues[i % b.size];
}
return NDArray.make<T>(newShape, {values: newValues});
}
protected sumInternal(ndarray: NDArray): Scalar {
let sum = 0;
const values = ndarray.getValues();
for (let i = 0; i < values.length; ++i) {
sum += values[i];
}
return Scalar.new(sum);
}
protected argMinInternal(ndarray: NDArray): Scalar {
let min = Number.MAX_VALUE;
let minIndex = -1;
const values = ndarray.getValues();
for (let i = 0; i < values.length; ++i) {
const value = values[i];
if (isNaN(value)) {
return Scalar.new(NaN);
}
if (value < min) {
min = value;
minIndex = i;
}
}
return Scalar.new(minIndex);
}
protected argMaxInternal(ndarray: NDArray): Scalar {
let max = Number.NEGATIVE_INFINITY;
let maxIndex = -1;
const values = ndarray.getValues();
for (let i = 0; i < values.length; ++i) {
const value = values[i];
if (isNaN(value)) {
return Scalar.new(NaN);
}
if (value > max) {
max = value;
maxIndex = i;
}
}
return Scalar.new(maxIndex);
}
protected argMaxEqualsInternal(x1: NDArray, x2: NDArray): Scalar {
const argMax1 = this.argMaxInternal(x1).get();
const argMax2 = this.argMaxInternal(x2).get();
if (isNaN(argMax1) || isNaN(argMax2)) {
return Scalar.new(NaN);
}
return Scalar.new(+(argMax1 === argMax2));
}
protected topKInternal(ndarray: NDArray, k: number):
{values: Array1D, indices: Array1D} {
const values = ndarray.getValues();
const valuesAndIndices: Array<{value: number, index: number}> = [];
for (let i = 0; i < values.length; i++) {
valuesAndIndices.push({value: values[i], index: i});
}
valuesAndIndices.sort((a, b) => {
return b.value - a.value;
});
const topkValues = new Float32Array(k);
const topkIndices = new Float32Array(k);
for (let i = 0; i < k; i++) {
topkValues[i] = valuesAndIndices[i].value;
topkIndices[i] = valuesAndIndices[i].index;
}
return {values: Array1D.new(topkValues), indices: Array1D.new(topkIndices)};
}
protected minInternal(ndarray: NDArray): Scalar {
const values = ndarray.getValues();
let min = values[0];
for (let i = 1; i < values.length; ++i) {
const value = values[i];
if (isNaN(value)) {
return Scalar.new(NaN);
}
if (value < min) {
min = value;
}
}
return Scalar.new(min);
}
protected maxInternal(ndarray: NDArray): Scalar {
const values = ndarray.getValues();
let max = values[0];
for (let i = 1; i < values.length; ++i) {
const value = values[i];
if (isNaN(value)) {
return Scalar.new(NaN);
}
if (value > max) {
max = value;
}
}
return Scalar.new(max);
}
protected expInternal<T extends NDArray>(ndarray: T): T {
const values = ndarray.getValues();
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
newValues[i] = Math.exp(values[i]);
}
return NDArray.make<T>(ndarray.shape, {values: newValues});
}
protected logInternal<T extends NDArray>(ndarray: T): T {
const values = ndarray.getValues();
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
const value = values[i];
newValues[i] = Math.log(value);
}
return NDArray.make<T>(ndarray.shape, {values: newValues});
}
protected logSumExpInternal(ndarray: NDArray): Scalar {
const xMax = this.max(ndarray);
const a = this.arrayMinusScalar(ndarray, xMax);
const b = this.exp(a);
const c = this.sum(b);
const d = this.log(c);
const result = this.add(xMax, d);
xMax.dispose();
a.dispose();
b.dispose();
c.dispose();
d.dispose();
return result;
}
protected reluInternal<T extends NDArray>(ndarray: T): T {
const resultValues = new Float32Array(ndarray.size);
const values = ndarray.getValues();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.max(0, values[i]);
}
return NDArray.make<T>(ndarray.shape, {values: resultValues});
}
protected sigmoidInternal<T extends NDArray>(ndarray: T): T {
const resultValues = new Float32Array(ndarray.size);
const values = ndarray.getValues();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = 1 / (1 + Math.exp(-values[i]));
}
return NDArray.make<T>(ndarray.shape, {values: resultValues});
}
protected tanhInternal<T extends NDArray>(ndarray: T): T {
const resultValues = new Float32Array(ndarray.size);
const values = ndarray.getValues();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = util.tanh(values[i]);
}
return NDArray.make<T>(ndarray.shape, {values: resultValues});
}
protected sinInternal<T extends NDArray>(ndarray: T): T {
const resultValues = new Float32Array(ndarray.size);
const values = ndarray.getValues();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.sin(values[i]);
}
return NDArray.make<T>(ndarray.shape, {values: resultValues});
}
protected stepInternal<T extends NDArray>(ndarray: T): T {
const resultValues = new Float32Array(ndarray.size);
const values = ndarray.getValues();
for (let i = 0; i < values.length; ++i) {
const value = values[i];
resultValues[i] = value > 0 ? 1 : (value < 0 ? 0 : value);
}
return NDArray.make<T>(ndarray.shape, {values: resultValues});
}
/**
* image is of shape [r, c, d1].
* weights is of shape [F, F, d1, d2].
*/
protected conv2dInternal(
x: Array3D, weights: Array4D, biases: Array1D|null, stride: number,
pad: number): Array3D {
const [xRows, xCols, inputDepth] = x.shape;
const fieldSize = weights.shape[0];
const outputDepth = weights.shape[3];
const outputShape = conv_util.computeOutputShape3D(
[xRows, xCols, inputDepth], fieldSize, outputDepth, stride, pad);
const y = Array3D.zeros(outputShape);
for (let d2 = 0; d2 < outputDepth; ++d2) {
for (let yR = 0; yR < y.shape[0]; ++yR) {
const xRCorner = yR * stride - pad;
const xRMin = Math.max(0, xRCorner);
const xRMax = Math.min(xRows, fieldSize + xRCorner);
for (let yC = 0; yC < y.shape[1]; ++yC) {
const xCCorner = yC * stride - pad;
const xCMin = Math.max(0, xCCorner);
const xCMax = Math.min(xCols, fieldSize + xCCorner);
let dotProd = 0;
for (let xR = xRMin; xR < xRMax; ++xR) {
const wR = xR - xRCorner;
for (let xC = xCMin; xC < xCMax; ++xC) {
const wC = xC - xCCorner;
for (let d1 = 0; d1 < inputDepth; ++d1) {
const pixel = x.get(xR, xC, d1);
const weight = weights.get(wR, wC, d1, d2);
dotProd += pixel * weight;
}
}
}
const bias = (biases != null) ? biases.get(d2) : 0;
y.set(dotProd + bias, yR, yC, d2);
}
}
}
return y;
}
protected conv2dBackPropInternal(
x: Array3D, dy: Array3D, weights: Array4D, stride: number,
pad: number): {dx: Array3D, dw: Array4D, db: Array1D} {
const fSize = weights.shape[0];
const dw = this.conv2dDerWeights(x, dy, fSize, stride, pad);
const db = this.conv2dDerBias(dy);
const dx = this.conv2dTransposeInternal(dy, weights, null, stride, pad);
return {dx, db, dw};
}
/**
* image is of shape [r, c, d1].
* weights is of shape [F, F, d1, d2].
*/
protected conv2dTransposeInternal(
x: Array3D, weights: Array4D, biases: Array1D|null, origStride: number,
origPad: number): Array3D {
const fSize = weights.shape[0];
const pad = fSize - 1 - origPad;
const origInputDepth = weights.shape[2];
const origOutputDepth = weights.shape[3];
const xRows = x.shape[0];
const xCols = x.shape[1];
// Dilate the input.
const xRowsDilated = (xRows - 1) * origStride + 1;
const xColsDilated = (xCols - 1) * origStride + 1;
const outputShape = conv_util.computeOutputShape3D(
[xRowsDilated, xColsDilated, origOutputDepth], fSize, origInputDepth, 1,
pad);
const y = Array3D.zeros(outputShape);
for (let d2 = 0; d2 < origInputDepth; ++d2) {
for (let yR = 0; yR < y.shape[0]; ++yR) {
const xRCorner = yR - pad;
const xRMin = Math.max(0, Math.ceil(xRCorner / origStride));
const xRMax = Math.min(xRows, (fSize + xRCorner) / origStride);
for (let yC = 0; yC < y.shape[1]; ++yC) {
const xCCorner = yC - pad;
const xCMin = Math.max(0, Math.ceil(xCCorner / origStride));
const xCMax = Math.min(xCols, (fSize + xCCorner) / origStride);
let dotProd = 0;
for (let xR = xRMin; xR < xRMax; ++xR) {
const wR = xR * origStride - xRCorner;
for (let xC = xCMin; xC < xCMax; ++xC) {
const wC = xC * origStride - xCCorner;
for (let d1 = 0; d1 < origOutputDepth; ++d1) {
const pixel = x.get(xR, xC, d1);
const weight =
weights.get(fSize - 1 - wR, fSize - 1 - wC, d2, d1);
dotProd += pixel * weight;
}
}
}
const bias = biases != null ? biases.get(d2) : 0;
y.set(dotProd + bias, yR, yC, d2);
}
}
}
return y;
}
/**
* image is of shape [r, c, d1].
* weights is of shape [F, F, d1, d2].
*/
protected conv2dTransposeShaderLike(
x: Array3D, origWeights: Array4D, origStride: number,
origPad: number): Array3D {
const fSize = origWeights.shape[0];
const pad = fSize - 1 - origPad;
const origInputDepth = origWeights.shape[2];
const origOutputDepth = origWeights.shape[3];
const xRows = x.shape[0];
const xCols = x.shape[1];
// Dilate the input.
const xRowsDilated = (xRows - 1) * origStride + 1;
const xColsDilated = (xCols - 1) * origStride + 1;
const outputShape = conv_util.computeOutputShape3D(
[xRowsDilated, xColsDilated, origOutputDepth], fSize, origInputDepth, 1,
pad);
const y = Array3D.zeros(outputShape);
for (let d2 = 0; d2 < origInputDepth; ++d2) {
for (let yR = 0; yR < y.shape[0]; ++yR) {
for (let yC = 0; yC < y.shape[1]; ++yC) {
// Shader code begins.
const xRCorner = yR - pad;
const xCCorner = yC - pad;
let dotProd = 0;
for (let wR = 0; wR < fSize; ++wR) {
const xR = (xRCorner + wR) / origStride;
if (xR < 0 || xR >= xRows || Math.floor(xR) !== xR) {
continue;
}
for (let wC = 0; wC < fSize; ++wC) {
const xC = (xCCorner + wC) / origStride;
if (xC < 0 || xC >= xCols || Math.floor(xC) !== xC) {
continue;
}
for (let d1 = 0; d1 < origOutputDepth; ++d1) {
const pixel = x.get(xR, xC, d1);
const weight =
origWeights.get(fSize - 1 - wR, fSize - 1 - wC, d2, d1);
dotProd += pixel * weight;
}
}
}
y.set(dotProd, yR, yC, d2);
}
}
}
return y;
}
conv2dDerWeights(
x: Array3D, dY: Array3D, fSize: number, stride: number,
zeroPad: number): Array4D {
const inputDepth = x.shape[2];
const outputDepth = dY.shape[2];
const weightsShape =
conv_util.computeWeightsShape4D(inputDepth, outputDepth, fSize);
const dW = Array4D.zeros(weightsShape);
const yNumRows = dY.shape[0];
const yNumCols = dY.shape[1];
const xNumRows = x.shape[0];
const xNumCols = x.shape[1];
for (let wR = 0; wR < fSize; ++wR) {
const yRMin = Math.max(0, Math.ceil((zeroPad - wR) / stride));
const yRMax = Math.min(yNumRows, (xNumRows + zeroPad - wR) / stride);
for (let wC = 0; wC < fSize; ++wC) {
const yCMin = Math.max(0, Math.ceil((zeroPad - wC) / stride));
const yCMax = Math.min(yNumCols, (xNumCols + zeroPad - wC) / stride);
for (let d1 = 0; d1 < inputDepth; ++d1) {
for (let d2 = 0; d2 < outputDepth; ++d2) {
// Need to convolve.
let dotProd = 0;
for (let yR = yRMin; yR < yRMax; ++yR) {
const xR = wR + yR * stride - zeroPad;
for (let yC = yCMin; yC < yCMax; ++yC) {
const xC = wC + yC * stride - zeroPad;
dotProd += x.get(xR, xC, d1) * dY.get(yR, yC, d2);
}
}
dW.set(dotProd, wR, wC, d1, d2);
}
}
}
}
return dW;
}
conv2dDerBias(dY: Array3D): Array1D {
const outputDepth = dY.shape[2];
const numRows = dY.shape[0];
const numCols = dY.shape[1];
const values = new Float32Array(outputDepth);
for (let d2 = 0; d2 < outputDepth; ++d2) {
let sum = 0;
for (let r = 0; r < numRows; ++r) {
for (let c = 0; c < numCols; ++c) {
sum += dY.get(r, c, d2);
}
}
values[d2] = sum;
}
return Array1D.new(values);
}
protected switchDimInternal<T extends NDArray>(t: T, newDim: number[]): T {
const newShape: number[] = new Array(t.rank);
for (let i = 0; i < newShape.length; i++) {
newShape[i] = t.shape[newDim[i]];
}
const resultValues = new Float32Array(t.size);
const values = t.getValues();
const result = NDArray.make<T>(newShape, {values: resultValues});
for (let i = 0; i < t.size; ++i) {
const loc = t.indexToLoc(i);
// Permute location.
const newLoc: number[] = new Array(loc.length);
for (let i = 0; i < newLoc.length; i++) {
newLoc[i] = loc[newDim[i]];
}
const newIndex = result.locToIndex(newLoc);
resultValues[newIndex] = values[i];
}
return result;
}
private pool(
x: Array3D, fSize: number, stride: number, pad: number,
poolType: 'max'|'min'|'avg') {
const [xRows, xCols, depth] = x.shape;
const outputShape = conv_util.computeOutputShape3D(
[xRows, xCols, depth], fSize, depth, stride, pad);
const y = Array3D.zeros(outputShape);
for (let d = 0; d < depth; ++d) {
for (let yR = 0; yR < y.shape[0]; ++yR) {
const xRCorner = yR * stride - pad;
const xRMin = Math.max(0, xRCorner);
const xRMax = Math.min(xRows, fSize + xRCorner);
for (let yC = 0; yC < y.shape[1]; ++yC) {
const xCCorner = yC * stride - pad;
const xCMin = Math.max(0, xCCorner);
const xCMax = Math.min(xCols, fSize + xCCorner);
let minMaxValue =
(poolType === 'max' ? Number.NEGATIVE_INFINITY :
Number.POSITIVE_INFINITY);
let avgValue = 0;
for (let xR = xRMin; xR < xRMax; ++xR) {
for (let xC = xCMin; xC < xCMax; ++xC) {
const pixel = x.get(xR, xC, d);
if (isNaN(pixel)) {
minMaxValue = NaN;
avgValue = NaN;
break;
}
if ((poolType === 'max' && pixel > minMaxValue) ||
(poolType === 'min' && pixel < minMaxValue)) {
minMaxValue = pixel;
} else if (poolType === 'avg') {
avgValue += pixel / (fSize * fSize);
}
}
if (isNaN(minMaxValue)) {
break;
}
}
y.set(poolType === 'avg' ? avgValue : minMaxValue, yR, yC, d);
}
}
}
return y;
}
protected maxPoolInternal(
x: Array3D, fSize: number, stride: number, pad: number): Array3D {
return this.pool(x, fSize, stride, pad, 'max');
}
maxPoolPositions(x: Array3D, fSize: number, stride: number, pad: number) {
const [xRows, xCols, depth] = x.shape;
const outputShape =
conv_util.computeOutputShape3D(x.shape, fSize, depth, stride, pad);
const maxPositions = Array3D.zeros(outputShape);
for (let d = 0; d < depth; ++d) {
for (let yR = 0; yR < outputShape[0]; ++yR) {
const xRCorner = yR * stride - pad;
const xRMin = Math.max(0, xRCorner);
const xRMax = Math.min(xRows, fSize + xRCorner);
for (let yC = 0; yC < outputShape[1]; ++yC) {
const xCCorner = yC * stride - pad;
const xCMin = Math.max(0, xCCorner);
const xCMax = Math.min(xCols, fSize + xCCorner);
let maxValue = Number.NEGATIVE_INFINITY;
let maxPosition = -1;
for (let xR = xRMin; xR < xRMax; ++xR) {
const wR = xR - xRCorner;
for (let xC = xCMin; xC < xCMax; ++xC) {
const wC = xC - xCCorner;
const pixel = x.get(xR, xC, d);
if (pixel > maxValue) {
maxValue = pixel;
maxPosition = wR * fSize + wC;
}
}
}
maxPositions.set(maxPosition, yR, yC, d);
}
}
}
return maxPositions;
}
protected maxPoolBackpropInternal(
dy: Array3D, x: Array3D, fSize: number, origStride: number,
origPad: number): Array3D {
const maxPositions = this.maxPoolPositions(x, fSize, origStride, origPad);
const pad = fSize - 1 - origPad;
const [dyRows, dyCols, depth] = dy.shape;
// Dilate the input.
const dyRowsDilated = (dyRows - 1) * origStride + 1;
const dxColsDilated = (dyCols - 1) * origStride + 1;
const outputShape = conv_util.computeOutputShape3D(
[dyRowsDilated, dxColsDilated, depth], fSize, depth, 1, pad);
const dx = Array3D.zeros(outputShape);
for (let d = 0; d < depth; ++d) {
for (let dxR = 0; dxR < dx.shape[0]; ++dxR) {
for (let dxC = 0; dxC < dx.shape[1]; ++dxC) {
// Shader code begins.
const dyRCorner = dxR - pad;
const dyCCorner = dxC - pad;
let dotProd = 0;
for (let wR = 0; wR < fSize; ++wR) {
const dyR = (dyRCorner + wR) / origStride;
if (dyR < 0 || dyR >= dyRows || Math.floor(dyR) !== dyR) {
continue;
}
for (let wC = 0; wC < fSize; ++wC) {
const dyC = (dyCCorner + wC) / origStride;
if (dyC < 0 || dyC >= dyCols || Math.floor(dyC) !== dyC) {
continue;
}
const maxPos = fSize * fSize - 1 - maxPositions.get(dyR, dyC, d);
const curPos = wR * fSize + wC;
const mask = maxPos === curPos ? 1 : 0;
if (mask === 0) {
continue;
}
const pixel = dy.get(dyR, dyC, d);
dotProd += pixel * mask;
}
}
dx.set(dotProd, dxR, dxC, d);
}
}
}
return dx;
}
protected minPoolInternal(
x: Array3D, fSize: number, stride: number, pad: number): Array3D {
return this.pool(x, fSize, stride, pad, 'min');
}
protected avgPoolInternal(
x: Array3D, fSize: number, stride: number, pad: number): Array3D {
return this.pool(x, fSize, stride, pad, 'avg');
}
protected resizeBilinear3DInternal(
x: Array3D, newShape2D: [number, number],
alignCorners: boolean): Array3D {
const output = Array3D.zeros([newShape2D[0], newShape2D[1], x.shape[2]]);
const effectiveInputSize =
alignCorners ? [x.shape[0] - 1, x.shape[1] - 1, x.shape[2]] : x.shape;
const effectiveOutputSize = alignCorners ?
[output.shape[0] - 1, output.shape[1] - 1, output.shape[2]] :
output.shape;
for (let r = 0; r < output.shape[0]; r++) {
for (let c = 0; c < output.shape[1]; c++) {
for (let d = 0; d < output.shape[2]; d++) {
// Begin shader.
// Compute the fractional index of the source.
const sourceFracRow =
(effectiveInputSize[0]) * r / (effectiveOutputSize[0]);
const sourceFracCol =
(effectiveInputSize[1]) * c / (effectiveOutputSize[1]);
const sourceRowFloor = Math.floor(sourceFracRow);
const sourceRowCeil =
Math.min(x.shape[0] - 1, Math.ceil(sourceFracRow));
const sourceColFloor = Math.floor(sourceFracCol);
const sourceColCeil =
Math.min(x.shape[1] - 1, Math.ceil(sourceFracCol));
const topLeft = x.get(sourceRowFloor, sourceColFloor, d);
const bottomLeft = x.get(sourceRowCeil, sourceColFloor, d);
const topRight = x.get(sourceRowFloor, sourceColCeil, d);
const bottomRight = x.get(sourceRowCeil, sourceColCeil, d);
const rowFrac = sourceFracRow - sourceRowFloor;
const colFrac = sourceFracCol - sourceColFloor;
const top = topLeft + (topRight - topLeft) * colFrac;
const bottom = bottomLeft + (bottomRight - bottomLeft) * colFrac;
const newValue = top + (bottom - top) * rowFrac;
output.set(newValue, r, c, d);
}
}
}
return output;
}
protected batchNormalization3DInternal(
x: Array3D, mean: Array3D|Array1D, variance: Array3D|Array1D,
varianceEpsilon = .001, scale?: Array3D|Array1D,
offset?: Array3D|Array1D): Array3D {
const xValues = x.getValues();
const meanValues = mean.getValues();
const varianceValues = variance.getValues();
const scaleValues = scale ? scale.getValues() : new Float32Array([1]);
const offsetValues = offset ? offset.getValues() : new Float32Array([0]);
const outValues = new Float32Array(xValues.length);
for (let i = 0; i < xValues.length; i++) {
outValues[i] = offsetValues[i % offsetValues.length] +
(xValues[i] - meanValues[i % meanValues.length]) *
scaleValues[i % scaleValues.length] /
Math.sqrt(
varianceValues[i % varianceValues.length] + varianceEpsilon);
}
return NDArray.make<Array3D>(x.shape, {values: outValues});
}
} | the_stack |
import { TransformOptions, FrameOptions } from '../Sprite/Spritesheet'
export const Ease = {
linear(t: number, b: number, c: number, d: number): number {
return c*(t/=d) + b;
},
easeInQuad (t: number, b: number, c: number, d: number): number {
return c*(t/=d)*t + b;
},
easeOutQuad (t: number, b: number, c: number, d: number): number {
return -c *(t/=d)*(t-2) + b;
},
easeInOutQuad (t: number, b: number, c: number, d: number): number {
if ((t/=d/2) < 1) return c/2*t*t + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
},
easeInCubic (t: number, b: number, c: number, d: number): number {
return c*(t/=d)*t*t + b;
},
easeOutCubic (t: number, b: number, c: number, d: number): number {
return c*((t=t/d-1)*t*t + 1) + b;
},
easeInOutCubic (t: number, b: number, c: number, d: number): number {
if ((t/=d/2) < 1) return c/2*t*t*t + b;
return c/2*((t-=2)*t*t + 2) + b;
},
easeInQuart (t: number, b: number, c: number, d: number): number {
return c*(t/=d)*t*t*t + b;
},
easeOutQuart (t: number, b: number, c: number, d: number): number {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
},
easeInOutQuart (t: number, b: number, c: number, d: number): number {
if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
return -c/2 * ((t-=2)*t*t*t - 2) + b;
},
easeInQuint (t: number, b: number, c: number, d: number): number {
return c*(t/=d)*t*t*t*t + b;
},
easeOutQuint (t: number, b: number, c: number, d: number): number {
return c*((t=t/d-1)*t*t*t*t + 1) + b;
},
easeInOutQuint (t: number, b: number, c: number, d: number): number {
if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
return c/2*((t-=2)*t*t*t*t + 2) + b;
},
easeInSine (t: number, b: number, c: number, d: number): number {
return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
},
easeOutSine (t: number, b: number, c: number, d: number): number {
return c * Math.sin(t/d * (Math.PI/2)) + b;
},
easeInOutSine (t: number, b: number, c: number, d: number): number {
return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
},
easeInExpo (t: number, b: number, c: number, d: number): number {
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
},
easeOutExpo (t: number, b: number, c: number, d: number): number {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
},
easeInOutExpo (t: number, b: number, c: number, d: number): number {
if (t==0) return b;
if (t==d) return b+c;
if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
},
easeInCirc (t: number, b: number, c: number, d: number): number {
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
},
easeOutCirc (t: number, b: number, c: number, d: number): number {
return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
},
easeInOutCirc (t: number, b: number, c: number, d: number): number {
if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
},
easeInElastic (t: number, b: number, c: number, d: number): number {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
},
easeOutElastic (t: number, b: number, c: number, d: number): number {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
},
easeInOutElastic (t: number, b: number, c: number, d: number): number {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5);
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
},
easeInBack (t: number, b: number, c: number, d: number, s: number): number {
if (s == undefined) s = 1.70158;
return c*(t/=d)*t*((s+1)*t - s) + b;
},
easeOutBack (t: number, b: number, c: number, d: number, s: number): number {
if (s == undefined) s = 1.70158;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
easeInOutBack (t: number, b: number, c: number, d: number, s: number): number {
if (s == undefined) s = 1.70158;
if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
},
easeInBounce (t: number, b: number, c: number, d: number): number {
return c - Ease.easeOutBounce (d-t, 0, c, d) + b;
},
easeOutBounce (t: number, b: number, c: number, d: number): number {
if ((t/=d) < (1/2.75)) {
return c*(7.5625*t*t) + b;
} else if (t < (2/2.75)) {
return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
} else if (t < (2.5/2.75)) {
return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
} else {
return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
}
},
easeInOutBounce (t: number, b: number, c: number, d: number): number {
if (t < d/2) return Ease.easeInBounce (t*2, 0, c, d) * .5 + b;
return Ease.easeOutBounce (t*2-d, 0, c, d) * .5 + c*.5 + b;
}
}
type EaseType = (t: number, b: number, c: number, d: number) => number
export class Timeline {
time: number = 0
animation: FrameOptions[][] = []
/**
* Allows you to create complex animations more easily. For example, to display a movement with an Easing function
*
* ```ts
* import { Timeline, Ease } from '@rpgjs/client'
*
* new Timeline()
* .add(30, ({ scale }) => [{
* frameX: 0,
* frameY: 1,
* scale: [scale]
* }], {
* scale: {
* from: 0,
* to: 1,
* easing: Ease.easeOutBounce
* }
* })
* .add(100)
* .create()
* ```
*
* Here we say
*
* - For a duration of 30 seconds
* - A function that will be called every 1 frame with the `scale` property defined in transform
* - An object of transformation. Define the properties of your choice to be passed to the callback function
* - `to`: the starting value
* - `from`: the end value
* - `easing`: An easing function (By default, it is a linear function)
*
* Note that if you just put a duration (`add(100)`), it will only put a pause on the animation
*
* Easing functions available but you can create your own
*
* ```ts
* function myEase(t: number, b: number, c: number, d: number): number { }
* ```
*
* `t`: current time
* `b`: start value
* `c`: end value
* `d`: duration
*
* @title Add Animation in timeline
* @enum {Function}
*
* Ease.linear | linear
* Ease.easeInQuad | easeInQuad
* Ease.easeOutQuad | easeOutQuad
* Ease.easeInOutQuad | easeInOutQuad
* Ease.easeInCubic | easeInCubic
* Ease.easeOutCubic | easeOutCubic
* Ease.easeInOutCubic | easeInOutCubic
* Ease.easeInQuart | easeInQuart
* Ease.easeOutQuart | easeOutQuart
* Ease.easeInOutQuart | easeInOutQuart
* Ease.easeInQuint | easeInQuint
* Ease.easeOutQuint | easeOutQuint
* Ease.easeInOutQuint | easeInOutQuint
* Ease.easeInSine | easeInSine
* Ease.easeOutSine | easeOutSine
* Ease.easeInOutSine | easeInOutSine
* Ease.easeInExpo | easeInExpo
* Ease.easeOutExpo | easeOutExpo
* Ease.easeInOutExpo | easeInOutExpo
* Ease.easeInCirc | easeInCirc
* Ease.easeOutCirc | easeOutCirc
* Ease.easeInOutCirc | easeInOutCirc
* Ease.easeInElastic | easeInElastic
* Ease.easeOutElastic | easeOutElastic
* Ease.easeInOutElastic | easeInOutElastic
* Ease.easeInBack | easeInBack
* Ease.easeOutBack | easeOutBack
* Ease.easeInOutBack | easeInOutBack
* Ease.easeInBounce | easeInBounce
* Ease.easeOutBounce | easeOutBounce
* @method timeline.add(duration,cb?,transform?)
* @param {number} duration
* @param { (obj?: number, time?: number) => TransformOptions[] } [cb]
* @param { [property: string]: { to:number, from: number: easing?: Function } } [transform]
* @returns {Timeline}
* @memberof Timeline
*/
add(duration: number, cb?: (obj?: any, time?: number) => TransformOptions[], transform?: {
[property: string]: {
to: number,
from: number,
easing?: EaseType
}
}): Timeline {
if (!cb) {
this.animation.push([{
time: duration + this.time,
}])
this.time += duration
return this
}
for (let i=0 ; i < duration ; i++) {
let anim
const obj = {}
for (let prop in transform) {
const param = transform[prop]
const cbEasing = param.easing || Ease.linear
if (param.to < param.from) {
obj[prop] = 1 - cbEasing(i, param.to, param.from, duration)
}
else {
obj[prop] = cbEasing(i, param.from, param.to, duration)
}
}
const ret = cb(obj, i)
anim = ret.map(el => {
(el as any).time = i + this.time
return el
})
this.animation.push(anim)
}
this.time += duration
return this
}
/**
* Allows you to create the animation array to assign to the `animations` property in the Spritesheet
*
* ```ts
* import { Spritesheet, Timeline } from '@rpgjs/server'
*
* @Spritesheet({
* id: 'sprite',
* image: require('./sprite.png'),
* width: 192,
* height: 228,
* framesHeight: 6,
* framesWidth: 6,
* anchor: [0.5],
* textures: {
* myanim: {
* animations: new Timeline()
* .add(SEE THE ADD METHOD)
* .create()
* }
* }
* })
* export class MyAnim {}
* ```
*
* @title Create the animation array
* @method timeline.create()
* @returns {FrameOptions[][]} The animation array
* @memberof Timeline
*/
create(): FrameOptions[][] {
return this.animation
}
} | the_stack |
export interface paths {
'/': {
get: {
responses: {
/** OK */
200: unknown
}
}
}
'/aggregate': {
get: {
parameters: {
query: {
aggregate_cid?: parameters['rowFilter.aggregate.aggregate_cid']
piece_cid?: parameters['rowFilter.aggregate.piece_cid']
sha256hex?: parameters['rowFilter.aggregate.sha256hex']
export_size?: parameters['rowFilter.aggregate.export_size']
metadata?: parameters['rowFilter.aggregate.metadata']
entry_created?: parameters['rowFilter.aggregate.entry_created']
/** Filtering Columns */
select?: parameters['select']
/** Ordering */
order?: parameters['order']
/** Limiting and Pagination */
offset?: parameters['offset']
/** Limiting and Pagination */
limit?: parameters['limit']
}
header: {
/** Limiting and Pagination */
Range?: parameters['range']
/** Limiting and Pagination */
'Range-Unit'?: parameters['rangeUnit']
/** Preference */
Prefer?: parameters['preferCount']
}
}
responses: {
/** OK */
200: {
schema: definitions['aggregate'][]
}
/** Partial Content */
206: unknown
}
}
}
'/aggregate_entry': {
get: {
parameters: {
query: {
aggregate_cid?: parameters['rowFilter.aggregate_entry.aggregate_cid']
cid_v1?: parameters['rowFilter.aggregate_entry.cid_v1']
datamodel_selector?: parameters['rowFilter.aggregate_entry.datamodel_selector']
/** Filtering Columns */
select?: parameters['select']
/** Ordering */
order?: parameters['order']
/** Limiting and Pagination */
offset?: parameters['offset']
/** Limiting and Pagination */
limit?: parameters['limit']
}
header: {
/** Limiting and Pagination */
Range?: parameters['range']
/** Limiting and Pagination */
'Range-Unit'?: parameters['rangeUnit']
/** Preference */
Prefer?: parameters['preferCount']
}
}
responses: {
/** OK */
200: {
schema: definitions['aggregate_entry'][]
}
/** Partial Content */
206: unknown
}
}
}
'/auth_key': {
get: {
parameters: {
query: {
id?: parameters['rowFilter.auth_key.id']
name?: parameters['rowFilter.auth_key.name']
secret?: parameters['rowFilter.auth_key.secret']
user_id?: parameters['rowFilter.auth_key.user_id']
inserted_at?: parameters['rowFilter.auth_key.inserted_at']
updated_at?: parameters['rowFilter.auth_key.updated_at']
deleted_at?: parameters['rowFilter.auth_key.deleted_at']
/** Filtering Columns */
select?: parameters['select']
/** Ordering */
order?: parameters['order']
/** Limiting and Pagination */
offset?: parameters['offset']
/** Limiting and Pagination */
limit?: parameters['limit']
}
header: {
/** Limiting and Pagination */
Range?: parameters['range']
/** Limiting and Pagination */
'Range-Unit'?: parameters['rangeUnit']
/** Preference */
Prefer?: parameters['preferCount']
}
}
responses: {
/** OK */
200: {
schema: definitions['auth_key'][]
}
/** Partial Content */
206: unknown
}
}
post: {
parameters: {
body: {
/** auth_key */
auth_key?: definitions['auth_key']
}
query: {
/** Filtering Columns */
select?: parameters['select']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** Created */
201: unknown
}
}
delete: {
parameters: {
query: {
id?: parameters['rowFilter.auth_key.id']
name?: parameters['rowFilter.auth_key.name']
secret?: parameters['rowFilter.auth_key.secret']
user_id?: parameters['rowFilter.auth_key.user_id']
inserted_at?: parameters['rowFilter.auth_key.inserted_at']
updated_at?: parameters['rowFilter.auth_key.updated_at']
deleted_at?: parameters['rowFilter.auth_key.deleted_at']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** No Content */
204: never
}
}
patch: {
parameters: {
query: {
id?: parameters['rowFilter.auth_key.id']
name?: parameters['rowFilter.auth_key.name']
secret?: parameters['rowFilter.auth_key.secret']
user_id?: parameters['rowFilter.auth_key.user_id']
inserted_at?: parameters['rowFilter.auth_key.inserted_at']
updated_at?: parameters['rowFilter.auth_key.updated_at']
deleted_at?: parameters['rowFilter.auth_key.deleted_at']
}
body: {
/** auth_key */
auth_key?: definitions['auth_key']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** No Content */
204: never
}
}
}
'/content': {
get: {
parameters: {
query: {
cid?: parameters['rowFilter.content.cid']
dag_size?: parameters['rowFilter.content.dag_size']
inserted_at?: parameters['rowFilter.content.inserted_at']
updated_at?: parameters['rowFilter.content.updated_at']
/** Filtering Columns */
select?: parameters['select']
/** Ordering */
order?: parameters['order']
/** Limiting and Pagination */
offset?: parameters['offset']
/** Limiting and Pagination */
limit?: parameters['limit']
}
header: {
/** Limiting and Pagination */
Range?: parameters['range']
/** Limiting and Pagination */
'Range-Unit'?: parameters['rangeUnit']
/** Preference */
Prefer?: parameters['preferCount']
}
}
responses: {
/** OK */
200: {
schema: definitions['content'][]
}
/** Partial Content */
206: unknown
}
}
post: {
parameters: {
body: {
/** content */
content?: definitions['content']
}
query: {
/** Filtering Columns */
select?: parameters['select']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** Created */
201: unknown
}
}
delete: {
parameters: {
query: {
cid?: parameters['rowFilter.content.cid']
dag_size?: parameters['rowFilter.content.dag_size']
inserted_at?: parameters['rowFilter.content.inserted_at']
updated_at?: parameters['rowFilter.content.updated_at']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** No Content */
204: never
}
}
patch: {
parameters: {
query: {
cid?: parameters['rowFilter.content.cid']
dag_size?: parameters['rowFilter.content.dag_size']
inserted_at?: parameters['rowFilter.content.inserted_at']
updated_at?: parameters['rowFilter.content.updated_at']
}
body: {
/** content */
content?: definitions['content']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** No Content */
204: never
}
}
}
'/deal': {
get: {
parameters: {
query: {
deal_id?: parameters['rowFilter.deal.deal_id']
aggregate_cid?: parameters['rowFilter.deal.aggregate_cid']
client?: parameters['rowFilter.deal.client']
provider?: parameters['rowFilter.deal.provider']
status?: parameters['rowFilter.deal.status']
start_epoch?: parameters['rowFilter.deal.start_epoch']
end_epoch?: parameters['rowFilter.deal.end_epoch']
entry_created?: parameters['rowFilter.deal.entry_created']
entry_last_updated?: parameters['rowFilter.deal.entry_last_updated']
status_meta?: parameters['rowFilter.deal.status_meta']
start_time?: parameters['rowFilter.deal.start_time']
sector_start_epoch?: parameters['rowFilter.deal.sector_start_epoch']
sector_start_time?: parameters['rowFilter.deal.sector_start_time']
end_time?: parameters['rowFilter.deal.end_time']
/** Filtering Columns */
select?: parameters['select']
/** Ordering */
order?: parameters['order']
/** Limiting and Pagination */
offset?: parameters['offset']
/** Limiting and Pagination */
limit?: parameters['limit']
}
header: {
/** Limiting and Pagination */
Range?: parameters['range']
/** Limiting and Pagination */
'Range-Unit'?: parameters['rangeUnit']
/** Preference */
Prefer?: parameters['preferCount']
}
}
responses: {
/** OK */
200: {
schema: definitions['deal'][]
}
/** Partial Content */
206: unknown
}
}
}
'/migration_event': {
get: {
parameters: {
query: {
id?: parameters['rowFilter.migration_event.id']
name?: parameters['rowFilter.migration_event.name']
data?: parameters['rowFilter.migration_event.data']
inserted_at?: parameters['rowFilter.migration_event.inserted_at']
/** Filtering Columns */
select?: parameters['select']
/** Ordering */
order?: parameters['order']
/** Limiting and Pagination */
offset?: parameters['offset']
/** Limiting and Pagination */
limit?: parameters['limit']
}
header: {
/** Limiting and Pagination */
Range?: parameters['range']
/** Limiting and Pagination */
'Range-Unit'?: parameters['rangeUnit']
/** Preference */
Prefer?: parameters['preferCount']
}
}
responses: {
/** OK */
200: {
schema: definitions['migration_event'][]
}
/** Partial Content */
206: unknown
}
}
post: {
parameters: {
body: {
/** migration_event */
migration_event?: definitions['migration_event']
}
query: {
/** Filtering Columns */
select?: parameters['select']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** Created */
201: unknown
}
}
delete: {
parameters: {
query: {
id?: parameters['rowFilter.migration_event.id']
name?: parameters['rowFilter.migration_event.name']
data?: parameters['rowFilter.migration_event.data']
inserted_at?: parameters['rowFilter.migration_event.inserted_at']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** No Content */
204: never
}
}
patch: {
parameters: {
query: {
id?: parameters['rowFilter.migration_event.id']
name?: parameters['rowFilter.migration_event.name']
data?: parameters['rowFilter.migration_event.data']
inserted_at?: parameters['rowFilter.migration_event.inserted_at']
}
body: {
/** migration_event */
migration_event?: definitions['migration_event']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** No Content */
204: never
}
}
}
'/pin': {
get: {
parameters: {
query: {
id?: parameters['rowFilter.pin.id']
status?: parameters['rowFilter.pin.status']
content_cid?: parameters['rowFilter.pin.content_cid']
service?: parameters['rowFilter.pin.service']
inserted_at?: parameters['rowFilter.pin.inserted_at']
updated_at?: parameters['rowFilter.pin.updated_at']
/** Filtering Columns */
select?: parameters['select']
/** Ordering */
order?: parameters['order']
/** Limiting and Pagination */
offset?: parameters['offset']
/** Limiting and Pagination */
limit?: parameters['limit']
}
header: {
/** Limiting and Pagination */
Range?: parameters['range']
/** Limiting and Pagination */
'Range-Unit'?: parameters['rangeUnit']
/** Preference */
Prefer?: parameters['preferCount']
}
}
responses: {
/** OK */
200: {
schema: definitions['pin'][]
}
/** Partial Content */
206: unknown
}
}
post: {
parameters: {
body: {
/** pin */
pin?: definitions['pin']
}
query: {
/** Filtering Columns */
select?: parameters['select']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** Created */
201: unknown
}
}
delete: {
parameters: {
query: {
id?: parameters['rowFilter.pin.id']
status?: parameters['rowFilter.pin.status']
content_cid?: parameters['rowFilter.pin.content_cid']
service?: parameters['rowFilter.pin.service']
inserted_at?: parameters['rowFilter.pin.inserted_at']
updated_at?: parameters['rowFilter.pin.updated_at']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** No Content */
204: never
}
}
patch: {
parameters: {
query: {
id?: parameters['rowFilter.pin.id']
status?: parameters['rowFilter.pin.status']
content_cid?: parameters['rowFilter.pin.content_cid']
service?: parameters['rowFilter.pin.service']
inserted_at?: parameters['rowFilter.pin.inserted_at']
updated_at?: parameters['rowFilter.pin.updated_at']
}
body: {
/** pin */
pin?: definitions['pin']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** No Content */
204: never
}
}
}
'/upload': {
get: {
parameters: {
query: {
id?: parameters['rowFilter.upload.id']
user_id?: parameters['rowFilter.upload.user_id']
key_id?: parameters['rowFilter.upload.key_id']
content_cid?: parameters['rowFilter.upload.content_cid']
source_cid?: parameters['rowFilter.upload.source_cid']
mime_type?: parameters['rowFilter.upload.mime_type']
type?: parameters['rowFilter.upload.type']
name?: parameters['rowFilter.upload.name']
files?: parameters['rowFilter.upload.files']
origins?: parameters['rowFilter.upload.origins']
meta?: parameters['rowFilter.upload.meta']
inserted_at?: parameters['rowFilter.upload.inserted_at']
updated_at?: parameters['rowFilter.upload.updated_at']
deleted_at?: parameters['rowFilter.upload.deleted_at']
/** Filtering Columns */
select?: parameters['select']
/** Ordering */
order?: parameters['order']
/** Limiting and Pagination */
offset?: parameters['offset']
/** Limiting and Pagination */
limit?: parameters['limit']
}
header: {
/** Limiting and Pagination */
Range?: parameters['range']
/** Limiting and Pagination */
'Range-Unit'?: parameters['rangeUnit']
/** Preference */
Prefer?: parameters['preferCount']
}
}
responses: {
/** OK */
200: {
schema: definitions['upload'][]
}
/** Partial Content */
206: unknown
}
}
post: {
parameters: {
body: {
/** upload */
upload?: definitions['upload']
}
query: {
/** Filtering Columns */
select?: parameters['select']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** Created */
201: unknown
}
}
delete: {
parameters: {
query: {
id?: parameters['rowFilter.upload.id']
user_id?: parameters['rowFilter.upload.user_id']
key_id?: parameters['rowFilter.upload.key_id']
content_cid?: parameters['rowFilter.upload.content_cid']
source_cid?: parameters['rowFilter.upload.source_cid']
mime_type?: parameters['rowFilter.upload.mime_type']
type?: parameters['rowFilter.upload.type']
name?: parameters['rowFilter.upload.name']
files?: parameters['rowFilter.upload.files']
origins?: parameters['rowFilter.upload.origins']
meta?: parameters['rowFilter.upload.meta']
inserted_at?: parameters['rowFilter.upload.inserted_at']
updated_at?: parameters['rowFilter.upload.updated_at']
deleted_at?: parameters['rowFilter.upload.deleted_at']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** No Content */
204: never
}
}
patch: {
parameters: {
query: {
id?: parameters['rowFilter.upload.id']
user_id?: parameters['rowFilter.upload.user_id']
key_id?: parameters['rowFilter.upload.key_id']
content_cid?: parameters['rowFilter.upload.content_cid']
source_cid?: parameters['rowFilter.upload.source_cid']
mime_type?: parameters['rowFilter.upload.mime_type']
type?: parameters['rowFilter.upload.type']
name?: parameters['rowFilter.upload.name']
files?: parameters['rowFilter.upload.files']
origins?: parameters['rowFilter.upload.origins']
meta?: parameters['rowFilter.upload.meta']
inserted_at?: parameters['rowFilter.upload.inserted_at']
updated_at?: parameters['rowFilter.upload.updated_at']
deleted_at?: parameters['rowFilter.upload.deleted_at']
}
body: {
/** upload */
upload?: definitions['upload']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** No Content */
204: never
}
}
}
'/user': {
get: {
parameters: {
query: {
id?: parameters['rowFilter.user.id']
magic_link_id?: parameters['rowFilter.user.magic_link_id']
github_id?: parameters['rowFilter.user.github_id']
name?: parameters['rowFilter.user.name']
picture?: parameters['rowFilter.user.picture']
email?: parameters['rowFilter.user.email']
public_address?: parameters['rowFilter.user.public_address']
github?: parameters['rowFilter.user.github']
inserted_at?: parameters['rowFilter.user.inserted_at']
updated_at?: parameters['rowFilter.user.updated_at']
/** Filtering Columns */
select?: parameters['select']
/** Ordering */
order?: parameters['order']
/** Limiting and Pagination */
offset?: parameters['offset']
/** Limiting and Pagination */
limit?: parameters['limit']
}
header: {
/** Limiting and Pagination */
Range?: parameters['range']
/** Limiting and Pagination */
'Range-Unit'?: parameters['rangeUnit']
/** Preference */
Prefer?: parameters['preferCount']
}
}
responses: {
/** OK */
200: {
schema: definitions['user'][]
}
/** Partial Content */
206: unknown
}
}
post: {
parameters: {
body: {
/** user */
user?: definitions['user']
}
query: {
/** Filtering Columns */
select?: parameters['select']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** Created */
201: unknown
}
}
delete: {
parameters: {
query: {
id?: parameters['rowFilter.user.id']
magic_link_id?: parameters['rowFilter.user.magic_link_id']
github_id?: parameters['rowFilter.user.github_id']
name?: parameters['rowFilter.user.name']
picture?: parameters['rowFilter.user.picture']
email?: parameters['rowFilter.user.email']
public_address?: parameters['rowFilter.user.public_address']
github?: parameters['rowFilter.user.github']
inserted_at?: parameters['rowFilter.user.inserted_at']
updated_at?: parameters['rowFilter.user.updated_at']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** No Content */
204: never
}
}
patch: {
parameters: {
query: {
id?: parameters['rowFilter.user.id']
magic_link_id?: parameters['rowFilter.user.magic_link_id']
github_id?: parameters['rowFilter.user.github_id']
name?: parameters['rowFilter.user.name']
picture?: parameters['rowFilter.user.picture']
email?: parameters['rowFilter.user.email']
public_address?: parameters['rowFilter.user.public_address']
github?: parameters['rowFilter.user.github']
inserted_at?: parameters['rowFilter.user.inserted_at']
updated_at?: parameters['rowFilter.user.updated_at']
}
body: {
/** user */
user?: definitions['user']
}
header: {
/** Preference */
Prefer?: parameters['preferReturn']
}
}
responses: {
/** No Content */
204: never
}
}
}
'/rpc/postgres_fdw_handler': {
post: {
parameters: {
body: {
args: { [key: string]: unknown }
}
header: {
/** Preference */
Prefer?: parameters['preferParams']
}
}
responses: {
/** OK */
200: unknown
}
}
}
'/rpc/pgrst_watch': {
post: {
parameters: {
body: {
args: { [key: string]: unknown }
}
header: {
/** Preference */
Prefer?: parameters['preferParams']
}
}
responses: {
/** OK */
200: unknown
}
}
}
'/rpc/postgres_fdw_validator': {
post: {
parameters: {
body: {
args: {
'': string
}
}
header: {
/** Preference */
Prefer?: parameters['preferParams']
}
}
responses: {
/** OK */
200: unknown
}
}
}
'/rpc/find_deals_by_content_cids': {
post: {
parameters: {
body: {
args: {
cids: string
}
}
header: {
/** Preference */
Prefer?: parameters['preferParams']
}
}
responses: {
/** OK */
200: unknown
}
}
}
'/rpc/create_upload': {
post: {
parameters: {
body: {
args: {
data: string
}
}
header: {
/** Preference */
Prefer?: parameters['preferParams']
}
}
responses: {
/** OK */
200: unknown
}
}
}
}
export interface definitions {
aggregate: {
aggregate_cid?: string
piece_cid?: string
sha256hex?: string
export_size?: number
metadata?: string
entry_created?: string
}
aggregate_entry: {
aggregate_cid?: string
cid_v1?: string
datamodel_selector?: string
}
auth_key: {
/**
* Note:
* This is a Primary Key.<pk/>
*/
id: number
name: string
secret: string
/**
* Note:
* This is a Foreign Key to `user.id`.<fk table='user' column='id'/>
*/
user_id: number
inserted_at: string
updated_at: string
deleted_at?: string
}
content: {
/**
* Note:
* This is a Primary Key.<pk/>
*/
cid: string
dag_size?: number
inserted_at: string
updated_at: string
}
deal: {
deal_id?: number
aggregate_cid?: string
client?: string
provider?: string
status?: string
start_epoch?: number
end_epoch?: number
entry_created?: string
entry_last_updated?: string
status_meta?: string
start_time?: string
sector_start_epoch?: number
sector_start_time?: string
end_time?: string
}
migration_event: {
/**
* Note:
* This is a Primary Key.<pk/>
*/
id: number
name: string
data?: string
inserted_at: string
}
pin: {
/**
* Note:
* This is a Primary Key.<pk/>
*/
id: number
status: 'PinError' | 'PinQueued' | 'Pinned' | 'Pinning'
/**
* Note:
* This is a Foreign Key to `content.cid`.<fk table='content' column='cid'/>
*/
content_cid: string
service: 'Pinata' | 'IpfsCluster' | 'IpfsCluster2'
inserted_at: string
updated_at: string
}
upload: {
/**
* Note:
* This is a Primary Key.<pk/>
*/
id: number
/**
* Note:
* This is a Foreign Key to `user.id`.<fk table='user' column='id'/>
*/
user_id: number
/**
* Note:
* This is a Foreign Key to `auth_key.id`.<fk table='auth_key' column='id'/>
*/
key_id?: number
/**
* Note:
* This is a Foreign Key to `content.cid`.<fk table='content' column='cid'/>
*/
content_cid: string
source_cid: string
mime_type?: string
type: 'Car' | 'Blob' | 'Multipart' | 'Remote' | 'Nft'
name?: string
files?: string
origins?: string
meta?: string
inserted_at: string
updated_at: string
deleted_at?: string
}
user: {
/**
* Note:
* This is a Primary Key.<pk/>
*/
id: number
magic_link_id?: string
github_id: string
name: string
picture?: string
email: string
public_address?: string
github?: string
inserted_at: string
updated_at: string
}
}
export interface parameters {
/** Preference */
preferParams: 'params=single-object'
/** Preference */
preferReturn: 'return=representation' | 'return=minimal' | 'return=none'
/** Preference */
preferCount: 'count=none'
/** Filtering Columns */
select: string
/** On Conflict */
on_conflict: string
/** Ordering */
order: string
/** Limiting and Pagination */
range: string
/** Limiting and Pagination */
rangeUnit: string
/** Limiting and Pagination */
offset: string
/** Limiting and Pagination */
limit: string
/** aggregate */
'body.aggregate': definitions['aggregate']
'rowFilter.aggregate.aggregate_cid': string
'rowFilter.aggregate.piece_cid': string
'rowFilter.aggregate.sha256hex': string
'rowFilter.aggregate.export_size': string
'rowFilter.aggregate.metadata': string
'rowFilter.aggregate.entry_created': string
/** aggregate_entry */
'body.aggregate_entry': definitions['aggregate_entry']
'rowFilter.aggregate_entry.aggregate_cid': string
'rowFilter.aggregate_entry.cid_v1': string
'rowFilter.aggregate_entry.datamodel_selector': string
/** auth_key */
'body.auth_key': definitions['auth_key']
'rowFilter.auth_key.id': string
'rowFilter.auth_key.name': string
'rowFilter.auth_key.secret': string
'rowFilter.auth_key.user_id': string
'rowFilter.auth_key.inserted_at': string
'rowFilter.auth_key.updated_at': string
'rowFilter.auth_key.deleted_at': string
/** content */
'body.content': definitions['content']
'rowFilter.content.cid': string
'rowFilter.content.dag_size': string
'rowFilter.content.inserted_at': string
'rowFilter.content.updated_at': string
/** deal */
'body.deal': definitions['deal']
'rowFilter.deal.deal_id': string
'rowFilter.deal.aggregate_cid': string
'rowFilter.deal.client': string
'rowFilter.deal.provider': string
'rowFilter.deal.status': string
'rowFilter.deal.start_epoch': string
'rowFilter.deal.end_epoch': string
'rowFilter.deal.entry_created': string
'rowFilter.deal.entry_last_updated': string
'rowFilter.deal.status_meta': string
'rowFilter.deal.start_time': string
'rowFilter.deal.sector_start_epoch': string
'rowFilter.deal.sector_start_time': string
'rowFilter.deal.end_time': string
/** migration_event */
'body.migration_event': definitions['migration_event']
'rowFilter.migration_event.id': string
'rowFilter.migration_event.name': string
'rowFilter.migration_event.data': string
'rowFilter.migration_event.inserted_at': string
/** pin */
'body.pin': definitions['pin']
'rowFilter.pin.id': string
'rowFilter.pin.status': string
'rowFilter.pin.content_cid': string
'rowFilter.pin.service': string
'rowFilter.pin.inserted_at': string
'rowFilter.pin.updated_at': string
/** upload */
'body.upload': definitions['upload']
'rowFilter.upload.id': string
'rowFilter.upload.user_id': string
'rowFilter.upload.key_id': string
'rowFilter.upload.content_cid': string
'rowFilter.upload.source_cid': string
'rowFilter.upload.mime_type': string
'rowFilter.upload.type': string
'rowFilter.upload.name': string
'rowFilter.upload.files': string
'rowFilter.upload.origins': string
'rowFilter.upload.meta': string
'rowFilter.upload.inserted_at': string
'rowFilter.upload.updated_at': string
'rowFilter.upload.deleted_at': string
/** user */
'body.user': definitions['user']
'rowFilter.user.id': string
'rowFilter.user.magic_link_id': string
'rowFilter.user.github_id': string
'rowFilter.user.name': string
'rowFilter.user.picture': string
'rowFilter.user.email': string
'rowFilter.user.public_address': string
'rowFilter.user.github': string
'rowFilter.user.inserted_at': string
'rowFilter.user.updated_at': string
}
export interface operations {}
export interface external {} | the_stack |
import { EventEmitter } from 'events';
import * as WebSocket from 'ws';
import { SignalingErrors } from './errors';
import Log from './log';
// tslint:disable-next-line
const Backoff = require('backoff');
const CONNECT_SUCCESS_TIMEOUT = 10000;
const CONNECT_TIMEOUT = 5000;
const HEARTBEAT_TIMEOUT = 15000;
export interface IMessageEvent {
data: string;
target: WebSocket;
type: string;
}
/**
* All possible states of WSTransport.
*/
export enum WSTransportState {
/**
* The WebSocket is not open but is trying to connect.
*/
Connecting = 'connecting',
/**
* The WebSocket is not open and is not trying to connect.
*/
Closed = 'closed',
/**
* The underlying WebSocket is open and active.
*/
Open = 'open',
}
/**
* Options to be passed to the WSTransport constructor.
*/
export interface IWSTransportConstructorOptions {
/**
* Maximum time to wait before attempting to reconnect the signaling websocket.
* Default is 20000ms. Minimum is 3000ms.
*/
backoffMaxMs?: number;
/**
* Time in milliseconds before websocket times out when attempting to connect
*/
connectTimeoutMs?: number;
/**
* A WebSocket factory to use instead of WebSocket.
*/
WebSocket?: any;
}
/**
* WebSocket Transport
*/
export default class WSTransport extends EventEmitter {
/**
* The current state of the WSTransport.
*/
state: WSTransportState = WSTransportState.Closed;
/**
* The backoff instance used to schedule reconnection attempts.
*/
private readonly _backoff: any;
/**
* The current connection timeout. If it times out, we've failed to connect
* and should try again.
*
* We use any here because NodeJS returns a Timer and browser returns a number
* and one can't be cast to the other, despite their working interoperably.
*/
private _connectTimeout?: any;
/**
* Time in milliseconds before websocket times out when attempting to connect
*/
private _connectTimeoutMs?: number;
/**
* The current connection timeout. If it times out, we've failed to connect
* and should try again.
*
* We use any here because NodeJS returns a Timer and browser returns a number
* and one can't be cast to the other, despite their working interoperably.
*/
private _heartbeatTimeout?: any;
/**
* An instance of Logger to use.
*/
private _log: Log = Log.getInstance();
/**
* Previous state of the connection
*/
private _previousState: WSTransportState;
/**
* Whether we should attempt to fallback if we receive an applicable error
* when trying to connect to a signaling endpoint.
*/
private _shouldFallback: boolean = false;
/**
* The currently connecting or open WebSocket.
*/
private _socket?: WebSocket;
/**
* The time the active connection was opened.
*/
private _timeOpened?: number;
/**
* The current uri index that the transport is connected to.
*/
private _uriIndex: number = 0;
/**
* List of URI of the endpoints to connect to.
*/
private readonly _uris: string[];
/**
* The constructor to use for WebSocket
*/
private readonly _WebSocket: typeof WebSocket;
/**
* @constructor
* @param uris - List of URI of the endpoints to connect to.
* @param [options] - Constructor options.
*/
constructor(uris: string[], options: IWSTransportConstructorOptions = { }) {
super();
this._connectTimeoutMs = options.connectTimeoutMs || CONNECT_TIMEOUT;
let initialDelay = 100;
if (uris && uris.length > 1) {
// We only want a random initial delay if there are any fallback edges
// Initial delay between 1s and 5s both inclusive
initialDelay = Math.floor(Math.random() * (5000 - 1000 + 1)) + 1000;
}
const backoffConfig = {
factor: 2.0,
initialDelay,
maxDelay: typeof options.backoffMaxMs === 'number'
? Math.max(options.backoffMaxMs, 3000)
: 20000,
randomisationFactor: 0.40,
};
this._log.info('Initializing transport backoff using config: ', backoffConfig);
this._backoff = Backoff.exponential(backoffConfig);
this._uris = uris;
this._WebSocket = options.WebSocket || WebSocket;
// Called when a backoff timer is started.
this._backoff.on('backoff', (_: any, delay: number) => {
if (this.state === WSTransportState.Closed) { return; }
this._log.info(`Will attempt to reconnect WebSocket in ${delay}ms`);
});
// Called when a backoff timer ends. We want to try to reconnect
// the WebSocket at this point.
this._backoff.on('ready', (attempt: number) => {
if (this.state === WSTransportState.Closed) { return; }
this._connect(attempt + 1);
});
}
/**
* Close the WebSocket, and don't try to reconnect.
*/
close(): void {
this._log.info('WSTransport.close() called...');
this._close();
}
/**
* Attempt to open a WebSocket connection.
*/
open(): void {
this._log.info('WSTransport.open() called...');
if (this._socket &&
(this._socket.readyState === WebSocket.CONNECTING ||
this._socket.readyState === WebSocket.OPEN)) {
this._log.info('WebSocket already open.');
return;
}
this._connect();
}
/**
* Send a message through the WebSocket connection.
* @param message - A message to send to the endpoint.
* @returns Whether the message was sent.
*/
send(message: string): boolean {
// We can't send the message if the WebSocket isn't open
if (!this._socket || this._socket.readyState !== WebSocket.OPEN) {
return false;
}
try {
this._socket.send(message);
} catch (e) {
// Some unknown error occurred. Reset the socket to get a fresh session.
this._log.info('Error while sending message:', e.message);
this._closeSocket();
return false;
}
return true;
}
/**
* Close the WebSocket, and don't try to reconnect.
*/
private _close(): void {
this._setState(WSTransportState.Closed);
this._closeSocket();
}
/**
* Close the WebSocket and remove all event listeners.
*/
private _closeSocket(): void {
clearTimeout(this._connectTimeout);
clearTimeout(this._heartbeatTimeout);
this._log.info('Closing and cleaning up WebSocket...');
if (!this._socket) {
this._log.info('No WebSocket to clean up.');
return;
}
this._socket.removeEventListener('close', this._onSocketClose as any);
this._socket.removeEventListener('error', this._onSocketError as any);
this._socket.removeEventListener('message', this._onSocketMessage as any);
this._socket.removeEventListener('open', this._onSocketOpen as any);
if (this._socket.readyState === WebSocket.CONNECTING ||
this._socket.readyState === WebSocket.OPEN) {
this._socket.close();
}
// Reset backoff counter if connection was open for long enough to be considered successful
if (this._timeOpened && Date.now() - this._timeOpened > CONNECT_SUCCESS_TIMEOUT) {
this._backoff.reset();
}
this._backoff.backoff();
delete this._socket;
this.emit('close');
}
/**
* Attempt to connect to the endpoint via WebSocket.
* @param [retryCount] - Retry number, if this is a retry. Undefined if
* first attempt, 1+ if a retry.
*/
private _connect(retryCount?: number): void {
if (retryCount) {
this._log.info(`Attempting to reconnect (retry #${retryCount})...`);
} else {
this._log.info('Attempting to connect...');
}
this._closeSocket();
this._setState(WSTransportState.Connecting);
let socket = null;
try {
socket = new this._WebSocket(this._uris[this._uriIndex]);
} catch (e) {
this._log.info('Could not connect to endpoint:', e.message);
this._close();
this.emit('error', {
code: 31000,
message: e.message || `Could not connect to ${this._uris[this._uriIndex]}`,
twilioError: new SignalingErrors.ConnectionDisconnected(),
});
return;
}
delete this._timeOpened;
this._connectTimeout = setTimeout(() => {
this._log.info('WebSocket connection attempt timed out.');
this._moveUriIndex();
this._closeSocket();
}, this._connectTimeoutMs);
socket.addEventListener('close', this._onSocketClose as any);
socket.addEventListener('error', this._onSocketError as any);
socket.addEventListener('message', this._onSocketMessage as any);
socket.addEventListener('open', this._onSocketOpen as any);
this._socket = socket;
}
/**
* Move the uri index to the next index
* If the index is at the end, the index goes back to the first one.
*/
private _moveUriIndex = (): void => {
this._uriIndex++;
if (this._uriIndex >= this._uris.length) {
this._uriIndex = 0;
}
}
/**
* Called in response to WebSocket#close event.
*/
private _onSocketClose = (event: CloseEvent): void => {
this._log.info(`Received websocket close event code: ${event.code}. Reason: ${event.reason}`);
// 1006: Abnormal close. When the server is unreacheable
// 1015: TLS Handshake error
if (event.code === 1006 || event.code === 1015) {
this.emit('error', {
code: 31005,
message: event.reason ||
'Websocket connection to Twilio\'s signaling servers were ' +
'unexpectedly ended. If this is happening consistently, there may ' +
'be an issue resolving the hostname provided. If a region or an ' +
'edge is being specified in Device setup, ensure it is valid.',
twilioError: new SignalingErrors.ConnectionError(),
});
const wasConnected = (
// Only in Safari and certain Firefox versions, on network interruption, websocket drops right away with 1006
// Let's check current state if it's open, meaning we should not fallback
// because we're coming from a previously connected session
this.state === WSTransportState.Open ||
// But on other browsers, websocket doesn't drop
// but our heartbeat catches it, setting the internal state to "Connecting".
// With this, we should check the previous state instead.
this._previousState === WSTransportState.Open
);
// Only fallback if this is not the first error
// and if we were not connected previously
if (this._shouldFallback || !wasConnected) {
this._moveUriIndex();
}
this._shouldFallback = true;
}
this._closeSocket();
}
/**
* Called in response to WebSocket#error event.
*/
private _onSocketError = (err: Error): void => {
this._log.info(`WebSocket received error: ${err.message}`);
this.emit('error', {
code: 31000,
message: err.message || 'WSTransport socket error',
twilioError: new SignalingErrors.ConnectionDisconnected(),
});
}
/**
* Called in response to WebSocket#message event.
*/
private _onSocketMessage = (message: IMessageEvent): void => {
// Clear heartbeat timeout on any incoming message, as they
// all indicate an active connection.
this._setHeartbeatTimeout();
// Filter and respond to heartbeats
if (this._socket && message.data === '\n') {
this._socket.send('\n');
return;
}
this.emit('message', message);
}
/**
* Called in response to WebSocket#open event.
*/
private _onSocketOpen = (): void => {
this._log.info('WebSocket opened successfully.');
this._timeOpened = Date.now();
this._shouldFallback = false;
this._setState(WSTransportState.Open);
clearTimeout(this._connectTimeout);
this._setHeartbeatTimeout();
this.emit('open');
}
/**
* Set a timeout to reconnect after HEARTBEAT_TIMEOUT milliseconds
* have passed without receiving a message over the WebSocket.
*/
private _setHeartbeatTimeout(): void {
clearTimeout(this._heartbeatTimeout);
this._heartbeatTimeout = setTimeout(() => {
this._log.info(`No messages received in ${HEARTBEAT_TIMEOUT / 1000} seconds. Reconnecting...`);
this._shouldFallback = true;
this._closeSocket();
}, HEARTBEAT_TIMEOUT);
}
/**
* Set the current and previous state
*/
private _setState(state: WSTransportState): void {
this._previousState = this.state;
this.state = state;
}
/**
* The uri the transport is currently connected to
*/
get uri(): string {
return this._uris[this._uriIndex];
}
} | the_stack |
'use strict';
//core
import * as util from 'util';
import * as assert from 'assert';
import * as net from 'net';
//npm
import UUID = require('uuid');
import chalk from "chalk";
//project
import {createParser} from "./json-parser";
import * as cu from './client-utils';
const clientPackage = require('../package.json');
if (!(clientPackage.version && typeof clientPackage.version === 'string')) {
throw new Error('Client NPM package did not have a top-level field that is a string.');
}
const PromiseSymbol = Symbol('is promise method');
import {weAreDebugging} from './we-are-debugging';
import Timer = NodeJS.Timer;
import {EventEmitter} from 'events';
import * as path from "path";
import {LMXLockRequestError, LMXUnlockRequestError} from "./shared-internal";
import {LMXClientLockException, LMXClientUnlockException} from "./exceptions";
import {EVCb} from "./shared-internal";
import {LMXClientException} from "./exceptions";
import {LMXClientError} from "./shared-internal";
import {inspectError} from "./shared-internal";
import {log} from "./client-utils";
if (weAreDebugging) {
log.debug('lmx client is in debug mode. Timeouts are turned off.');
}
export interface ValidConstructorOpts {
[key: string]: string
}
export const validConstructorOptions = <ValidConstructorOpts>{
key: 'string',
listener: 'function',
connectTimeout: 'integer (in millis)',
host: 'string',
port: 'integer',
ttl: 'integer (in millis)',
unlockRequestTimeout: 'integer (in millis)',
lockRequestTimeout: 'integer (in millis)',
lockRetryMax: 'integer',
keepLocksAfterDeath: 'boolean (if the client process exits, the broker keeps the relevant locks locked.)',
keepLocksOnExit: 'boolean ()',
noDelay: 'boolean (the tcp protocol "no delay" option)',
udsPath: 'string (an absolute file path)'
};
export const validLockOptions = {
force: 'boolean',
maxRetries: 'integer',
maxRetry: 'integer',
ttl: 'integer (in millis)',
lockRequestTimeout: 'integer (in millis)',
keepLocksAfterDeath: 'boolean',
keepLocksOnExit: 'boolean'
};
export const validUnlockOptions = {
force: 'boolean',
unlockRequestTimeout: 'integer',
keepLocksAfterDeath: 'boolean'
};
export interface ClientOpts {
key: string,
listener: Function,
host: string,
port: number
unlockRequestTimeout: number;
lockRequestTimeout: number;
lockRetryMax: number;
retryMax: number;
maxRetries: number;
ttl: number,
keepLocksAfterDeath: boolean,
keepLocksOnExit: boolean,
noDelay: boolean;
udsPath: string;
connectTimeout?: number
}
export type EndReadCallback = (err?: any, val?: any) => void;
export interface IUuidTimeoutBool {
[key: string]: boolean
}
export interface IClientResolution {
[key: string]: EVCb<any>
}
export type LMClientCallBack = (err: any, c?: Client) => void;
export type Ensure = (cb?: LMClientCallBack) => Promise<Client>;
export interface UuidBooleanHash {
[key: string]: boolean;
}
export interface LMXClientLockOpts {
ttl?: number,
lockRequestTimeout?: number,
[PromiseSymbol]? : boolean,
maxRetries?: number,
force?: boolean,
semaphore?: number,
max?: number,
retry?: boolean,
maxRetry?: number,
retryMax?: number,
_uuid?: string,
__maxRetries?: number,
__retryCount?: number
}
export interface LMXClientUnlockOpts {
[PromiseSymbol]? : boolean,
force?: boolean,
_uuid?: string,
__retryCount?: number,
id?: string,
rwStatus?: string,
unlockRequestTimeout?: number
}
export interface LMLockSuccessData {
(fn?: LMClientUnlockCallBack): void
acquired: true,
key: string,
unlock: LMLockSuccessData,
lockUuid: string,
readersCount: number,
id: string
}
export interface LMUnlockSuccessData {
unlocked: true,
key: string,
id: string
}
export interface LMClientLockCallBack {
(err: LMXClientLockException, v: LMLockSuccessData): void;
}
export interface LMClientUnlockCallBack {
(err: null | LMXClientUnlockException, v: LMUnlockSuccessData): void,
acquired?: boolean,
unlock?: LMClientUnlockCallBack,
release?: LMClientUnlockCallBack,
key?: string,
readersCount?: number | null
}
export class Client {
port = 6970;
host = 'localhost';
listeners: Object;
connectTimeout = 3000;
opts: Partial<ClientOpts>;
ttl: number;
noRecover: boolean;
unlockRequestTimeout: number;
lockRequestTimeout: number;
lockRetryMax: number;
ws: net.Socket = <any>null;
cannotContinue = false;
timeouts: IUuidTimeoutBool;
resolutions: IClientResolution;
ensure: Ensure;
connect: Ensure;
giveups: UuidBooleanHash;
timers: { [key: string]: Timer };
write: (data: any, cb?: EVCb<any>) => void;
isOpen: boolean;
close: () => void;
keepLocksAfterDeath = false;
keepLocksOnExit = false;
createNewConnection: () => void;
endCurrentConnection: () => void;
emitter = new EventEmitter();
noDelay = true;
socketFile = '';
recovering = false;
constructor(o?: Partial<ClientOpts>, cb?: LMClientCallBack) {
this.isOpen = false;
const opts = this.opts = o || {};
assert.strict(typeof opts === 'object', 'Bad arguments to lmx client constructor - options must be an object.');
if (cb) {
assert.strict(typeof cb === 'function', 'optional second argument to lmx Client constructor must be a function.');
}
for (const key of Object.keys(opts)) {
if (!validConstructorOptions[key]) {
throw new Error('An option passed to lmx Client constructor is ' +
`not a recognized option => "${key}", \n valid options are: ` + util.inspect(validConstructorOptions));
}
}
if ('host' in opts && opts.host !== undefined) {
assert.strict(typeof opts.host === 'string', 'lmx: "host" option needs to be a string.');
this.host = opts.host;
}
if ('port' in opts && opts.port !== undefined) {
assert.strict(Number.isInteger(opts.port),
cu.getClientErrorMessage(`the "port" option needs to be an integer.`));
assert.strict(opts.port > 1024 && opts.port < 49152,
cu.getClientErrorMessage('the "port" option needs to be an integer in the range (1025-49151).'));
this.port = opts.port;
}
if ('listener' in opts && opts.listener !== undefined) {
assert.strict(typeof opts.listener === 'function',
cu.getClientErrorMessage('the "listener" option should be a function.'));
assert.strict(typeof opts.key === 'string',
cu.getClientErrorMessage('you must pass in a key to use listener functionality.'));
}
if ('connectTimeout' in opts && opts.connectTimeout !== undefined) {
assert.strict(Number.isInteger(opts.connectTimeout),
cu.getClientErrorMessage('the "connectTimeout" option must be an integer.'));
assert.strict(opts.connectTimeout > 10 && opts.connectTimeout < 20000,
cu.getClientErrorMessage('the "connectTimeout" option must be between 10 and 20000 ms.'));
this.connectTimeout = opts.connectTimeout;
}
if ('lockRetryMax' in opts && opts.lockRetryMax !== undefined) {
assert.strict(Number.isInteger(opts.lockRetryMax),
cu.getClientErrorMessage('the "lockRetryMax" option needs to be an integer.'));
assert.strict(opts.lockRetryMax >= 0 && opts.lockRetryMax <= 100,
cu.getClientErrorMessage('the "lockRetryMax" integer needs to be in range (0-100).'));
}
if (opts['retryMax']) {
assert.strict(Number.isInteger(opts.retryMax),
cu.getClientErrorMessage('the "retryMax" option needs to be an integer.'));
assert.strict(opts.retryMax >= 0 && opts.retryMax <= 100,
cu.getClientErrorMessage('the "retryMax" integer needs to be in range (0-100).'));
}
if (opts['unlockRequestTimeout']) {
assert.strict(Number.isInteger(opts.unlockRequestTimeout),
cu.getClientErrorMessage('the "unlockRequestTimeout" option needs to be an integer (representing milliseconds).'));
assert.strict(opts.unlockRequestTimeout >= 20 && opts.unlockRequestTimeout <= 800000,
cu.getClientErrorMessage('the "unlockRequestTimeout" needs to be integer between 20 and 800000 millis.'));
}
if (opts['lockRequestTimeout']) {
assert.strict(Number.isInteger(opts.lockRequestTimeout),
cu.getClientErrorMessage('the "lockRequestTimeout" option needs to be an integer (representing milliseconds).'));
assert.strict(opts.lockRequestTimeout >= 20 && opts.lockRequestTimeout <= 800000,
cu.getClientErrorMessage('the "lockRequestTimeout" needs to be integer between 20 and 800000 millis.'));
}
if (opts['ttl']) {
assert.strict(Number.isInteger(opts.ttl),
cu.getClientErrorMessage('the "ttl" option needs to be an integer (representing milliseconds).'));
assert.strict(opts.ttl >= 3 && opts.ttl <= 800000,
cu.getClientErrorMessage('the "ttl" needs to be integer between 3 and 800000 millis.'));
}
if ('keepLocksAfterDeath' in opts) {
assert.strict(typeof opts.keepLocksAfterDeath === 'boolean',
cu.getClientErrorMessage('the "keepLocksAfterDeath" option needs to be a boolean.'));
}
if ('keepLocksOnExit' in opts) {
assert.strict(typeof opts.keepLocksOnExit === 'boolean',
cu.getClientErrorMessage('the "keepLocksOnExit" option needs to be a boolean.'));
}
if (opts.ttl === null) {
opts.ttl = Infinity;
}
if ('noDelay' in opts && opts['noDelay'] !== undefined) {
assert.strict(typeof opts.noDelay === 'boolean',
'lmx: "noDelay" option needs to be an integer => ' + opts.noDelay);
this.noDelay = opts.noDelay;
}
if ('udsPath' in opts && opts['udsPath'] !== undefined) {
assert.strict(typeof opts.udsPath === 'string', '"udsPath" option must be a string.');
assert.strict(path.isAbsolute(opts.udsPath), '"udsPath" option must be an absolute path.');
this.socketFile = path.resolve(opts.udsPath);
}
this.keepLocksAfterDeath = Boolean(opts.keepLocksAfterDeath || opts.keepLocksOnExit);
this.listeners = {};
this.ttl = weAreDebugging ? 5000000 : (opts.ttl || 7050);
this.unlockRequestTimeout = weAreDebugging ? 5000000 : (opts.unlockRequestTimeout || 8000);
this.lockRequestTimeout = weAreDebugging ? 5000000 : (opts.lockRequestTimeout || 3000);
this.lockRetryMax = opts.lockRetryMax || opts.maxRetries || opts.retryMax || 3;
let ws: net.Socket = <any>null;
let connectPromise: Promise<any> = <any>null;
const self = this;
this.emitter.on('warning', function () {
if (self.emitter.listenerCount('warning') < 2) {
log.warn('No "warning" event handler(s) attached by end-user to client.emitter, therefore logging these errors from LMX library:');
log.warn(...Array.from(arguments).map(v => (typeof v === 'string' ? v : util.inspect(v))));
log.warn('Add a "warning" event listener to the lmx client to get rid of this message.');
}
});
this.write = (data: any, cb?: EVCb<any>) => {
if (!ws) {
throw new Error('please call ensure()/connect() on this lmx client, before using the lock/unlock methods.');
}
if (!ws.writable) {
return this.ensure((err, val) => {
if (err) {
throw new Error('Could not reconnect.');
}
this.write(data, cb);
});
}
data.max = data.max || null;
data.pid = process.pid;
if (data.ttl === Infinity) {
data.ttl = null;
}
if ('keepLocksAfterDeath' in data) {
data.keepLocksAfterDeath = Boolean(data.keepLocksAfterDeath);
}
else {
data.keepLocksAfterDeath = this.keepLocksAfterDeath || false;
}
ws.write(JSON.stringify(data) + '\n', 'utf8', cb);
};
const onData = (data: any) => {
const uuid = data.uuid;
const _uuid = data._uuid;
if (!(data && typeof data === 'object')) {
return this.emitter.emit('error', 'Internal error -> data was not an object.');
}
if (data.error) {
this.emitter.emit('error', data.error);
}
if (data.warning) {
this.emitter.emit('warning', data.warning);
}
if (data.type === 'version-mismatch') {
this.emitter.emit('error', data);
log.error(data);
this.cannotContinue = true;
this.write({type: 'version-mismatch-confirmed'});
this._fireCallbacksPrematurely(new Error('lmx version-match:' + util.inspect(data)));
return;
}
if (!uuid) {
return this.emitter.emit('warning',
'Potential lmx implementation error => message did not contain uuid =>' + util.inspect(data)
);
}
const fn = this.resolutions[uuid];
const to = this.timeouts[uuid];
delete this.timeouts[uuid];
// delete self.resolutions[uuid]; // don't do this here, the same resolution fn might need to be called more than once
if (this.giveups[uuid]) {
clearTimeout(this.timers[uuid]);
delete this.giveups[uuid];
delete this.resolutions[uuid];
return;
}
if (fn && to) {
this.emitter.emit('error', 'lmx implementation error - resolution function and timeout both exist.');
}
if (to) {
this.emitter.emit('warning', 'Client side lock/unlock request timed-out.');
if (data.acquired === true && data.type === 'lock') {
self.write({uuid: uuid, _uuid, key: data.key, type: 'lock-received-rejected'});
}
return;
}
if (fn) {
fn.call(this, data.error, data);
return;
}
this.emitter.emit('warning', 'lmx implementation warning, ' +
'no fn with that uuid in the resolutions hash => ' + util.inspect(data, {breakLength: Infinity}));
if (data.acquired === true && data.type === 'lock') {
// this most likely occurs when a retry request gets sent before the previous lock request gets resolved
this.emitter.emit('warning', `Rejecting lock acquisition for key => "${data.key}".`);
this.write({
uuid: uuid,
key: data.key,
type: 'lock-received-rejected'
});
}
};
this.ensure = this.connect = (cb?: (err: any, v?: Client) => void) => {
if (cb) {
assert.strict(typeof cb === 'function', 'Optional argument to ensure/connect must be a function.');
if (process.domain) {
cb = process.domain.bind(cb);
}
}
if (!this.recovering && (connectPromise && ws && ws.writable)) { // && self.isOpen
return connectPromise.then((val) => {
cb && cb.call(self, null, val);
return val;
},
function (err) {
cb && cb.call(self, err);
return Promise.reject(err);
});
}
this.recovering = false;
if (ws) {
try {
ws.destroy();
}
finally {
ws.removeAllListeners();
}
}
return connectPromise = new Promise((resolve, reject) => {
const onFirstErr = (e: any) => {
this.noRecover = true;
const err = 'lmx client error: ' + inspectError(e);
this.emitter.emit('warning', err);
reject(err);
};
const to = setTimeout(function () {
reject('lmx client err: client connection timeout after 3000ms.');
}, this.connectTimeout);
const cnkt = self.socketFile ? [self.socketFile] : [self.port, self.host];
if(self.socketFile && opts.port){
log.fatal('a "port" option was provided along with "socketFile" option, please pick one.');
}
// @ts-ignore
ws = net.createConnection(...cnkt, () => {
self.isOpen = true;
clearTimeout(to);
ws.removeListener('error', onFirstErr);
this.write({type: 'version', value: clientPackage.version});
resolve(this);
});
if (self.noDelay) {
ws.setNoDelay(true);
}
let called = false;
const recover = (e: any) => {
if (called) {
return;
}
called = true;
if (this.noRecover) {
return;
}
this.recovering = true;
e && this.emitter.emit('warning', 'lmx client error: ' + inspectError(e));
if (!ws.destroyed) {
ws.destroy();
ws.removeAllListeners();
}
for (const [k, v] of Object.entries(this.resolutions)) {
this.giveups[k] = true;
clearTimeout(this.timers[k]);
v('lmx connection ended/closed. ' +
'A new connection will be created but all locking requests' +
' in-flight should get receive errors in the callbacks.', {});
}
// create new connection
this.ensure().then(() => {
log.debug('new connection created, via recover routine.');
});
};
ws.setEncoding('utf8')
.once('error', onFirstErr)
.once('close', () => {
this.emitter.emit('warning', 'lmx client stream "close" event occurred.');
recover(null);
})
.once('end', () => {
this.emitter.emit('warning', 'lmx client stream "end" event occurred.');
recover(null);
})
.on('error', (e: any) => {
this.emitter.emit('warning', 'lmx client stream "error" event occurred: ' + inspectError(e));
recover(e);
})
.pipe(createParser())
.on('data', onData)
})
// if the user passes a callback, we fire the callback here
.then(val => {
cb && cb.call(self, null, val);
return val;
},
err => {
cb && cb.call(self, err);
return Promise.reject(err);
});
};
process.once('exit', () => {
ws && ws.destroy();
});
this.endCurrentConnection = () => {
return ws && ws.end();
};
this.close = () => {
this.noRecover = true;
return ws && ws.destroy();
};
this.createNewConnection = () => {
return ws && ws.destroy();
};
this.timeouts = {};
this.resolutions = {};
this.giveups = {};
this.timers = {};
// if the user passes a callback, we call connect here
// on behalf of the user
cb && this.connect(cb);
};
private onSocketDestroy(err: any) {
log.info('Socket destroy callback error:', err);
}
static create(opts?: Partial<ClientOpts>): Client {
return new Client(opts);
}
getConnectionInterface() {
return this.socketFile || this.port;
}
getConnectionInterfaceStr() {
return this.socketFile ? `socket-file: ${this.socketFile}` : `host:port '${this.getHost()}:${this.getPort()}'`
}
private _fireCallbacksPrematurely(originalErr: any) {
for (const k of Object.keys(this.timers)) {
clearTimeout(this.timers[k]);
}
this.timers = {};
const err = new Error('Unknown error - firing resolution callbacks prematurely.');
for (let k of Object.keys(this.resolutions)) {
const fn = this.resolutions[k];
delete this.resolutions[k];
const e = {
message: err.message,
stack: err.stack,
forcePrematureCallback: true,
originalErrorString: inspectError(err)
};
fn.call(this, e, e);
}
}
setNoRecover() {
this.noRecover = true;
}
requestLockInfo(key: string, cb: EVCb<any>): void;
requestLockInfo(key: string, opts: any, cb: EVCb<any>): void;
requestLockInfo(key: string, opts: any | EVCb<any>, cb?: EVCb<any>) {
assert.equal(typeof key, 'string', 'Key passed to lmx#lock needs to be a string.');
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
opts = opts || {};
const uuid = opts._uuid || UUID.v4();
this.resolutions[uuid] = (err, data) => {
clearTimeout(this.timers[uuid]);
delete this.timeouts[uuid];
if (err) {
return this.fireCallbackWithError(cb, false, new LMXClientException(
key,
null,
LMXClientError.UnknownError,
err,
`Unknown error - see included "originalError" object.)`
));
}
if (String(key) !== String(data.key)) {
delete this.resolutions[uuid];
throw new Error('lmx implementation error => bad key.');
}
if (data.error) {
this.emitter.emit('warning', data.error);
}
if ([data.acquired, data.retry].filter(Boolean).length > 1) {
throw new Error('lmx implementation error, both "acquired" and "retry" options provided, there can be only one.');
}
if (data.lockInfo === true) {
delete this.resolutions[uuid];
cb(null, {data});
}
};
this.write({
uuid: uuid,
key: key,
type: 'lock-info-request',
});
}
acquire(key: string, opts?: Partial<LMXClientLockOpts>): Promise<LMLockSuccessData> {
return new Promise((resolve, reject) => {
try {
[key, opts] = this.preParseLockOptsForPromises(key, opts);
}
catch (err) {
return reject(err);
}
this.lock(key, opts, (err, val) => {
err ? reject(err) : resolve(val);
});
});
}
release(key: string, opts: Partial<LMXClientUnlockOpts>): Promise<LMUnlockSuccessData> {
return new Promise((resolve, reject) => {
try {
[key, opts] = this.preParseUnlockOptsForPromise(key, opts);
}
catch (err) {
return reject(err);
}
this.unlock(key, opts, (err, val) => {
err ? reject(err) : resolve(val);
});
});
}
lockp(key: string, opts?: Partial<LMXClientLockOpts>): Promise<LMLockSuccessData> {
log.warn('lockp is deprecated because it is a confusing method name, use aliases acquire/acquireLock instead.');
return this.acquire.apply(this, <any>arguments);
}
unlockp(key: string, opts: Partial<LMXClientUnlockOpts>): Promise<LMUnlockSuccessData> {
log.warn('unlockp is deprecated because it is a confusing method name, use aliases release/releaseLock instead.');
return this.release.apply(this, <any>arguments);
}
acquireLock(key: string, opts?: boolean | number | Partial<LMXClientLockOpts>): Promise<LMLockSuccessData> {
return this.acquire.apply(this, <any>arguments);
}
releaseLock(key: string, opts: Partial<LMXClientUnlockOpts>): Promise<LMUnlockSuccessData> {
return this.release.apply(this, <any>arguments);
}
run(fn: LMLockSuccessData) {
return new Promise((resolve, reject) => {
fn((err, val) => {
err ? reject(err) : resolve(val);
});
});
}
runUnlock(fn: LMLockSuccessData): Promise<any> {
return this.run.apply(this, arguments);
}
execUnlock(fn: LMLockSuccessData): Promise<any> {
return this.run.apply(this, arguments);
}
protected cleanUp(uuid: string) {
clearTimeout(this.timers[uuid]);
delete this.timers[uuid];
delete this.timeouts[uuid];
delete this.resolutions[uuid];
}
protected fireUnlockCallbackWithError(cb: LMClientUnlockCallBack, isNextTick: boolean, err: LMXClientUnlockException) {
const uuid = err.id;
const key = err.key; // unused
this.cleanUp(uuid);
this.emitter.emit('warning', err.message);
if(isNextTick){
process.nextTick(cb, err, <LMUnlockSuccessData>{}); // need to pass empty object in case the user uses an object destructure call
}
else{
cb(err, <LMUnlockSuccessData>{}); // need to pass empty object in case the user uses an object destructure call
}
}
protected fireLockCallbackWithError(cb: LMClientLockCallBack, isNextTick: boolean, err: LMXClientLockException) {
const uuid = err.id;
const key = err.key; // unused
this.cleanUp(uuid);
this.emitter.emit('warning', err.message);
if(isNextTick){
process.nextTick(cb, err, <LMLockSuccessData>{}); // need to pass empty object in case the user uses an object destructure call
}
else{
cb(err, <LMLockSuccessData>{}); // need to pass empty object in case the user uses an object destructure call
}
}
protected fireCallbackWithError(cb: EVCb<any>, isNextTick: boolean, err: LMXClientException) {
const uuid = err.id;
const key = err.key; // unused
this.cleanUp(uuid);
this.emitter.emit('warning', err.message);
if(isNextTick){
process.nextTick(cb, err, <any>{}); // need to pass empty object in case the user uses an object destructure call
}
else{
cb(err, <any>{}); // need to pass empty object in case the user uses an object destructure call
}
}
ls(cb: EVCb<any>): void;
ls(opts: any, cb?: EVCb<any>): void;
ls(opts: any, cb?: EVCb<any>) {
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
if (typeof cb !== 'function') {
throw new Error('Callback needs to be a function type.');
}
opts = opts || {};
const id = UUID.v4();
this.resolutions[id] = cb;
this.write({
keepLocksAfterDeath: opts.keepLocksAfterDeath,
uuid: id,
type: 'ls',
});
}
protected preParseLockOptsForPromises(
key: string,
opts: LMXClientLockOpts
): [string, LMXClientLockOpts] {
if (typeof opts === 'boolean') {
opts = {force: opts};
}
else if (typeof opts === 'number') {
opts = {ttl: opts};
}
opts = opts || {};
opts[PromiseSymbol] = true;
return [key, opts];
}
protected parseLockOpts(
key: string,
opts: LMXClientLockOpts | LMClientLockCallBack,
cb?: LMClientLockCallBack
): [string, LMXClientLockOpts, LMClientLockCallBack] {
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
else if (typeof opts === 'boolean') {
opts = {force: opts};
}
else if (typeof opts === 'number') {
opts = {ttl: opts};
}
assert.strict(typeof cb === 'function', 'Please use a callback as the last argument to the lock method.');
opts = opts || {} as LMXClientLockOpts;
return [key, opts, cb];
}
_simulateVersionMismatch() {
this.write({
type: 'simulate-version-mismatch',
});
}
_invokeBrokerSideEndCall() {
this.write({
type: 'end-connection-from-broker-for-testing-purposes'
});
}
_invokeBrokerSideDestroyCall() {
this.write({
type: 'destroy-connection-from-broker-for-testing-purposes'
});
}
_makeClientSideError() {
this.close();
}
// lock(key: string, cb: LMClientLockCallBack, z?: LMClientLockCallBack) : void;
lock(key: string, cb: LMClientLockCallBack): void;
lock(key: string, opts: Partial<LMXClientLockOpts>, cb: LMClientLockCallBack): void;
lock(key: string, opts: Partial<LMXClientLockOpts> | LMClientLockCallBack, cb?: LMClientLockCallBack): void {
try {
[key, opts, cb] = this.parseLockOpts(key, opts, cb);
}
catch (err) {
if (typeof cb === 'function') {
return process.nextTick(cb, err, {});
}
log.error('No callback was passed to accept the following error.',
'Please include a callback as the final argument to the client.lock() routine.');
throw err;
}
try {
assert.equal(typeof key, 'string', 'Key passed to lmx #lock needs to be a string.');
assert.strict(typeof cb === 'function', 'callback function must be passed to Client lock() method; use lockp() or acquire() for promise API.');
if ('max' in opts) {
assert.strict(Number.isInteger(opts['max']), '"max" options property must be a positive integer.');
assert.strict(opts['max'] > 0, '"max" options property must be a positive integer.');
}
if ('semaphore' in opts) {
assert.strict(Number.isInteger(opts['semaphore']), '"semaphore" options property must be a positive integer.');
assert.strict(opts['semaphore'] > 0, '"semaphore" options property must be a positive integer.');
}
if ('force' in opts) {
assert.equal(typeof opts.force, 'boolean', 'lmx usage error => ' +
'"force" option must be a boolean value. Coerce it on your side, for safety.');
}
if ('retry' in opts) {
assert.equal(typeof opts.retry, 'boolean', 'lmx usage error => ' +
'"retry" option must be a boolean value. Coerce it on your side, for safety.');
opts.__maxRetries = 0;
}
if ('maxRetries' in opts) {
assert.strict(Number.isInteger(opts.maxRetries), '"maxRetries" option must be an integer.');
assert.strict(opts.maxRetries >= 0 && opts.maxRetries <= 20,
'"maxRetries" option must be an integer between 0 and 20 inclusive.');
if ('__maxRetries' in opts) {
assert.strictEqual(opts.__maxRetries, opts.maxRetries, 'maxRetries values do not match.');
}
opts.__maxRetries = opts.maxRetries;
}
if ('maxRetry' in opts) {
assert.strict(Number.isInteger(opts.maxRetry), '"maxRetry" option must be an integer.');
assert.strict(opts.maxRetry >= 0 && opts.maxRetry <= 20,
'"maxRetry" option must be an integer between 0 and 20 inclusive.');
if ('__maxRetries' in opts) {
assert.strictEqual(opts.__maxRetries, opts.maxRetry, 'maxRetries values do not match.');
}
opts.__maxRetries = opts.maxRetry;
}
if ('retryMax' in opts) {
assert.strict(Number.isInteger(opts.retryMax), '"retryMax" option must be an integer.');
assert.strict(opts.retryMax >= 0 && opts.retryMax <= 20,
'"retryMax" option must be an integer between 0 and 20 inclusive.');
if ('__maxRetries' in opts) {
assert.strictEqual(opts.__maxRetries, opts.retryMax, 'maxRetries values do not match.');
}
opts.__maxRetries = opts.retryMax;
}
if (!('__maxRetries' in opts)) {
opts.__maxRetries = this.lockRetryMax;
}
assert.strict(Number.isInteger(opts.__maxRetries), '__maxRetries value must be an integer.');
if (opts['ttl']) {
assert.strict(Number.isInteger(opts.ttl),
'lmx usage error => Please pass an integer representing milliseconds as the value for "ttl".');
assert.strict(opts.ttl >= 3 && opts.ttl <= 800000,
'lmx usage error => "ttl" for a lock needs to be integer between 3 and 800000 millis.');
}
if (opts['ttl'] === null) {
// allow ttl to be stringified, null or Infinity both mean there is no ttl
opts['ttl'] = Infinity;
}
if (opts['lockRequestTimeout']) {
assert.strict(Number.isInteger(opts.lockRequestTimeout),
'lmx: Please pass an integer representing milliseconds as the value for "ttl".');
assert.strict(opts.lockRequestTimeout >= 20 && opts.lockRequestTimeout <= 800000,
'lmx: "ttl" for a lock needs to be integer between 3 and 800000 millis.');
}
opts.__retryCount = opts.__retryCount || 0;
if (opts.__retryCount > 0) {
assert.strict(opts._uuid, 'lmx internal error: no _uuid past to retry call.');
}
}
catch (err) {
if (typeof cb === 'function') {
return process.nextTick(cb, err, {});
}
log.error(
'No callback was passed to accept the following error.',
'Please include a callback as the final argument to the client.lock() routine.'
);
throw err;
}
if (process.domain) {
cb = process.domain.bind(cb as any);
}
this.lockInternal(key, opts, cb);
}
on() {
log.warn('warning:', 'use c.emitter.on() instead of c.on()');
return this.emitter.on.apply(this.emitter, arguments);
}
once() {
log.warn('warning:', 'use c.emitter.once() instead of c.once()');
return this.emitter.once.apply(this.emitter, arguments);
}
private lockInternal(key: string, opts: any, cb: LMClientLockCallBack) {
const uuid = opts._uuid = opts._uuid || UUID.v4();
const ttl = opts.ttl || this.ttl;
const lrt = opts.lockRequestTimeout || this.lockRequestTimeout;
const maxRetries = opts.__maxRetries;
const retryCount = opts.__retryCount;
const forceUnlock = opts.forceUnlock === true;
const isNextTick = !opts[PromiseSymbol] && retryCount < 1;
if (!this.isOpen) {
return this.fireLockCallbackWithError(cb, isNextTick, new LMXClientLockException(
key,
uuid,
LMXLockRequestError.ConnectionClosed,
`Connection was closed (and/or a client connection error occurred.)`
));
}
if (this.recovering) {
return this.fireLockCallbackWithError(cb, isNextTick, new LMXClientLockException(
key,
null,
LMXLockRequestError.ConnectionRecovering,
`Connection is recovering - reconection in progress.`
));
}
if (this.cannotContinue) {
return this.fireLockCallbackWithError(cb, isNextTick, new LMXClientLockException(
key,
null,
LMXLockRequestError.CannotContinue,
`'Client cannot make any lock requests, most likely due to version mismatch between client and broker.'`
));
}
if (retryCount > maxRetries) {
return this.fireLockCallbackWithError(cb, isNextTick, new LMXClientLockException(
key,
uuid,
LMXLockRequestError.MaxRetries,
`Maximum retries (${maxRetries}) attempted to acquire lock for key "${key}".`
));
}
const rwStatus = opts.rwStatus || null;
const max = opts.max;
let timedOut = false;
this.timers[uuid] = setTimeout(() => {
timedOut = true;
delete this.timers[uuid];
delete this.resolutions[uuid];
const currentRetryCount = opts.__retryCount;
const newRetryCount = ++opts.__retryCount;
if (!this.isOpen) {
this.timeouts[uuid] = true;
this.write({uuid, key, type: 'lock-client-error'});
return this.fireLockCallbackWithError(cb, false, new LMXClientLockException(
key,
uuid,
LMXLockRequestError.ConnectionClosed,
`Connection was closed (and/or a client connection error occurred.)`
));
}
// noRetry
if (newRetryCount >= maxRetries) {
this.timeouts[uuid] = true;
this.write({uuid, key, type: 'lock-client-timeout'});
return this.fireLockCallbackWithError(cb, false, new LMXClientLockException(
key,
uuid,
LMXLockRequestError.RequestTimeoutError,
`lmx client lock request timed out after ${lrt * opts.__retryCount} ms, ` +
`${currentRetryCount} retries attempted to acquire lock for key "${key}".`
));
}
this.emitter.emit('warning',
`retrying lock request for key '${key}', on ${this.getConnectionInterfaceStr()}, ` +
`retry attempt # ${newRetryCount}`,
);
// this has to be called synchronously,
// so we can get a new resolution callback on the books
this.lockInternal(key, opts, cb);
}, lrt);
this.resolutions[uuid] = (err, data) => {
if (timedOut) {
return;
}
if (err) {
return this.fireLockCallbackWithError(cb, false, new LMXClientLockException(
key,
uuid,
LMXLockRequestError.UnknownException,
'Unknown lmx client exception: ' + util.inspect(err)
));
}
if (!data) {
return this.fireLockCallbackWithError(cb, false, new LMXClientLockException(
key,
uuid,
LMXLockRequestError.InternalError,
'LMX inernal error: no data received from broker in client lock resolution callback.'
));
}
if (data.uuid !== uuid) {
return this.fireLockCallbackWithError(cb, false, new LMXClientLockException(
key,
uuid,
LMXLockRequestError.InternalError,
`Internal lmx error, mismatch in uuids => '${data.uuid}', -> '${uuid}'.`
));
}
if (String(key) !== String(data.key)) {
return this.fireLockCallbackWithError(cb, false, new LMXClientLockException(
key,
uuid,
LMXLockRequestError.InternalError,
`lmx internal error: bad key, [1] => '${key}', [2] => '${data.key}'.`
));
}
if (data.error) {
return this.fireLockCallbackWithError(cb, false, new LMXClientLockException(
key,
uuid,
LMXLockRequestError.GenericLockError,
data.error,
));
}
if (data.acquired === true) {
// lock was acquired for the given key, yippee
this.cleanUp(uuid);
this.write({uuid, key, type: 'lock-received'}); // we let the broker know that we received the lock
const boundUnlock = this.unlock.bind(this, key, {_uuid: uuid, rwStatus, force: forceUnlock});
boundUnlock.acquired = true;
boundUnlock.readersCount = Number.isInteger(data.readersCount) ? data.readersCount : null;
boundUnlock.key = key;
boundUnlock.unlock = boundUnlock.release = boundUnlock;
boundUnlock.lockUuid = boundUnlock.id = uuid;
return cb(null, boundUnlock);
}
if (data.reelection === true) {
this.cleanUp(uuid);
return this.lockInternal(key, opts, cb);
}
if (data.acquired === false) {
// if acquired is false, we will:
// 1. be waiting for acquired to be true
// 2. if the timeout occurs before 1, we will make a new request and put our request at the front of the queue
// however, if wait is false, we will do neither 1 or 2
if (opts.wait === false) {
// when wait is false, user only wants to try once,
// and doesn't even want to wait until the timeout elapses.
// such that even if wait === false and maxRetries === 1,
// we still wouldn't wait for the timeout to elapse
this.giveups[uuid] = true;
this.fireLockCallbackWithError(cb, false, new LMXClientLockException(
key,
uuid,
LMXLockRequestError.WaitOptionSetToFalse,
'Could not acquire lock on first attempt, and "wait" option is false.'
));
}
return;
}
this.fireLockCallbackWithError(cb, false, new LMXClientLockException(
key,
uuid,
LMXLockRequestError.InternalError,
`Implementation error, please report, fallthrough in condition [1]`
));
};
{
let keepLocksAfterDeath = Boolean(opts.keepLocksAfterDeath || opts.keepLocksOnExit);
this.write({
keepLocksAfterDeath,
retryCount,
uuid: uuid,
key: key,
type: 'lock',
ttl: ttl,
rwStatus,
max
});
}
}
noop(err?: any) {
// this is a no-operation, obviously
// no ref to this, so can't use "this" here
err && log.error(err);
}
getPort() {
return this.port;
}
getHost() {
return this.host;
}
protected preParseUnlockOptsForPromise(
key: string,
opts?: string | boolean | LMXClientUnlockOpts,
): [string, LMXClientUnlockOpts] {
if (typeof opts === 'boolean') {
opts = {force: opts};
}
else if (typeof opts === 'string') {
opts = {_uuid: opts};
}
opts = opts || {} ;
opts[PromiseSymbol] = true;
return [key, opts as any];
}
protected parseUnlockOpts(
key: string,
opts?: LMXClientUnlockOpts | LMClientUnlockCallBack,
cb?: LMClientUnlockCallBack
): [string, LMXClientUnlockOpts, LMClientUnlockCallBack] {
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
else if (typeof opts === 'boolean') {
opts = {force: opts};
}
else if (typeof opts === 'string') {
opts = {_uuid: opts};
}
opts = opts || {};
if (cb) {
assert.strict(typeof cb === 'function', 'Please use a callback as the last argument to the client unlock method.');
}
else {
cb = this.noop;
}
return [key, opts, cb];
}
unlock(key: string): void;
unlock(key: string, opts: LMXClientUnlockOpts): void;
unlock(key: string, opts: LMXClientUnlockOpts, cb: LMClientUnlockCallBack): void;
unlock(key: string, opts?: LMXClientUnlockOpts | LMClientUnlockCallBack, cb?: LMClientUnlockCallBack) {
try {
[key, opts, cb] = this.parseUnlockOpts(key, opts, cb);
}
catch (err) {
if (typeof cb === 'function') {
return process.nextTick(cb, err, {});
}
log.error('No callback was passed to accept the following error.');
throw err;
}
if (opts.id) {
opts._uuid = opts.id;
}
if (cb && cb !== this.noop) {
if (process.domain) {
cb = process.domain.bind(cb as any);
}
}
cb = cb || this.noop;
try {
assert.equal(typeof key, 'string', 'Key passed to lmx #unlock needs to be a string.');
if (opts['force']) {
assert.equal(typeof opts.force, 'boolean', 'lmx usage error => ' +
'"force" option must be a boolean value. Coerce it on your side, for safety.');
}
if (opts['unlockRequestTimeout']) {
assert.strict(Number.isInteger(opts.unlockRequestTimeout),
'lmx: Please pass an integer representing milliseconds as the value for "ttl".');
assert.strict(opts.unlockRequestTimeout >= 20 && opts.unlockRequestTimeout <= 800000,
'lmx: "ttl" for a lock needs to be integer between 3 and 800000 millis.');
}
}
catch (err) {
return process.nextTick(cb, err, {});
}
const uuid = UUID.v4();
const rwStatus = opts.rwStatus || null;
const urt = opts.unlockRequestTimeout || this.unlockRequestTimeout;
let timedOut = false;
this.timers[uuid] = setTimeout(() => {
timedOut = true;
this.timeouts[uuid] = true;
this.fireUnlockCallbackWithError(cb, false, new LMXClientUnlockException(
key, uuid,
LMXUnlockRequestError.BadOrMismatchedId,
` LMX Unlock request to unlock key => "${key}" timed out.`
));
}, urt);
this.resolutions[uuid] = (err, data) => {
delete this.timeouts[uuid];
clearTimeout(this.timers[uuid]);
if (timedOut) {
return;
}
if (err) {
return this.fireUnlockCallbackWithError(cb, false, new LMXClientUnlockException(
key,
uuid,
LMXUnlockRequestError.InternalError,
'LMX unknown/internal error: ' + util.inspect(err, {breakLength: Infinity})
));
}
if (!data) {
return this.fireUnlockCallbackWithError(cb, false, new LMXClientUnlockException(
key,
uuid,
LMXUnlockRequestError.InternalError,
`lmx internal error: missing data in unlock resolution.`,
));
}
if (String(key) !== String(data.key)) {
return this.fireUnlockCallbackWithError(cb, false, new LMXClientUnlockException(
key,
uuid,
LMXUnlockRequestError.InternalError,
`lmx implementation error, bad key => first key: ${key}, second key: ${data.key}`,
));
}
if (data.error) {
return this.fireUnlockCallbackWithError(cb, false, new LMXClientUnlockException(
key,
uuid,
LMXUnlockRequestError.GeneralUnlockError,
'lmx request error: ' + data.error
));
}
if (data.unlocked === true) {
this.cleanUp(uuid);
// this.write({
// uuid: uuid,
// key: key,
// type: 'unlock-received'
// });
return cb(null, {id: uuid, key, unlocked: true});
}
if (data.unlocked === false) {
// data.error will most likely be defined as well
// so this may never get hit
return this.fireUnlockCallbackWithError(cb, false, new LMXClientUnlockException(
key,
uuid,
LMXUnlockRequestError.GeneralUnlockError,
data
));
}
this.fireUnlockCallbackWithError(cb, false, new LMXClientUnlockException(
key,
uuid,
LMXUnlockRequestError.GeneralUnlockError,
'lmx internal/implementation error: fallthrough in unlock resolution routine.'
));
};
let force: boolean = (opts.__retryCount > 0) || Boolean(opts.force);
this.write({
_uuid: opts._uuid,
uuid: uuid,
key: key,
rwStatus,
force: force,
type: 'unlock'
});
}
}
// aliases
export default Client;
export const LMXClient = Client;
export const LvMtxClient = Client; | the_stack |
import * as React from "react"
import { computed, action, observable } from "mobx"
import { observer } from "mobx-react"
import { uniq, makeSafeForCSS } from "../../clientUtils/Util"
import { Bounds } from "../../clientUtils/Bounds"
import {
VerticalAxisComponent,
AxisTickMarks,
VerticalAxisGridLines,
} from "../axis/AxisViews"
import { NoDataModal } from "../noDataModal/NoDataModal"
import { Text } from "../text/Text"
import {
VerticalColorLegend,
VerticalColorLegendManager,
LegendItem,
} from "../verticalColorLegend/VerticalColorLegend"
import { Tooltip } from "../tooltip/Tooltip"
import { BASE_FONT_SIZE } from "../core/GrapherConstants"
import { ColorScaleManager } from "../color/ColorScale"
import {
AbstactStackedChart,
AbstactStackedChartProps,
} from "./AbstractStackedChart"
import { StackedPoint, StackedSeries } from "./StackedConstants"
import { VerticalAxis } from "../axis/Axis"
import { ColorSchemeName } from "../color/ColorConstants"
import { stackSeries, withMissingValuesAsZeroes } from "./StackedUtils"
import { makeClipPath } from "../chart/ChartUtils"
import { Time } from "../../clientUtils/owidTypes"
import { ColorScaleConfigDefaults } from "../color/ColorScaleConfig"
interface StackedBarSegmentProps extends React.SVGAttributes<SVGGElement> {
bar: StackedPoint<Time>
series: StackedSeries<Time>
color: string
opacity: number
yAxis: VerticalAxis
xOffset: number
barWidth: number
onBarMouseOver: (
bar: StackedPoint<Time>,
series: StackedSeries<Time>
) => void
onBarMouseLeave: () => void
}
@observer
class StackedBarSegment extends React.Component<StackedBarSegmentProps> {
base: React.RefObject<SVGRectElement> = React.createRef()
@observable mouseOver: boolean = false
@computed get yPos(): number {
const { bar, yAxis } = this.props
return yAxis.place(bar.value + bar.valueOffset)
}
@computed get barHeight(): number {
const { bar, yAxis } = this.props
return yAxis.place(bar.valueOffset) - this.yPos
}
@computed get trueOpacity(): number {
return this.mouseOver ? 1 : this.props.opacity
}
@action.bound onBarMouseOver(): void {
this.mouseOver = true
this.props.onBarMouseOver(this.props.bar, this.props.series)
}
@action.bound onBarMouseLeave(): void {
this.mouseOver = false
this.props.onBarMouseLeave()
}
render(): JSX.Element {
const { color, xOffset, barWidth } = this.props
const { yPos, barHeight, trueOpacity } = this
return (
<rect
ref={this.base}
x={xOffset}
y={yPos}
width={barWidth}
height={barHeight}
fill={color}
opacity={trueOpacity}
onMouseOver={this.onBarMouseOver}
onMouseLeave={this.onBarMouseLeave}
/>
)
}
}
@observer
export class StackedBarChart
extends AbstactStackedChart<Time>
implements VerticalColorLegendManager, ColorScaleManager
{
readonly minBarSpacing = 4
constructor(props: AbstactStackedChartProps) {
super(props)
}
// currently hovered legend color
@observable hoverColor?: string
// current hovered individual bar
@observable hoverBar?: StackedPoint<Time>
@observable hoverSeries?: StackedSeries<Time>
@computed private get baseFontSize(): number {
return this.manager.baseFontSize ?? BASE_FONT_SIZE
}
@computed get tickFontSize(): number {
return 0.9 * this.baseFontSize
}
@computed get barWidth(): number {
const { dualAxis } = this
return (0.8 * dualAxis.innerBounds.width) / this.xValues.length
}
@computed get barSpacing(): number {
return (
this.dualAxis.innerBounds.width / this.xValues.length -
this.barWidth
)
}
@computed get barFontSize(): number {
return 0.75 * this.baseFontSize
}
@computed protected get paddingForLegend(): number {
return this.sidebarWidth + 20
}
// All currently hovered group keys, combining the legend and the main UI
@computed get hoverKeys(): string[] {
const { hoverColor } = this
const hoverKeys =
hoverColor === undefined
? []
: uniq(
this.series
.filter((g) => g.color === hoverColor)
.map((g) => g.seriesName)
)
return hoverKeys
}
@computed get activeColors(): string[] {
const { hoverKeys } = this
const activeKeys = hoverKeys.length > 0 ? hoverKeys : []
if (!activeKeys.length)
// No hover means they're all active by default
return uniq(this.series.map((g) => g.color))
return uniq(
this.series
.filter((g) => activeKeys.indexOf(g.seriesName) !== -1)
.map((g) => g.color)
)
}
@computed get legendItems(): LegendItem[] {
return this.series
.map((series) => {
return {
label: series.seriesName,
color: series.color,
}
})
.reverse() // Vertical legend orders things in the opposite direction we want
}
@computed get maxLegendWidth(): number {
return this.sidebarMaxWidth
}
@computed get sidebarMaxWidth(): number {
return this.bounds.width / 5
}
@computed get sidebarMinWidth(): number {
return 100
}
@computed get sidebarWidth(): number {
if (this.manager.hideLegend) return 0
const { sidebarMinWidth, sidebarMaxWidth, legendDimensions } = this
return Math.max(
Math.min(legendDimensions.width, sidebarMaxWidth),
sidebarMinWidth
)
}
@computed private get legendDimensions(): VerticalColorLegend {
return new VerticalColorLegend({ manager: this })
}
@computed get tooltip(): JSX.Element | undefined {
const {
hoverBar,
mapXValueToOffset,
barWidth,
dualAxis,
yColumns,
inputTable,
hoverSeries,
} = this
if (hoverBar === undefined) return
const xPos = mapXValueToOffset.get(hoverBar.position)
if (xPos === undefined) return
const yPos = dualAxis.verticalAxis.place(
hoverBar.valueOffset + hoverBar.value
)
const yColumn = yColumns[0] // we can just use the first column for formatting, b/c we assume all columns have same type
return (
<Tooltip
tooltipManager={this.props.manager}
x={xPos + barWidth}
y={yPos}
style={{ textAlign: "center" }}
>
<h3
style={{
padding: "0.3em 0.9em",
margin: 0,
backgroundColor: "#fcfcfc",
borderBottom: "1px solid #ebebeb",
fontWeight: "normal",
fontSize: "1em",
}}
>
{hoverSeries?.seriesName}
</h3>
<p
style={{
margin: 0,
padding: "0.3em 0.9em",
fontSize: "0.8em",
}}
>
<span>{yColumn.formatValueLong(hoverBar.value)}</span>
<br />
in
<br />
<span>
{inputTable.timeColumnFormatFunction(hoverBar.position)}
</span>
</p>
</Tooltip>
)
}
@computed get mapXValueToOffset(): Map<number, number> {
const { dualAxis, barWidth, barSpacing } = this
const xValueToOffset = new Map<number, number>()
let xOffset = dualAxis.innerBounds.left + barSpacing
for (let i = 0; i < this.xValues.length; i++) {
xValueToOffset.set(this.xValues[i], xOffset)
xOffset += barWidth + barSpacing
}
return xValueToOffset
}
// Place ticks centered beneath the bars, before doing overlap detection
@computed private get tickPlacements() {
const { mapXValueToOffset, barWidth, dualAxis } = this
const { xValues } = this
const { horizontalAxis } = dualAxis
return xValues.map((x) => {
const text = horizontalAxis.formatTick(x)
const xPos = mapXValueToOffset.get(x) as number
const bounds = Bounds.forText(text, { fontSize: this.tickFontSize })
return {
text,
bounds: bounds.set({
x: xPos + barWidth / 2 - bounds.width / 2,
y: dualAxis.innerBounds.bottom + 5,
}),
isHidden: false,
}
})
}
@computed get ticks() {
const { tickPlacements } = this
for (let i = 0; i < tickPlacements.length; i++) {
for (let j = 1; j < tickPlacements.length; j++) {
const t1 = tickPlacements[i],
t2 = tickPlacements[j]
if (t1 === t2 || t1.isHidden || t2.isHidden) continue
if (t1.bounds.intersects(t2.bounds.padWidth(-5))) {
if (i === 0) t2.isHidden = true
else if (j === tickPlacements.length - 1) t1.isHidden = true
else t2.isHidden = true
}
}
}
return tickPlacements.filter((t) => !t.isHidden)
}
@action.bound onLegendMouseOver(color: string): void {
this.hoverColor = color
}
@action.bound onLegendMouseLeave(): void {
this.hoverColor = undefined
}
@action.bound onLegendClick(): void {}
@action.bound onBarMouseOver(
bar: StackedPoint<Time>,
series: StackedSeries<Time>
): void {
this.hoverBar = bar
this.hoverSeries = series
}
@action.bound onBarMouseLeave(): void {
this.hoverBar = undefined
}
render(): JSX.Element {
if (this.failMessage)
return (
<NoDataModal
manager={this.manager}
bounds={this.bounds}
message={this.failMessage}
/>
)
const {
dualAxis,
renderUid,
bounds,
tooltip,
barWidth,
mapXValueToOffset,
ticks,
} = this
const { series } = this
const { innerBounds, verticalAxis } = dualAxis
const textColor = "#666"
const clipPath = makeClipPath(renderUid, innerBounds)
return (
<g
className="StackedBarChart"
width={bounds.width}
height={bounds.height}
>
{clipPath.element}
<rect
x={bounds.left}
y={bounds.top}
width={bounds.width}
height={bounds.height}
opacity={0}
fill="rgba(255,255,255,0)"
/>
<VerticalAxisComponent
bounds={bounds}
verticalAxis={verticalAxis}
/>
<VerticalAxisGridLines
verticalAxis={verticalAxis}
bounds={innerBounds}
/>
<AxisTickMarks
tickMarkTopPosition={innerBounds.bottom}
tickMarkXPositions={ticks.map(
(tick) => tick.bounds.centerX
)}
color={textColor}
/>
<g>
{ticks.map((tick, i) => {
return (
<Text
key={i}
x={tick.bounds.x}
y={tick.bounds.y}
fill={textColor}
fontSize={this.tickFontSize}
>
{tick.text}
</Text>
)
})}
</g>
<g clipPath={clipPath.id}>
{series.map((series, index) => {
const isLegendHovered = this.hoverKeys.includes(
series.seriesName
)
const opacity =
isLegendHovered || this.hoverKeys.length === 0
? 0.8
: 0.2
return (
<g
key={index}
className={
makeSafeForCSS(series.seriesName) +
"-segments"
}
>
{series.points.map((bar, index) => {
const xPos = mapXValueToOffset.get(
bar.position
) as number
const barOpacity =
bar === this.hoverBar ? 1 : opacity
return (
<StackedBarSegment
key={index}
bar={bar}
color={series.color}
xOffset={xPos}
opacity={barOpacity}
yAxis={verticalAxis}
series={series}
onBarMouseOver={this.onBarMouseOver}
onBarMouseLeave={
this.onBarMouseLeave
}
barWidth={barWidth}
/>
)
})}
</g>
)
})}
</g>
{!this.manager.hideLegend && (
<VerticalColorLegend manager={this} />
)}
{tooltip}
</g>
)
}
@computed get legendY(): number {
return this.bounds.top
}
@computed get legendX(): number {
return this.bounds.right - this.sidebarWidth
}
@computed private get xValues(): number[] {
return uniq(this.allStackedPoints.map((bar) => bar.position))
}
@computed get colorScaleConfig(): ColorScaleConfigDefaults | undefined {
return this.manager.colorScale
}
defaultBaseColorScheme = ColorSchemeName.stackedAreaDefault
@computed get series(): readonly StackedSeries<number>[] {
return stackSeries(withMissingValuesAsZeroes(this.unstackedSeries))
}
} | the_stack |
import { KubernetesObject } from 'kpt-functions';
import * as apisMetaV1 from './io.k8s.apimachinery.pkg.apis.meta.v1';
// LocalSubjectAccessReview checks whether or not a user or group can perform an action in a given namespace. Having a namespace scoped resource makes it much easier to grant namespace scoped policy that includes permissions checking.
export class LocalSubjectAccessReview implements KubernetesObject {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
public metadata: apisMetaV1.ObjectMeta;
// Spec holds information about the request being evaluated. spec.namespace must be equal to the namespace you made the request against. If empty, it is defaulted.
public spec: SubjectAccessReviewSpec;
// Status is filled in by the server and indicates whether the request is allowed or not
public status?: SubjectAccessReviewStatus;
constructor(desc: LocalSubjectAccessReview.Interface) {
this.apiVersion = LocalSubjectAccessReview.apiVersion;
this.kind = LocalSubjectAccessReview.kind;
this.metadata = desc.metadata;
this.spec = desc.spec;
this.status = desc.status;
}
}
export function isLocalSubjectAccessReview(
o: any
): o is LocalSubjectAccessReview {
return (
o &&
o.apiVersion === LocalSubjectAccessReview.apiVersion &&
o.kind === LocalSubjectAccessReview.kind
);
}
export namespace LocalSubjectAccessReview {
export const apiVersion = 'authorization.k8s.io/v1beta1';
export const group = 'authorization.k8s.io';
export const version = 'v1beta1';
export const kind = 'LocalSubjectAccessReview';
// LocalSubjectAccessReview checks whether or not a user or group can perform an action in a given namespace. Having a namespace scoped resource makes it much easier to grant namespace scoped policy that includes permissions checking.
export interface Interface {
metadata: apisMetaV1.ObjectMeta;
// Spec holds information about the request being evaluated. spec.namespace must be equal to the namespace you made the request against. If empty, it is defaulted.
spec: SubjectAccessReviewSpec;
// Status is filled in by the server and indicates whether the request is allowed or not
status?: SubjectAccessReviewStatus;
}
}
// NonResourceAttributes includes the authorization attributes available for non-resource requests to the Authorizer interface
export class NonResourceAttributes {
// Path is the URL path of the request
public path?: string;
// Verb is the standard HTTP verb
public verb?: string;
}
// NonResourceRule holds information that describes a rule for the non-resource
export class NonResourceRule {
// NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path. "*" means all.
public nonResourceURLs?: string[];
// Verb is a list of kubernetes non-resource API verbs, like: get, post, put, delete, patch, head, options. "*" means all.
public verbs: string[];
constructor(desc: NonResourceRule) {
this.nonResourceURLs = desc.nonResourceURLs;
this.verbs = desc.verbs;
}
}
// ResourceAttributes includes the authorization attributes available for resource requests to the Authorizer interface
export class ResourceAttributes {
// Group is the API Group of the Resource. "*" means all.
public group?: string;
// Name is the name of the resource being requested for a "get" or deleted for a "delete". "" (empty) means all.
public name?: string;
// Namespace is the namespace of the action being requested. Currently, there is no distinction between no namespace and all namespaces "" (empty) is defaulted for LocalSubjectAccessReviews "" (empty) is empty for cluster-scoped resources "" (empty) means "all" for namespace scoped resources from a SubjectAccessReview or SelfSubjectAccessReview
public namespace?: string;
// Resource is one of the existing resource types. "*" means all.
public resource?: string;
// Subresource is one of the existing resource types. "" means none.
public subresource?: string;
// Verb is a kubernetes resource API verb, like: get, list, watch, create, update, delete, proxy. "*" means all.
public verb?: string;
// Version is the API Version of the Resource. "*" means all.
public version?: string;
}
// ResourceRule is the list of actions the subject is allowed to perform on resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete.
export class ResourceRule {
// APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed. "*" means all.
public apiGroups?: string[];
// ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. "*" means all.
public resourceNames?: string[];
// Resources is a list of resources this rule applies to. "*" means all in the specified apiGroups.
// "*/foo" represents the subresource 'foo' for all resources in the specified apiGroups.
public resources?: string[];
// Verb is a list of kubernetes resource API verbs, like: get, list, watch, create, update, delete, proxy. "*" means all.
public verbs: string[];
constructor(desc: ResourceRule) {
this.apiGroups = desc.apiGroups;
this.resourceNames = desc.resourceNames;
this.resources = desc.resources;
this.verbs = desc.verbs;
}
}
// SelfSubjectAccessReview checks whether or the current user can perform an action. Not filling in a spec.namespace means "in all namespaces". Self is a special case, because users should always be able to check whether they can perform an action
export class SelfSubjectAccessReview implements KubernetesObject {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
public metadata: apisMetaV1.ObjectMeta;
// Spec holds information about the request being evaluated. user and groups must be empty
public spec: SelfSubjectAccessReviewSpec;
// Status is filled in by the server and indicates whether the request is allowed or not
public status?: SubjectAccessReviewStatus;
constructor(desc: SelfSubjectAccessReview.Interface) {
this.apiVersion = SelfSubjectAccessReview.apiVersion;
this.kind = SelfSubjectAccessReview.kind;
this.metadata = desc.metadata;
this.spec = desc.spec;
this.status = desc.status;
}
}
export function isSelfSubjectAccessReview(
o: any
): o is SelfSubjectAccessReview {
return (
o &&
o.apiVersion === SelfSubjectAccessReview.apiVersion &&
o.kind === SelfSubjectAccessReview.kind
);
}
export namespace SelfSubjectAccessReview {
export const apiVersion = 'authorization.k8s.io/v1beta1';
export const group = 'authorization.k8s.io';
export const version = 'v1beta1';
export const kind = 'SelfSubjectAccessReview';
// SelfSubjectAccessReview checks whether or the current user can perform an action. Not filling in a spec.namespace means "in all namespaces". Self is a special case, because users should always be able to check whether they can perform an action
export interface Interface {
metadata: apisMetaV1.ObjectMeta;
// Spec holds information about the request being evaluated. user and groups must be empty
spec: SelfSubjectAccessReviewSpec;
// Status is filled in by the server and indicates whether the request is allowed or not
status?: SubjectAccessReviewStatus;
}
}
// SelfSubjectAccessReviewSpec is a description of the access request. Exactly one of ResourceAuthorizationAttributes and NonResourceAuthorizationAttributes must be set
export class SelfSubjectAccessReviewSpec {
// NonResourceAttributes describes information for a non-resource access request
public nonResourceAttributes?: NonResourceAttributes;
// ResourceAuthorizationAttributes describes information for a resource access request
public resourceAttributes?: ResourceAttributes;
}
// SelfSubjectRulesReview enumerates the set of actions the current user can perform within a namespace. The returned list of actions may be incomplete depending on the server's authorization mode, and any errors experienced during the evaluation. SelfSubjectRulesReview should be used by UIs to show/hide actions, or to quickly let an end user reason about their permissions. It should NOT Be used by external systems to drive authorization decisions as this raises confused deputy, cache lifetime/revocation, and correctness concerns. SubjectAccessReview, and LocalAccessReview are the correct way to defer authorization decisions to the API server.
export class SelfSubjectRulesReview implements KubernetesObject {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
public metadata: apisMetaV1.ObjectMeta;
// Spec holds information about the request being evaluated.
public spec: SelfSubjectRulesReviewSpec;
// Status is filled in by the server and indicates the set of actions a user can perform.
public status?: SubjectRulesReviewStatus;
constructor(desc: SelfSubjectRulesReview.Interface) {
this.apiVersion = SelfSubjectRulesReview.apiVersion;
this.kind = SelfSubjectRulesReview.kind;
this.metadata = desc.metadata;
this.spec = desc.spec;
this.status = desc.status;
}
}
export function isSelfSubjectRulesReview(o: any): o is SelfSubjectRulesReview {
return (
o &&
o.apiVersion === SelfSubjectRulesReview.apiVersion &&
o.kind === SelfSubjectRulesReview.kind
);
}
export namespace SelfSubjectRulesReview {
export const apiVersion = 'authorization.k8s.io/v1beta1';
export const group = 'authorization.k8s.io';
export const version = 'v1beta1';
export const kind = 'SelfSubjectRulesReview';
// SelfSubjectRulesReview enumerates the set of actions the current user can perform within a namespace. The returned list of actions may be incomplete depending on the server's authorization mode, and any errors experienced during the evaluation. SelfSubjectRulesReview should be used by UIs to show/hide actions, or to quickly let an end user reason about their permissions. It should NOT Be used by external systems to drive authorization decisions as this raises confused deputy, cache lifetime/revocation, and correctness concerns. SubjectAccessReview, and LocalAccessReview are the correct way to defer authorization decisions to the API server.
export interface Interface {
metadata: apisMetaV1.ObjectMeta;
// Spec holds information about the request being evaluated.
spec: SelfSubjectRulesReviewSpec;
// Status is filled in by the server and indicates the set of actions a user can perform.
status?: SubjectRulesReviewStatus;
}
}
export class SelfSubjectRulesReviewSpec {
// Namespace to evaluate rules for. Required.
public namespace?: string;
}
// SubjectAccessReview checks whether or not a user or group can perform an action.
export class SubjectAccessReview implements KubernetesObject {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
public metadata: apisMetaV1.ObjectMeta;
// Spec holds information about the request being evaluated
public spec: SubjectAccessReviewSpec;
// Status is filled in by the server and indicates whether the request is allowed or not
public status?: SubjectAccessReviewStatus;
constructor(desc: SubjectAccessReview.Interface) {
this.apiVersion = SubjectAccessReview.apiVersion;
this.kind = SubjectAccessReview.kind;
this.metadata = desc.metadata;
this.spec = desc.spec;
this.status = desc.status;
}
}
export function isSubjectAccessReview(o: any): o is SubjectAccessReview {
return (
o &&
o.apiVersion === SubjectAccessReview.apiVersion &&
o.kind === SubjectAccessReview.kind
);
}
export namespace SubjectAccessReview {
export const apiVersion = 'authorization.k8s.io/v1beta1';
export const group = 'authorization.k8s.io';
export const version = 'v1beta1';
export const kind = 'SubjectAccessReview';
// SubjectAccessReview checks whether or not a user or group can perform an action.
export interface Interface {
metadata: apisMetaV1.ObjectMeta;
// Spec holds information about the request being evaluated
spec: SubjectAccessReviewSpec;
// Status is filled in by the server and indicates whether the request is allowed or not
status?: SubjectAccessReviewStatus;
}
}
// SubjectAccessReviewSpec is a description of the access request. Exactly one of ResourceAuthorizationAttributes and NonResourceAuthorizationAttributes must be set
export class SubjectAccessReviewSpec {
// Extra corresponds to the user.Info.GetExtra() method from the authenticator. Since that is input to the authorizer it needs a reflection here.
public extra?: { [key: string]: string[] };
// Groups is the groups you're testing for.
public group?: string[];
// NonResourceAttributes describes information for a non-resource access request
public nonResourceAttributes?: NonResourceAttributes;
// ResourceAuthorizationAttributes describes information for a resource access request
public resourceAttributes?: ResourceAttributes;
// UID information about the requesting user.
public uid?: string;
// User is the user you're testing for. If you specify "User" but not "Group", then is it interpreted as "What if User were not a member of any groups
public user?: string;
}
// SubjectAccessReviewStatus
export class SubjectAccessReviewStatus {
// Allowed is required. True if the action would be allowed, false otherwise.
public allowed: boolean;
// Denied is optional. True if the action would be denied, otherwise false. If both allowed is false and denied is false, then the authorizer has no opinion on whether to authorize the action. Denied may not be true if Allowed is true.
public denied?: boolean;
// EvaluationError is an indication that some error occurred during the authorization check. It is entirely possible to get an error and be able to continue determine authorization status in spite of it. For instance, RBAC can be missing a role, but enough roles are still present and bound to reason about the request.
public evaluationError?: string;
// Reason is optional. It indicates why a request was allowed or denied.
public reason?: string;
constructor(desc: SubjectAccessReviewStatus) {
this.allowed = desc.allowed;
this.denied = desc.denied;
this.evaluationError = desc.evaluationError;
this.reason = desc.reason;
}
}
// SubjectRulesReviewStatus contains the result of a rules check. This check can be incomplete depending on the set of authorizers the server is configured with and any errors experienced during evaluation. Because authorization rules are additive, if a rule appears in a list it's safe to assume the subject has that permission, even if that list is incomplete.
export class SubjectRulesReviewStatus {
// EvaluationError can appear in combination with Rules. It indicates an error occurred during rule evaluation, such as an authorizer that doesn't support rule evaluation, and that ResourceRules and/or NonResourceRules may be incomplete.
public evaluationError?: string;
// Incomplete is true when the rules returned by this call are incomplete. This is most commonly encountered when an authorizer, such as an external authorizer, doesn't support rules evaluation.
public incomplete: boolean;
// NonResourceRules is the list of actions the subject is allowed to perform on non-resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete.
public nonResourceRules: NonResourceRule[];
// ResourceRules is the list of actions the subject is allowed to perform on resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete.
public resourceRules: ResourceRule[];
constructor(desc: SubjectRulesReviewStatus) {
this.evaluationError = desc.evaluationError;
this.incomplete = desc.incomplete;
this.nonResourceRules = desc.nonResourceRules;
this.resourceRules = desc.resourceRules;
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.