text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
'use strict';
import * as fs from 'fs';
import * as path from 'path';
import * as component from '../../../../common/component';
import { FrameworkControllerConfig, FrameworkControllerTaskRoleConfig, toMegaBytes } from '../../../../common/experimentConfig';
import { ExperimentStartupInfo } from '../../../../common/experimentStartupInfo';
import { EnvironmentInformation } from '../../environment';
import { KubernetesEnvironmentService } from './kubernetesEnvironmentService';
import { FrameworkControllerClientFactory } from '../../../kubernetes/frameworkcontroller/frameworkcontrollerApiClient';
import { FrameworkControllerClusterConfigAzure, FrameworkControllerJobStatus, FrameworkControllerTrialConfigTemplate,
FrameworkControllerJobCompleteStatus } from '../../../kubernetes/frameworkcontroller/frameworkcontrollerConfig';
import { KeyVaultConfig, AzureStorage } from '../../../kubernetes/kubernetesConfig';
@component.Singleton
export class FrameworkControllerEnvironmentService extends KubernetesEnvironmentService {
private config: FrameworkControllerConfig;
private createStoragePromise?: Promise<void>;
private readonly fcContainerPortMap: Map<string, number> = new Map<string, number>(); // store frameworkcontroller container port
constructor(config: FrameworkControllerConfig, info: ExperimentStartupInfo) {
super(config, info);
this.experimentId = info.experimentId;
this.config = config;
// Create kubernetesCRDClient
this.kubernetesCRDClient = FrameworkControllerClientFactory.createClient(this.config.namespace);
this.genericK8sClient.setNamespace = this.config.namespace ?? "default"
// Create storage
if (this.config.storage.storageType === 'azureStorage') {
if (this.config.storage.azureShare === undefined ||
this.config.storage.azureAccount === undefined ||
this.config.storage.keyVaultName === undefined ||
this.config.storage.keyVaultKey === undefined) {
throw new Error("Azure storage configuration error!");
}
this.azureStorageAccountName = this.config.storage.azureAccount;
this.azureStorageShare = this.config.storage.azureShare;
this.createStoragePromise = this.createAzureStorage(this.config.storage.keyVaultName, this.config.storage.keyVaultKey);
} else if (this.config.storage.storageType === 'nfs') {
if (this.config.storage.server === undefined ||
this.config.storage.path === undefined) {
throw new Error("NFS storage configuration error!");
}
this.createStoragePromise = this.createNFSStorage(this.config.storage.server, this.config.storage.path);
}
}
public get environmentMaintenceLoopInterval(): number {
return 5000;
}
public get hasStorageService(): boolean {
return false;
}
public get getName(): string {
return 'frameworkcontroller';
}
public async startEnvironment(environment: EnvironmentInformation): Promise<void> {
if (this.kubernetesCRDClient === undefined) {
throw new Error("kubernetesCRDClient not initialized!");
}
if (this.createStoragePromise) {
await this.createStoragePromise;
}
let configTaskRoles: any = undefined;
configTaskRoles = this.config.taskRoles;
//Generate the port used for taskRole
this.generateContainerPort(configTaskRoles);
const expFolder = `${this.CONTAINER_MOUNT_PATH}/nni/${this.experimentId}`;
environment.command = `cd ${expFolder} && ${environment.command} \
1>${expFolder}/envs/${environment.id}/trialrunner_stdout 2>${expFolder}/envs/${environment.id}/trialrunner_stderr`;
environment.maxTrialNumberPerGpu = this.config.maxTrialNumberPerGpu;
const frameworkcontrollerJobName: string = `nniexp${this.experimentId}env${environment.id}`.toLowerCase();
const command = this.generateCommandScript(this.config.taskRoles, environment.command);
await fs.promises.writeFile(path.join(this.environmentLocalTempFolder, "run.sh"), command, { encoding: 'utf8' });
//upload script files to sotrage
const trialJobOutputUrl: string = await this.uploadFolder(this.environmentLocalTempFolder, `nni/${this.experimentId}`);
environment.trackingUrl = trialJobOutputUrl;
// Generate kubeflow job resource config object
const frameworkcontrollerJobConfig: any = await this.prepareFrameworkControllerConfig(
environment.id,
this.environmentWorkingFolder,
frameworkcontrollerJobName
);
// Create kubeflow job based on generated kubeflow job resource config
await this.kubernetesCRDClient.createKubernetesJob(frameworkcontrollerJobConfig);
}
/**
* upload local folder to nfs or azureStroage
*/
private async uploadFolder(srcDirectory: string, destDirectory: string): Promise<string> {
if (this.config.storage.storageType === 'azureStorage') {
if (this.azureStorageClient === undefined) {
throw new Error('azureStorageClient is not initialized');
}
return await this.uploadFolderToAzureStorage(srcDirectory, destDirectory, 2);
} else {
// do not need to upload files to nfs server, temp folder already mounted to nfs
return `nfs://${this.config.storage.server}:${destDirectory}`;
}
}
/**
* generate trial's command for frameworkcontroller
* expose port and execute injector.sh before executing user's command
* @param command
*/
private generateCommandScript(taskRoles: FrameworkControllerTaskRoleConfig[], command: string): string {
let portScript: string = '';
for (const taskRole of taskRoles) {
portScript += `FB_${taskRole.name.toUpperCase()}_PORT=${this.fcContainerPortMap.get(
taskRole.name
)} `;
}
return `${portScript} . /mnt/frameworkbarrier/injector.sh && ${command}`;
}
private async prepareFrameworkControllerConfig(envId: string, trialWorkingFolder: string, frameworkcontrollerJobName: string):
Promise<any> {
const podResources: any = [];
for (const taskRole of this.config.taskRoles) {
const resource: any = {};
resource.requests = this.generatePodResource(toMegaBytes(taskRole.memorySize), taskRole.cpuNumber, taskRole.gpuNumber);
resource.limits = {...resource.requests};
podResources.push(resource);
}
// Generate frameworkcontroller job resource config object
const frameworkcontrollerJobConfig: any =
await this.generateFrameworkControllerJobConfig(envId, trialWorkingFolder, frameworkcontrollerJobName, podResources);
return Promise.resolve(frameworkcontrollerJobConfig);
}
private generateContainerPort(taskRoles: FrameworkControllerTrialConfigTemplate[]): void {
if (taskRoles === undefined) {
throw new Error('frameworkcontroller trial config is not initialized');
}
let port: number = 4000; //The default port used in container
for (const index of taskRoles.keys()) {
this.fcContainerPortMap.set(taskRoles[index].name, port);
port += 1;
}
}
/**
* Generate frameworkcontroller resource config file
* @param trialJobId trial job id
* @param trialWorkingFolder working folder
* @param frameworkcontrollerJobName job name
* @param podResources pod template
*/
private async generateFrameworkControllerJobConfig(envId: string, trialWorkingFolder: string,
frameworkcontrollerJobName: string, podResources: any): Promise<any> {
const taskRoles: any = [];
for (const index of this.config.taskRoles.keys()) {
const containerPort: number | undefined = this.fcContainerPortMap.get(this.config.taskRoles[index].name);
if (containerPort === undefined) {
throw new Error('Container port is not initialized');
}
const taskRole: any = this.generateTaskRoleConfig(
trialWorkingFolder,
this.config.taskRoles[index].dockerImage,
`run.sh`,
podResources[index],
containerPort,
await this.createRegistrySecret(this.config.taskRoles[index].privateRegistryAuthPath)
);
taskRoles.push({
name: this.config.taskRoles[index].name,
taskNumber: this.config.taskRoles[index].taskNumber,
frameworkAttemptCompletionPolicy: {
minFailedTaskCount: this.config.taskRoles[index].frameworkAttemptCompletionPolicy.minFailedTaskCount,
minSucceededTaskCount: this.config.taskRoles[index].frameworkAttemptCompletionPolicy.minSucceedTaskCount
},
task: taskRole
});
}
return Promise.resolve({
apiVersion: `frameworkcontroller.microsoft.com/v1`,
kind: 'Framework',
metadata: {
name: frameworkcontrollerJobName,
namespace: this.config.namespace ?? "default",
labels: {
app: this.NNI_KUBERNETES_TRIAL_LABEL,
expId: this.experimentId,
envId: envId
}
},
spec: {
executionType: 'Start',
taskRoles: taskRoles
}
});
}
private generateTaskRoleConfig(trialWorkingFolder: string, replicaImage: string, runScriptFile: string,
podResources: any, containerPort: number, privateRegistrySecretName: string | undefined): any {
const volumeSpecMap: Map<string, object> = new Map<string, object>();
if (this.config.storage.storageType === 'azureStorage') {
volumeSpecMap.set('nniVolumes', [
{
name: 'nni-vol',
azureFile: {
secretName: `${this.azureStorageSecretName}`,
shareName: `${this.azureStorageShare}`,
readonly: false
}
}, {
name: 'frameworkbarrier-volume',
emptyDir: {}
}]);
} else {
volumeSpecMap.set('nniVolumes', [
{
name: 'nni-vol',
nfs: {
server: `${this.config.storage.server}`,
path: `${this.config.storage.path}`
}
}, {
name: 'frameworkbarrier-volume',
emptyDir: {}
}]);
}
const containers: any = [
{
name: 'framework',
image: replicaImage,
command: ['sh', `${path.join(trialWorkingFolder, runScriptFile)}`],
volumeMounts: [
{
name: 'nni-vol',
mountPath: this.CONTAINER_MOUNT_PATH
}, {
name: 'frameworkbarrier-volume',
mountPath: '/mnt/frameworkbarrier'
}],
resources: podResources,
ports: [{
containerPort: containerPort
}]
}];
const initContainers: any = [
{
name: 'frameworkbarrier',
image: 'frameworkcontroller/frameworkbarrier',
volumeMounts: [
{
name: 'frameworkbarrier-volume',
mountPath: '/mnt/frameworkbarrier'
}]
}];
const spec: any = {
containers: containers,
initContainers: initContainers,
restartPolicy: 'OnFailure',
volumes: volumeSpecMap.get('nniVolumes'),
hostNetwork: false
};
if (privateRegistrySecretName) {
spec.imagePullSecrets = [
{
name: privateRegistrySecretName
}
]
}
if (this.config.serviceAccountName !== undefined) {
spec.serviceAccountName = this.config.serviceAccountName;
}
return {
pod: {
spec: spec
}
};
}
public async refreshEnvironmentsStatus(environments: EnvironmentInformation[]): Promise<void> {
environments.forEach(async (environment) => {
if (this.kubernetesCRDClient === undefined) {
throw new Error("kubernetesCRDClient undefined")
}
const kubeflowJobName: string = `nniexp${this.experimentId}env${environment.id}`.toLowerCase();
const kubernetesJobInfo = await this.kubernetesCRDClient.getKubernetesJob(kubeflowJobName);
if (kubernetesJobInfo.status && kubernetesJobInfo.status.state) {
const frameworkJobType: FrameworkControllerJobStatus = <FrameworkControllerJobStatus>kubernetesJobInfo.status.state;
/* eslint-disable require-atomic-updates */
switch (frameworkJobType) {
case 'AttemptCreationPending':
case 'AttemptCreationRequested':
case 'AttemptPreparing':
environment.setStatus('WAITING');
break;
case 'AttemptRunning':
environment.setStatus('RUNNING');
break;
case 'Completed': {
const completedJobType: FrameworkControllerJobCompleteStatus =
<FrameworkControllerJobCompleteStatus>kubernetesJobInfo.status.attemptStatus.completionStatus.type.name;
switch (completedJobType) {
case 'Succeeded':
environment.setStatus('SUCCEEDED');
break;
case 'Failed':
environment.setStatus('FAILED');
break;
default:
}
break;
}
default:
}
/* eslint-enable require-atomic-updates */
}
});
}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/policyDefinitionsMappers";
import * as Parameters from "../models/parameters";
import { PolicyClientContext } from "../policyClientContext";
/** Class representing a PolicyDefinitions. */
export class PolicyDefinitions {
private readonly client: PolicyClientContext;
/**
* Create a PolicyDefinitions.
* @param {PolicyClientContext} client Reference to the service client.
*/
constructor(client: PolicyClientContext) {
this.client = client;
}
/**
* Creates or updates a policy definition.
* @param policyDefinitionName The name of the policy definition to create.
* @param parameters The policy definition properties.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyDefinitionsCreateOrUpdateResponse>
*/
createOrUpdate(policyDefinitionName: string, parameters: Models.PolicyDefinition, options?: msRest.RequestOptionsBase): Promise<Models.PolicyDefinitionsCreateOrUpdateResponse>;
/**
* @param policyDefinitionName The name of the policy definition to create.
* @param parameters The policy definition properties.
* @param callback The callback
*/
createOrUpdate(policyDefinitionName: string, parameters: Models.PolicyDefinition, callback: msRest.ServiceCallback<Models.PolicyDefinition>): void;
/**
* @param policyDefinitionName The name of the policy definition to create.
* @param parameters The policy definition properties.
* @param options The optional parameters
* @param callback The callback
*/
createOrUpdate(policyDefinitionName: string, parameters: Models.PolicyDefinition, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyDefinition>): void;
createOrUpdate(policyDefinitionName: string, parameters: Models.PolicyDefinition, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyDefinition>, callback?: msRest.ServiceCallback<Models.PolicyDefinition>): Promise<Models.PolicyDefinitionsCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{
policyDefinitionName,
parameters,
options
},
createOrUpdateOperationSpec,
callback) as Promise<Models.PolicyDefinitionsCreateOrUpdateResponse>;
}
/**
* Deletes a policy definition.
* @param policyDefinitionName The name of the policy definition to delete.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(policyDefinitionName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param policyDefinitionName The name of the policy definition to delete.
* @param callback The callback
*/
deleteMethod(policyDefinitionName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param policyDefinitionName The name of the policy definition to delete.
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(policyDefinitionName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(policyDefinitionName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
policyDefinitionName,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* Gets the policy definition.
* @param policyDefinitionName The name of the policy definition to get.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyDefinitionsGetResponse>
*/
get(policyDefinitionName: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyDefinitionsGetResponse>;
/**
* @param policyDefinitionName The name of the policy definition to get.
* @param callback The callback
*/
get(policyDefinitionName: string, callback: msRest.ServiceCallback<Models.PolicyDefinition>): void;
/**
* @param policyDefinitionName The name of the policy definition to get.
* @param options The optional parameters
* @param callback The callback
*/
get(policyDefinitionName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyDefinition>): void;
get(policyDefinitionName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyDefinition>, callback?: msRest.ServiceCallback<Models.PolicyDefinition>): Promise<Models.PolicyDefinitionsGetResponse> {
return this.client.sendOperationRequest(
{
policyDefinitionName,
options
},
getOperationSpec,
callback) as Promise<Models.PolicyDefinitionsGetResponse>;
}
/**
* Gets the built in policy definition.
* @param policyDefinitionName The name of the built in policy definition to get.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyDefinitionsGetBuiltInResponse>
*/
getBuiltIn(policyDefinitionName: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyDefinitionsGetBuiltInResponse>;
/**
* @param policyDefinitionName The name of the built in policy definition to get.
* @param callback The callback
*/
getBuiltIn(policyDefinitionName: string, callback: msRest.ServiceCallback<Models.PolicyDefinition>): void;
/**
* @param policyDefinitionName The name of the built in policy definition to get.
* @param options The optional parameters
* @param callback The callback
*/
getBuiltIn(policyDefinitionName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyDefinition>): void;
getBuiltIn(policyDefinitionName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyDefinition>, callback?: msRest.ServiceCallback<Models.PolicyDefinition>): Promise<Models.PolicyDefinitionsGetBuiltInResponse> {
return this.client.sendOperationRequest(
{
policyDefinitionName,
options
},
getBuiltInOperationSpec,
callback) as Promise<Models.PolicyDefinitionsGetBuiltInResponse>;
}
/**
* Creates or updates a policy definition at management group level.
* @param policyDefinitionName The name of the policy definition to create.
* @param parameters The policy definition properties.
* @param managementGroupId The ID of the management group.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyDefinitionsCreateOrUpdateAtManagementGroupResponse>
*/
createOrUpdateAtManagementGroup(policyDefinitionName: string, parameters: Models.PolicyDefinition, managementGroupId: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyDefinitionsCreateOrUpdateAtManagementGroupResponse>;
/**
* @param policyDefinitionName The name of the policy definition to create.
* @param parameters The policy definition properties.
* @param managementGroupId The ID of the management group.
* @param callback The callback
*/
createOrUpdateAtManagementGroup(policyDefinitionName: string, parameters: Models.PolicyDefinition, managementGroupId: string, callback: msRest.ServiceCallback<Models.PolicyDefinition>): void;
/**
* @param policyDefinitionName The name of the policy definition to create.
* @param parameters The policy definition properties.
* @param managementGroupId The ID of the management group.
* @param options The optional parameters
* @param callback The callback
*/
createOrUpdateAtManagementGroup(policyDefinitionName: string, parameters: Models.PolicyDefinition, managementGroupId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyDefinition>): void;
createOrUpdateAtManagementGroup(policyDefinitionName: string, parameters: Models.PolicyDefinition, managementGroupId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyDefinition>, callback?: msRest.ServiceCallback<Models.PolicyDefinition>): Promise<Models.PolicyDefinitionsCreateOrUpdateAtManagementGroupResponse> {
return this.client.sendOperationRequest(
{
policyDefinitionName,
parameters,
managementGroupId,
options
},
createOrUpdateAtManagementGroupOperationSpec,
callback) as Promise<Models.PolicyDefinitionsCreateOrUpdateAtManagementGroupResponse>;
}
/**
* Deletes a policy definition at management group level.
* @param policyDefinitionName The name of the policy definition to delete.
* @param managementGroupId The ID of the management group.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteAtManagementGroup(policyDefinitionName: string, managementGroupId: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param policyDefinitionName The name of the policy definition to delete.
* @param managementGroupId The ID of the management group.
* @param callback The callback
*/
deleteAtManagementGroup(policyDefinitionName: string, managementGroupId: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param policyDefinitionName The name of the policy definition to delete.
* @param managementGroupId The ID of the management group.
* @param options The optional parameters
* @param callback The callback
*/
deleteAtManagementGroup(policyDefinitionName: string, managementGroupId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteAtManagementGroup(policyDefinitionName: string, managementGroupId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
policyDefinitionName,
managementGroupId,
options
},
deleteAtManagementGroupOperationSpec,
callback);
}
/**
* Gets the policy definition at management group level.
* @param policyDefinitionName The name of the policy definition to get.
* @param managementGroupId The ID of the management group.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyDefinitionsGetAtManagementGroupResponse>
*/
getAtManagementGroup(policyDefinitionName: string, managementGroupId: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyDefinitionsGetAtManagementGroupResponse>;
/**
* @param policyDefinitionName The name of the policy definition to get.
* @param managementGroupId The ID of the management group.
* @param callback The callback
*/
getAtManagementGroup(policyDefinitionName: string, managementGroupId: string, callback: msRest.ServiceCallback<Models.PolicyDefinition>): void;
/**
* @param policyDefinitionName The name of the policy definition to get.
* @param managementGroupId The ID of the management group.
* @param options The optional parameters
* @param callback The callback
*/
getAtManagementGroup(policyDefinitionName: string, managementGroupId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyDefinition>): void;
getAtManagementGroup(policyDefinitionName: string, managementGroupId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyDefinition>, callback?: msRest.ServiceCallback<Models.PolicyDefinition>): Promise<Models.PolicyDefinitionsGetAtManagementGroupResponse> {
return this.client.sendOperationRequest(
{
policyDefinitionName,
managementGroupId,
options
},
getAtManagementGroupOperationSpec,
callback) as Promise<Models.PolicyDefinitionsGetAtManagementGroupResponse>;
}
/**
* Gets all the policy definitions for a subscription.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyDefinitionsListResponse>
*/
list(options?: msRest.RequestOptionsBase): Promise<Models.PolicyDefinitionsListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): void;
list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyDefinitionListResult>, callback?: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): Promise<Models.PolicyDefinitionsListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback) as Promise<Models.PolicyDefinitionsListResponse>;
}
/**
* Gets all the built in policy definitions.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyDefinitionsListBuiltInResponse>
*/
listBuiltIn(options?: msRest.RequestOptionsBase): Promise<Models.PolicyDefinitionsListBuiltInResponse>;
/**
* @param callback The callback
*/
listBuiltIn(callback: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
listBuiltIn(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): void;
listBuiltIn(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyDefinitionListResult>, callback?: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): Promise<Models.PolicyDefinitionsListBuiltInResponse> {
return this.client.sendOperationRequest(
{
options
},
listBuiltInOperationSpec,
callback) as Promise<Models.PolicyDefinitionsListBuiltInResponse>;
}
/**
* Gets all the policy definitions for a subscription at management group level.
* @param managementGroupId The ID of the management group.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyDefinitionsListByManagementGroupResponse>
*/
listByManagementGroup(managementGroupId: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyDefinitionsListByManagementGroupResponse>;
/**
* @param managementGroupId The ID of the management group.
* @param callback The callback
*/
listByManagementGroup(managementGroupId: string, callback: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): void;
/**
* @param managementGroupId The ID of the management group.
* @param options The optional parameters
* @param callback The callback
*/
listByManagementGroup(managementGroupId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): void;
listByManagementGroup(managementGroupId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyDefinitionListResult>, callback?: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): Promise<Models.PolicyDefinitionsListByManagementGroupResponse> {
return this.client.sendOperationRequest(
{
managementGroupId,
options
},
listByManagementGroupOperationSpec,
callback) as Promise<Models.PolicyDefinitionsListByManagementGroupResponse>;
}
/**
* Gets all the policy definitions for a subscription.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyDefinitionsListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyDefinitionsListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyDefinitionListResult>, callback?: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): Promise<Models.PolicyDefinitionsListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.PolicyDefinitionsListNextResponse>;
}
/**
* Gets all the built in policy definitions.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyDefinitionsListBuiltInNextResponse>
*/
listBuiltInNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyDefinitionsListBuiltInNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listBuiltInNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listBuiltInNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): void;
listBuiltInNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyDefinitionListResult>, callback?: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): Promise<Models.PolicyDefinitionsListBuiltInNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listBuiltInNextOperationSpec,
callback) as Promise<Models.PolicyDefinitionsListBuiltInNextResponse>;
}
/**
* Gets all the policy definitions for a subscription at management group level.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyDefinitionsListByManagementGroupNextResponse>
*/
listByManagementGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyDefinitionsListByManagementGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByManagementGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByManagementGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): void;
listByManagementGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyDefinitionListResult>, callback?: msRest.ServiceCallback<Models.PolicyDefinitionListResult>): Promise<Models.PolicyDefinitionsListByManagementGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByManagementGroupNextOperationSpec,
callback) as Promise<Models.PolicyDefinitionsListByManagementGroupNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const createOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}",
urlParameters: [
Parameters.policyDefinitionName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.PolicyDefinition,
required: true
}
},
responses: {
201: {
bodyMapper: Mappers.PolicyDefinition
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}",
urlParameters: [
Parameters.policyDefinitionName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}",
urlParameters: [
Parameters.policyDefinitionName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyDefinition
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getBuiltInOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}",
urlParameters: [
Parameters.policyDefinitionName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyDefinition
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const createOrUpdateAtManagementGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}",
urlParameters: [
Parameters.policyDefinitionName,
Parameters.managementGroupId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.PolicyDefinition,
required: true
}
},
responses: {
201: {
bodyMapper: Mappers.PolicyDefinition
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const deleteAtManagementGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}",
urlParameters: [
Parameters.policyDefinitionName,
Parameters.managementGroupId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getAtManagementGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}",
urlParameters: [
Parameters.policyDefinitionName,
Parameters.managementGroupId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyDefinition
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyDefinitionListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listBuiltInOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Authorization/policyDefinitions",
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyDefinitionListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByManagementGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions",
urlParameters: [
Parameters.managementGroupId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyDefinitionListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyDefinitionListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listBuiltInNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyDefinitionListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByManagementGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyDefinitionListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import * as del from "del";
import * as fs from "fs";
import { ensureDir, move, pathExists, remove } from "fs-extra";
import * as path from "path";
import * as tarfs from "tar-fs";
import * as vscode from "vscode";
import * as yauzl from "yauzl";
import * as zlib from "zlib";
import { IdfToolsManager } from "./idfToolsManager";
import { IPackage } from "./IPackage";
import { Logger } from "./logger/logger";
import { OutputChannel } from "./logger/outputChannel";
import { PackageError } from "./packageError";
import * as utils from "./utils";
export class InstallManager {
constructor(private installPath: string) {}
public getToolPackagesPath(toolPackage: string[]) {
return path.resolve(this.installPath, ...toolPackage);
}
public async installPackages(
idfToolsManager: IdfToolsManager,
progress: vscode.Progress<{ message?: string; increment?: number }>,
cancelToken?: vscode.CancellationToken
): Promise<void> {
return idfToolsManager.getPackageList().then((packages) => {
let count: number = 1;
return utils.buildPromiseChain(packages, async (pkg) => {
const versionName = idfToolsManager.getVersionToUse(pkg);
const absolutePath: string = this.getToolPackagesPath([
"tools",
pkg.name,
versionName,
]);
const binDir = pkg.binaries
? path.join(absolutePath, ...pkg.binaries)
: absolutePath;
const toolPathExists = await pathExists(binDir);
if (toolPathExists) {
const binVersion = await idfToolsManager.checkBinariesVersion(
pkg,
binDir
);
const expectedVersion = idfToolsManager.getVersionToUse(pkg);
if (binVersion === expectedVersion) {
this.appendChannel(
`Using existing ${pkg.description} in ${absolutePath}`
);
progress.report({
message: `Installed ${count}/${packages.length}: ${pkg.description}...`,
});
return;
}
}
progress.report({
message: `Installing ${count}/${packages.length}: ${pkg.description}...`,
});
this.appendChannel(`Installing package ${pkg.description}`);
const urlToUse = idfToolsManager.obtainUrlInfoForPlatform(pkg);
const parsedUrl = urlToUse.url.split(/\#|\?/)[0].split("."); // Get url file extension
let p: Promise<void>;
if (parsedUrl[parsedUrl.length - 1] === "zip") {
p = this.installZipPackage(idfToolsManager, pkg, cancelToken).then(
async () => {
if (pkg.strip_container_dirs) {
await this.promisedStripContainerDirs(
absolutePath,
pkg.strip_container_dirs
);
}
}
);
} else if (
parsedUrl[parsedUrl.length - 2] === "tar" &&
parsedUrl[parsedUrl.length - 1] === "gz"
) {
p = this.installTarPackage(idfToolsManager, pkg, cancelToken).then(
async () => {
if (pkg.strip_container_dirs) {
await this.promisedStripContainerDirs(
absolutePath,
pkg.strip_container_dirs
);
}
}
);
} else {
p = new Promise<void>((resolve) => {
resolve();
});
}
count += 1;
return p;
});
});
}
public async installZipFile(
zipFilePath: string,
destPath: string,
cancelToken?: vscode.CancellationToken
) {
return new Promise<void>(async (resolve, reject) => {
const doesZipFileExists = await pathExists(zipFilePath);
if (!doesZipFileExists) {
return reject(`File ${zipFilePath} doesn't exist.`);
}
yauzl.open(zipFilePath, { lazyEntries: true }, (error, zipfile) => {
if (error) {
return reject(
new PackageError("Zip file error", "InstallZipFile", error)
);
}
if (cancelToken && cancelToken.isCancellationRequested) {
return reject(
new PackageError("Install cancelled by user", "InstallZipFile")
);
}
zipfile.on("end", () => {
return resolve();
});
zipfile.on("error", (err) => {
return reject(
new PackageError("Zip File error", "InstallZipFile", err)
);
});
zipfile.readEntry();
zipfile.on("entry", async (entry: yauzl.Entry) => {
const absolutePath: string = path.resolve(destPath, entry.fileName);
const dirExists = await utils.dirExistPromise(absolutePath);
if (dirExists) {
try {
await del(absolutePath, { force: true });
} catch (err) {
this.appendChannel(
`Error deleting previous ${absolutePath}: ${err.message}`
);
return reject(
new PackageError(
"Install folder cant be deleted",
"InstallZipFile",
err,
err.errorCode
)
);
}
}
if (entry.fileName.endsWith("/")) {
try {
await ensureDir(absolutePath, { mode: 0o775 });
zipfile.readEntry();
} catch (err) {
return reject(
new PackageError(
"Error creating directory",
"InstallZipFile",
err
)
);
}
} else {
const exists = await pathExists(absolutePath);
if (!exists) {
zipfile.openReadStream(
entry,
async (err, readStream: fs.ReadStream) => {
if (err) {
return reject(
new PackageError(
"Error reading zip stream",
"InstallZipFile",
err
)
);
}
readStream.on("error", (openErr) => {
return reject(
new PackageError(
"Error in readstream",
"InstallZipFile",
openErr
)
);
});
try {
await ensureDir(path.dirname(absolutePath), {
mode: 0o775,
});
} catch (mkdirErr) {
return reject(
new PackageError(
"Error creating directory",
"InstallZipFile",
mkdirErr
)
);
}
const absoluteEntryTmpPath: string = absolutePath + ".tmp";
const doesTmpPathExists = await pathExists(
absoluteEntryTmpPath
);
if (doesTmpPathExists) {
try {
await remove(absoluteEntryTmpPath);
} catch (rmError) {
return reject(
new PackageError(
`Error unlinking tmp file ${absoluteEntryTmpPath}`,
"InstallZipFile",
rmError
)
);
}
}
const writeStream: fs.WriteStream = fs.createWriteStream(
absoluteEntryTmpPath,
{ mode: 0o755 }
);
writeStream.on("error", (writeStreamErr) => {
return reject(
new PackageError(
"Error in writeStream",
"InstallZipFile",
writeStreamErr
)
);
});
writeStream.on("close", async () => {
try {
await move(absoluteEntryTmpPath, absolutePath);
} catch (closeWriteStreamErr) {
return reject(
new PackageError(
`Error renaming file ${absoluteEntryTmpPath}`,
"InstallZipFile",
closeWriteStreamErr
)
);
}
zipfile.readEntry();
});
readStream.pipe(writeStream);
}
);
} else {
if (path.extname(absolutePath) !== ".txt") {
this.appendChannel(
`Warning File ${absolutePath}
already exists and was not updated.`
);
}
zipfile.readEntry();
}
}
});
});
});
}
public async installZipPackage(
idfToolsManager: IdfToolsManager,
pkg: IPackage,
cancelToken?: vscode.CancellationToken
) {
this.appendChannel(`Installing zip package ${pkg.description}`);
const urlInfo = idfToolsManager.obtainUrlInfoForPlatform(pkg);
const fileName = utils.fileNameFromUrl(urlInfo.url);
const packageFile: string = this.getToolPackagesPath(["dist", fileName]);
const packageDownloaded = await pathExists(packageFile);
if (!packageDownloaded) {
this.appendChannel(
`${pkg.description} downloaded file is not available.`
);
throw new PackageError(
"Error finding downloaded file",
"InstallZipPackage"
);
}
const isValidFile = await utils.validateFileSizeAndChecksum(
packageFile,
urlInfo.sha256,
urlInfo.size
);
if (!isValidFile) {
this.appendChannel(
`Package ${pkg.description} downloaded file is invalid.`
);
throw new PackageError("Downloaded file invalid", "InstallZipPackage");
}
const versionName = idfToolsManager.getVersionToUse(pkg);
const absolutePath: string = this.getToolPackagesPath([
"tools",
pkg.name,
versionName,
]);
return await this.installZipFile(packageFile, absolutePath, cancelToken);
}
public installTarPackage(
idfToolsManager: IdfToolsManager,
pkg: IPackage,
cancelToken?: vscode.CancellationToken
): Promise<void> {
return new Promise(async (resolve, reject) => {
const urlInfo = idfToolsManager.obtainUrlInfoForPlatform(pkg);
const fileName = utils.fileNameFromUrl(urlInfo.url);
const packageFile: string = this.getToolPackagesPath(["dist", fileName]);
if (cancelToken && cancelToken.isCancellationRequested) {
return reject(new Error("Process cancelled by user"));
}
const packageDownloaded = await pathExists(packageFile);
if (!packageDownloaded) {
this.appendChannel(
`Package ${pkg.description} downloaded file not available.`
);
return reject(
new PackageError("Downloaded file unavailable", "InstallTarPackage")
);
}
const isValidFile = await utils.validateFileSizeAndChecksum(
packageFile,
urlInfo.sha256,
urlInfo.size
);
if (!isValidFile) {
this.appendChannel(
`Package ${pkg.description} downloaded file is invalid.`
);
return reject(
new PackageError("Downloaded file invalid", "InstallTarPackage")
);
}
const versionName = idfToolsManager.getVersionToUse(pkg);
const absolutePath: string = this.getToolPackagesPath([
"tools",
pkg.name,
versionName,
]);
const dirExists = await utils.dirExistPromise(absolutePath);
if (dirExists) {
try {
await del(absolutePath, { force: true });
} catch (err) {
this.appendChannel(
`Error deleting ${pkg.name} old install: ${err.message}`
);
return reject(
new PackageError(
"Install folder cant be deleted",
"installTarPackage",
err,
err.errorCode
)
);
}
}
const binPath = pkg.binaries
? path.join(absolutePath, ...pkg.binaries, pkg.version_cmd[0])
: path.join(absolutePath, pkg.version_cmd[0]);
const binExists = await pathExists(binPath);
if (binExists) {
this.appendChannel(
`Existing ${pkg.description} found in ${this.installPath}`
);
return resolve();
}
this.appendChannel(`Installing tar.gz package ${pkg.description}`);
const extractor = tarfs.extract(absolutePath, {
readable: true, // all dirs and files should be readable
writable: true, // all dirs and files should be writable
});
extractor.on("error", (err) => {
reject(
new PackageError(
"Extracting gunzipped tar error",
"InstallTarPackage",
err,
err.code
)
);
});
extractor.on("finish", () => {
return resolve();
});
try {
fs.createReadStream(packageFile)
.pipe(zlib.createGunzip())
.pipe(extractor);
} catch (error) {
return reject(error);
}
});
}
private appendChannel(text: string): void {
OutputChannel.appendLine(text);
Logger.info(text);
}
private async promisedStripContainerDirs(pkgDirPath: string, levels: number) {
const tmpPath = pkgDirPath + ".tmp";
const exists = await utils.dirExistPromise(tmpPath);
if (exists) {
await del(tmpPath, { force: true });
}
await move(pkgDirPath, tmpPath);
await ensureDir(pkgDirPath);
let basePath = tmpPath;
// Walk given number of levels down
for (let i = 0; i < levels; i++) {
const files = await utils.readDirPromise(basePath);
if (files.length > 1) {
throw new Error(`At level ${i} expected 1 entry, got ${files.length}`);
}
basePath = path.join(basePath, files[0]);
const isDirectory = await utils.dirExistPromise(basePath);
if (!isDirectory) {
throw new Error(
`At level ${levels[i]}, ${files[0]} is not a directory.`
);
}
}
// Get list of directories/files to move
const filesToMove = await utils.readDirPromise(basePath);
for (let file of filesToMove) {
const moveFrom = path.join(basePath, file);
const moveTo = path.join(pkgDirPath, file);
await move(moveFrom, moveTo);
}
await del(tmpPath, { force: true });
}
} | the_stack |
import { WrappingStyle as WrappingStyleType } from "../types/misc";
import * as drawing from "./drawing";
export { drawing };
/**
* Represents a CSS color with red, green, blue and alpha components.
*
* Instances of this class are immutable.
*
* @param {number} red
* @param {number} green
* @param {number} blue
* @param {number=1} alpha
*/
export class Color {
constructor(private _red: number, private _green: number, private _blue: number, private _alpha: number = 1) { }
/**
* The red component of this color as a number between 0 and 255.
*
* @type {number}
*/
get red(): number {
return this._red;
}
/**
* The green component of this color as a number between 0 and 255.
*
* @type {number}
*/
get green(): number {
return this._green;
}
/**
* The blue component of this color as a number between 0 and 255.
*
* @type {number}
*/
get blue(): number {
return this._blue;
}
/**
* The alpha component of this color as a number between 0 and 1, where 0 means transparent and 1 means opaque.
*
* @type {number}
*/
get alpha(): number {
return this._alpha;
}
/**
* @param {?number} value The new alpha. If null, the existing alpha is used.
* @return {!libjass.parts.Color} Returns a new Color instance with the same color but the provided alpha.
*/
withAlpha(value: number): Color {
return new Color(this._red, this._green, this._blue, value);
}
/**
* @return {string} The CSS representation "rgba(...)" of this color.
*/
toString(): string {
return `rgba(${ this._red }, ${ this._green }, ${ this._blue }, ${ this._alpha.toFixed(3) })`;
}
/**
* Returns a new Color by interpolating the current color to the final color by the given progression.
*
* @param {!libjass.parts.Color} final
* @param {number} progression
* @return {!libjass.parts.Color}
*/
interpolate(final: Color, progression: number): Color {
return new Color(
this._red + progression * (final.red - this._red),
this._green + progression * (final.green - this._green),
this._blue + progression * (final.blue - this._blue),
this._alpha + progression * (final.alpha - this._alpha),
);
}
}
/**
* The base interface of the ASS tag classes.
*/
export interface Part { }
/**
* A comment, i.e., any text enclosed in {} that is not understood as an ASS tag.
*
* @param {string} value The text of this comment
*/
export class Comment {
constructor(private _value: string) { }
/**
* The value of this comment.
*
* @type {string}
*/
get value(): string {
return this._value;
}
}
/**
* A block of text, i.e., any text not enclosed in {}. Also includes \h.
*
* @param {string} value The content of this block of text
*/
export class Text {
constructor(private _value: string) { }
/**
* The value of this text part.
*
* @type {string}
*/
get value(): string {
return this._value;
}
/**
* @return {string}
*/
toString(): string {
return `Text { value: ${ this._value.replace(/\u00A0/g, "\\h") } }`;
}
}
/**
* A newline character \N.
*/
export class NewLine {
}
/**
* A soft newline character \n.
*/
export class SoftNewLine {
}
/**
* An italic tag {\i}
*
* @param {?boolean} value {\i1} -> true, {\i0} -> false, {\i} -> null
*/
export class Italic {
constructor(private _value: boolean | null) { }
/**
* The value of this italic tag.
*
* @type {?boolean}
*/
get value(): boolean | null {
return this._value;
}
}
/**
* A bold tag {\b}
*
* @param {?boolean|?number} value {\b1} -> true, {\b0} -> false, {\b###} -> weight of the bold (number), {\b} -> null
*/
export class Bold {
constructor(private _value: boolean | number | null) { }
/**
* The value of this bold tag.
*
* @type {?boolean|?number}
*/
get value(): boolean | number | null {
return this._value;
}
}
/**
* An underline tag {\u}
*
* @param {?boolean} value {\u1} -> true, {\u0} -> false, {\u} -> null
*/
export class Underline {
constructor(private _value: boolean | null) { }
/**
* The value of this underline tag.
*
* @type {?boolean}
*/
get value(): boolean | null {
return this._value;
}
}
/**
* A strike-through tag {\s}
*
* @param {?boolean} value {\s1} -> true, {\s0} -> false, {\s} -> null
*/
export class StrikeThrough {
constructor(private _value: boolean | null) { }
/**
* The value of this strike-through tag.
*
* @type {?boolean}
*/
get value(): boolean | null {
return this._value;
}
}
/**
* A border tag {\bord}
*
* @param {?number} value {\bord###} -> width (number), {\bord} -> null
*/
export class Border {
constructor(private _value: number | null) { }
/**
* The value of this border tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A horizontal border tag {\xbord}
*
* @param {?number} value {\xbord###} -> width (number), {\xbord} -> null
*/
export class BorderX {
constructor(private _value: number | null) { }
/**
* The value of this horizontal border tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A vertical border tag {\ybord}
*
* @param {?number} value {\ybord###} -> height (number), {\ybord} -> null
*/
export class BorderY {
constructor(private _value: number | null) { }
/**
* The value of this vertical border tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A shadow tag {\shad}
*
* @param {?number} value {\shad###} -> depth (number), {\shad} -> null
*/
export class Shadow {
constructor(private _value: number | null) { }
/**
* The value of this shadow tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A horizontal shadow tag {\xshad}
*
* @param {?number} value {\xshad###} -> depth (number), {\xshad} -> null
*/
export class ShadowX {
constructor(private _value: number | null) { }
/**
* The value of this horizontal shadow tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A vertical shadow tag {\yshad}
*
* @param {?number} value {\yshad###} -> depth (number), {\yshad} -> null
*/
export class ShadowY {
constructor(private _value: number | null) { }
/**
* The value of this vertical shadow tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A blur tag {\be}
*
* @param {?number} value {\be###} -> strength (number), {\be} -> null
*/
export class Blur {
constructor(private _value: number | null) { }
/**
* The value of this blur tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A Gaussian blur tag {\blur}
*
* @param {?number} value {\blur###} -> strength (number), {\blur} -> null
*/
export class GaussianBlur {
constructor(private _value: number | null) { }
/**
* The value of this Gaussian blur tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A font name tag {\fn}
*
* @param {?string} value {\fn###} -> name (string), {\fn} -> null
*/
export class FontName {
constructor(private _value: string | null) { }
/**
* The value of this font name tag.
*
* @type {?string}
*/
get value(): string | null {
return this._value;
}
}
/**
* A font size tag {\fs}
*
* @param {?number} value {\fs###} -> size (number), {\fs} -> null
*/
export class FontSize {
constructor(private _value: number | null) { }
/**
* The value of this font size tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A font size increase tag {\fs+}
*
* @param {number} value {\fs+###} -> relative difference (number, percentage)
*/
export class FontSizePlus {
constructor(private _value: number) { }
/**
* The value of this font size increase tag.
*
* @type {number}
*/
get value(): number {
return this._value;
}
}
/**
* A font size decrease tag {\fs-}
*
* @param {number} value {\fs-###} -> relative difference (number, percentage)
*/
export class FontSizeMinus {
constructor(private _value: number) { }
/**
* The value of this font size decrease tag.
*
* @type {number}
*/
get value(): number {
return this._value;
}
}
/**
* A horizontal font scaling tag {\fscx}
*
* @param {?number} value {\fscx###} -> scale (number), {\fscx} -> null
*/
export class FontScaleX {
constructor(private _value: number | null) { }
/**
* The value of this horizontal font scaling tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A vertical font scaling tag {\fscy}
*
* @param {?number} value {\fscy###} -> scale (number), {\fscy} -> null
*/
export class FontScaleY {
constructor(private _value: number | null) { }
/**
* The value of this vertical font scaling tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A letter-spacing tag {\fsp}
*
* @param {?number} value {\fsp###} -> spacing (number), {\fsp} -> null
*/
export class LetterSpacing {
constructor(private _value: number | null) { }
/**
* The value of this letter-spacing tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* An X-axis rotation tag {\frx}
*
* @param {?number} value {\frx###} -> angle (number), {\frx} -> null
*/
export class RotateX {
constructor(private _value: number | null) { }
/**
* The value of this X-axis rotation tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A Y-axis rotation tag {\fry}
*
* @param {?number} value {\fry###} -> angle (number), {\fry} -> null
*/
export class RotateY {
constructor(private _value: number | null) { }
/**
* The value of this Y-axis rotation tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A Z-axis rotation tag {\fr} or {\frz}
*
* @param {?number} value {\frz###} -> angle (number), {\frz} -> null
*/
export class RotateZ {
constructor(private _value: number | null) { }
/**
* The value of this Z-axis rotation tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* An X-axis shearing tag {\fax}
*
* @param {?number} value {\fax###} -> angle (number), {\fax} -> null
*/
export class SkewX {
constructor(private _value: number | null) { }
/**
* The value of this X-axis shearing tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A Y-axis shearing tag {\fay}
*
* @param {?number} value {\fay###} -> angle (number), {\fay} -> null
*/
export class SkewY {
constructor(private _value: number | null) { }
/**
* The value of this Y-axis shearing tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A primary color tag {\c} or {\1c}
*
* @param {libjass.parts.Color} value {\1c###} -> color (Color), {\1c} -> null
*/
export class PrimaryColor {
constructor(private _value: Color | null) { }
/**
* The value of this primary color tag.
*
* @type {libjass.parts.Color}
*/
get value(): Color | null {
return this._value;
}
}
/**
* A secondary color tag {\2c}
*
* @param {libjass.parts.Color} value {\2c###} -> color (Color), {\2c} -> null
*/
export class SecondaryColor {
constructor(private _value: Color | null) { }
/**
* The value of this secondary color tag.
*
* @type {libjass.parts.Color}
*/
get value(): Color | null {
return this._value;
}
}
/**
* An outline color tag {\3c}
*
* @param {libjass.parts.Color} value {\3c###} -> color (Color), {\3c} -> null
*/
export class OutlineColor {
constructor(private _value: Color | null) { }
/**
* The value of this outline color tag.
*
* @type {libjass.parts.Color}
*/
get value(): Color | null {
return this._value;
}
}
/**
* A shadow color tag {\4c}
*
* @param {libjass.parts.Color} value {\4c###} -> color (Color), {\4c} -> null
*/
export class ShadowColor {
constructor(private _value: Color | null) { }
/**
* The value of this shadow color tag.
*
* @type {libjass.parts.Color}
*/
get value(): Color | null {
return this._value;
}
}
/**
* An alpha tag {\alpha}
*
* @param {?number} value {\alpha###} -> alpha (number), {\alpha} -> null
*/
export class Alpha {
constructor(private _value: number | null) { }
/**
* The value of this alpha tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A primary alpha tag {\1a}
*
* @param {?number} value {\1a###} -> alpha (number), {\1a} -> null
*/
export class PrimaryAlpha {
constructor(private _value: number | null) { }
/**
* The value of this primary alpha tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A secondary alpha tag {\2a}
*
* @param {?number} value {\2a###} -> alpha (number), {\2a} -> null
*/
export class SecondaryAlpha {
constructor(private _value: number | null) { }
/**
* The value of this secondary alpha tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* An outline alpha tag {\3a}
*
* @param {?number} value {\3a###} -> alpha (number), {\3a} -> null
*/
export class OutlineAlpha {
constructor(private _value: number | null) { }
/**
* The value of this outline alpha tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* A shadow alpha tag {\4a}
*
* @param {?number} value {\4a###} -> alpha (number), {\4a} -> null
*/
export class ShadowAlpha {
constructor(private _value: number | null) { }
/**
* The value of this shadow alpha tag.
*
* @type {?number}
*/
get value(): number | null {
return this._value;
}
}
/**
* An alignment tag {\an} or {\a}
*
* @param {number} value {\an###} -> alignment (number)
*/
export class Alignment {
constructor(private _value: number) { }
/**
* The value of this alignment tag.
*
* @type {number}
*/
get value(): number {
return this._value;
}
}
/**
* A color karaoke tag {\k}
*
* @param {number} duration {\k###} -> duration (number)
*/
export class ColorKaraoke {
constructor(private _duration: number) { }
/**
* The duration of this color karaoke tag.
*
* @type {number}
*/
get duration(): number {
return this._duration;
}
}
/**
* A sweeping color karaoke tag {\K} or {\kf}
*
* @param {number} duration {\kf###} -> duration (number)
*/
export class SweepingColorKaraoke {
constructor(private _duration: number) { }
/**
* The duration of this sweeping color karaoke tag.
*
* @type {number}
*/
get duration(): number {
return this._duration;
}
}
/**
* An outline karaoke tag {\ko}
*
* @param {number} duration {\ko###} -> duration (number)
*/
export class OutlineKaraoke {
constructor(private _duration: number) { }
/**
* The duration of this outline karaoke tag.
*
* @type {number}
*/
get duration(): number {
return this._duration;
}
}
/**
* A wrapping style tag {\q}
*
* @param {number} value {\q###} -> style (number)
*/
export class WrappingStyle {
constructor(private _value: WrappingStyleType) { }
/**
* The value of this wrapping style tag.
*
* @type {number}
*/
get value(): WrappingStyleType {
return this._value;
}
}
/**
* A style reset tag {\r}
*
* @param {?string} value {\r###} -> style name (string), {\r} -> null
*/
export class Reset {
constructor(private _value: string | null) { }
/**
* The value of this style reset tag.
*
* @type {?string}
*/
get value(): string | null {
return this._value;
}
}
/**
* A position tag {\pos}
*
* @param {number} x
* @param {number} y
*/
export class Position {
constructor(private _x: number, private _y: number) { }
/**
* The x value of this position tag.
*
* @type {number}
*/
get x(): number {
return this._x;
}
/**
* The y value of this position tag.
*
* @type {number}
*/
get y(): number {
return this._y;
}
}
/**
* A movement tag {\move}
*
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @param {?number} t1
* @param {?number} t2
*/
export class Move {
constructor(private _x1: number, private _y1: number, private _x2: number, private _y2: number, private _t1: number | null, private _t2: number | null) { }
/**
* The starting x value of this move tag.
*
* @type {number}
*/
get x1(): number {
return this._x1;
}
/**
* The starting y value of this move tag.
*
* @type {number}
*/
get y1(): number {
return this._y1;
}
/**
* The ending x value of this move tag.
*
* @type {number}
*/
get x2(): number {
return this._x2;
}
/**
* The ending y value of this move tag.
*
* @type {number}
*/
get y2(): number {
return this._y2;
}
/**
* The start time of this move tag.
*
* @type {?number}
*/
get t1(): number | null {
return this._t1;
}
/**
* The end time value of this move tag.
*
* @type {?number}
*/
get t2(): number | null {
return this._t2;
}
}
/**
* A rotation origin tag {\org}
*
* @param {number} x
* @param {number} y
*/
export class RotationOrigin {
constructor(private _x: number, private _y: number) { }
/**
* The x value of this rotation origin tag.
*
* @type {number}
*/
get x(): number {
return this._x;
}
/**
* The y value of this rotation origin tag.
*
* @type {number}
*/
get y(): number {
return this._y;
}
}
/**
* A simple fade tag {\fad}
*
* @param {number} start
* @param {number} end
*/
export class Fade {
constructor(private _start: number, private _end: number) { }
/**
* The start time of this fade tag.
*
* @type {number}
*/
get start(): number {
return this._start;
}
/**
* The end time of this fade tag.
*
* @type {number}
*/
get end(): number {
return this._end;
}
}
/**
* A complex fade tag {\fade}
*
* @param {number} a1
* @param {number} a2
* @param {number} a3
* @param {number} t1
* @param {number} t2
* @param {number} t3
* @param {number} t4
*/
export class ComplexFade {
constructor(
private _a1: number, private _a2: number, private _a3: number,
private _t1: number, private _t2: number, private _t3: number, private _t4: number,
) { }
/**
* The alpha value of this complex fade tag at time t2.
*
* @type {number}
*/
get a1(): number {
return this._a1;
}
/**
* The alpha value of this complex fade tag at time t3.
*
* @type {number}
*/
get a2(): number {
return this._a2;
}
/**
* The alpha value of this complex fade tag at time t4.
*
* @type {number}
*/
get a3(): number {
return this._a3;
}
/**
* The starting time of this complex fade tag.
*
* @type {number}
*/
get t1(): number {
return this._t1;
}
/**
* The first intermediate time of this complex fade tag.
*
* @type {number}
*/
get t2(): number {
return this._t2;
}
/**
* The second intermediate time of this complex fade tag.
*
* @type {number}
*/
get t3(): number {
return this._t3;
}
/**
* The ending time of this complex fade tag.
*
* @type {number}
*/
get t4(): number {
return this._t4;
}
}
/**
* A transform tag {\t}
*
* @param {?number} start
* @param {?number} end
* @param {?number} accel
* @param {!Array.<!libjass.parts.Tag>} tags
*/
export class Transform {
constructor(private _start: number | null, private _end: number | null, private _accel: number | null, private _tags: Part[]) { }
/**
* The starting time of this transform tag.
*
* @type {?number}
*/
get start(): number | null {
return this._start;
}
/**
* The ending time of this transform tag.
*
* @type {?number}
*/
get end(): number | null {
return this._end;
}
/**
* The acceleration of this transform tag.
*
* @type {?number}
*/
get accel(): number | null {
return this._accel;
}
/**
* The tags animated by this transform tag.
*
* @type {!Array.<!libjass.parts.Tag>}
*/
get tags(): Part[] {
return this._tags;
}
}
/**
* A rectangular clip tag {\clip} or {\iclip}
*
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @param {boolean} inside
*/
export class RectangularClip {
constructor(private _x1: number, private _y1: number, private _x2: number, private _y2: number, private _inside: boolean) { }
/**
* The X coordinate of the starting position of this rectangular clip tag.
*
* @type {number}
*/
get x1(): number {
return this._x1;
}
/**
* The Y coordinate of the starting position of this rectangular clip tag.
*
* @type {number}
*/
get y1(): number {
return this._y1;
}
/**
* The X coordinate of the ending position of this rectangular clip tag.
*
* @type {number}
*/
get x2(): number {
return this._x2;
}
/**
* The Y coordinate of the ending position of this rectangular clip tag.
*
* @type {number}
*/
get y2(): number {
return this._y2;
}
/**
* Whether this rectangular clip tag clips the region it encloses or the region it excludes.
*
* @type {boolean}
*/
get inside(): boolean {
return this._inside;
}
}
/**
* A vector clip tag {\clip} or {\iclip}
*
* @param {number} scale
* @param {!Array.<!libjass.parts.drawing.Instruction>} instructions
* @param {boolean} inside
*/
export class VectorClip {
constructor(private _scale: number, private _instructions: drawing.Instruction[], private _inside: boolean) { }
/**
* The scale of this vector clip tag.
*
* @type {number}
*/
get scale(): number {
return this._scale;
}
/**
* The clip commands of this vector clip tag.
*
* @type {string}
*/
get instructions(): drawing.Instruction[] {
return this._instructions;
}
/**
* Whether this vector clip tag clips the region it encloses or the region it excludes.
*
* @type {boolean}
*/
get inside(): boolean {
return this._inside;
}
}
/**
* A drawing mode tag {\p}
*
* @param {number} scale
*/
export class DrawingMode {
constructor(private _scale: number) { }
/**
* The scale of this drawing mode tag.
*
* @type {number}
*/
get scale(): number {
return this._scale;
}
}
/**
* A drawing mode baseline offset tag {\pbo}
*
* @param {number} value
*/
export class DrawingBaselineOffset {
constructor(private _value: number) { }
/**
* The value of this drawing mode baseline offset tag.
*
* @type {number}
*/
get value(): number {
return this._value;
}
}
/**
* A pseudo-part representing text interpreted as drawing instructions
*
* @param {!Array.<!libjass.parts.drawing.Instruction>} instructions
*/
export class DrawingInstructions {
constructor(private _instructions: drawing.Instruction[]) { }
/**
* The instructions contained in this drawing instructions part.
*
* @type {!Array.<!libjass.parts.drawing.Instruction>}
*/
get instructions(): drawing.Instruction[] {
return this._instructions;
}
}
const addToString = function (ctor: Function, ctorName: string): void {
if (!ctor.prototype.hasOwnProperty("toString")) {
const propertyNames = Object.getOwnPropertyNames(ctor.prototype).filter(property => property !== "constructor");
ctor.prototype.toString = function (this: any): string {
return `${ ctorName } { ${ propertyNames.map(name => `${ name }: ${ this[name] }`).join(", ") }${ (propertyNames.length > 0) ? " " : "" }}`;
};
}
};
import { registerClass } from "../serialization";
for (const key of Object.keys(exports)) {
const value: any = exports[key];
if (value instanceof Function) {
addToString(value, key);
registerClass(value);
}
}
for (const key of Object.keys(drawing)) {
const value: any = (drawing as any)[key];
if (value instanceof Function) {
addToString(value, `Drawing${ key }`);
registerClass(value);
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { PollerLike, PollOperationState } from "@azure/core-lro";
import {
P2SVpnGateway,
P2SVpnGatewaysListByResourceGroupOptionalParams,
P2SVpnGatewaysListOptionalParams,
P2SVpnGatewaysGetOptionalParams,
P2SVpnGatewaysGetResponse,
P2SVpnGatewaysCreateOrUpdateOptionalParams,
P2SVpnGatewaysCreateOrUpdateResponse,
TagsObject,
P2SVpnGatewaysUpdateTagsOptionalParams,
P2SVpnGatewaysUpdateTagsResponse,
P2SVpnGatewaysDeleteOptionalParams,
P2SVpnProfileParameters,
P2SVpnGatewaysGenerateVpnProfileOptionalParams,
P2SVpnGatewaysGenerateVpnProfileResponse,
P2SVpnGatewaysGetP2SVpnConnectionHealthOptionalParams,
P2SVpnGatewaysGetP2SVpnConnectionHealthResponse,
P2SVpnConnectionHealthRequest,
P2SVpnGatewaysGetP2SVpnConnectionHealthDetailedOptionalParams,
P2SVpnGatewaysGetP2SVpnConnectionHealthDetailedResponse,
P2SVpnConnectionRequest,
P2SVpnGatewaysDisconnectP2SVpnConnectionsOptionalParams
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Interface representing a P2SVpnGateways. */
export interface P2SVpnGateways {
/**
* Lists all the P2SVpnGateways in a resource group.
* @param resourceGroupName The resource group name of the P2SVpnGateway.
* @param options The options parameters.
*/
listByResourceGroup(
resourceGroupName: string,
options?: P2SVpnGatewaysListByResourceGroupOptionalParams
): PagedAsyncIterableIterator<P2SVpnGateway>;
/**
* Lists all the P2SVpnGateways in a subscription.
* @param options The options parameters.
*/
list(
options?: P2SVpnGatewaysListOptionalParams
): PagedAsyncIterableIterator<P2SVpnGateway>;
/**
* Retrieves the details of a virtual wan p2s vpn gateway.
* @param resourceGroupName The resource group name of the P2SVpnGateway.
* @param gatewayName The name of the gateway.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
gatewayName: string,
options?: P2SVpnGatewaysGetOptionalParams
): Promise<P2SVpnGatewaysGetResponse>;
/**
* Creates a virtual wan p2s vpn gateway if it doesn't exist else updates the existing gateway.
* @param resourceGroupName The resource group name of the P2SVpnGateway.
* @param gatewayName The name of the gateway.
* @param p2SVpnGatewayParameters Parameters supplied to create or Update a virtual wan p2s vpn
* gateway.
* @param options The options parameters.
*/
beginCreateOrUpdate(
resourceGroupName: string,
gatewayName: string,
p2SVpnGatewayParameters: P2SVpnGateway,
options?: P2SVpnGatewaysCreateOrUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<P2SVpnGatewaysCreateOrUpdateResponse>,
P2SVpnGatewaysCreateOrUpdateResponse
>
>;
/**
* Creates a virtual wan p2s vpn gateway if it doesn't exist else updates the existing gateway.
* @param resourceGroupName The resource group name of the P2SVpnGateway.
* @param gatewayName The name of the gateway.
* @param p2SVpnGatewayParameters Parameters supplied to create or Update a virtual wan p2s vpn
* gateway.
* @param options The options parameters.
*/
beginCreateOrUpdateAndWait(
resourceGroupName: string,
gatewayName: string,
p2SVpnGatewayParameters: P2SVpnGateway,
options?: P2SVpnGatewaysCreateOrUpdateOptionalParams
): Promise<P2SVpnGatewaysCreateOrUpdateResponse>;
/**
* Updates virtual wan p2s vpn gateway tags.
* @param resourceGroupName The resource group name of the P2SVpnGateway.
* @param gatewayName The name of the gateway.
* @param p2SVpnGatewayParameters Parameters supplied to update a virtual wan p2s vpn gateway tags.
* @param options The options parameters.
*/
updateTags(
resourceGroupName: string,
gatewayName: string,
p2SVpnGatewayParameters: TagsObject,
options?: P2SVpnGatewaysUpdateTagsOptionalParams
): Promise<P2SVpnGatewaysUpdateTagsResponse>;
/**
* Deletes a virtual wan p2s vpn gateway.
* @param resourceGroupName The resource group name of the P2SVpnGateway.
* @param gatewayName The name of the gateway.
* @param options The options parameters.
*/
beginDelete(
resourceGroupName: string,
gatewayName: string,
options?: P2SVpnGatewaysDeleteOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes a virtual wan p2s vpn gateway.
* @param resourceGroupName The resource group name of the P2SVpnGateway.
* @param gatewayName The name of the gateway.
* @param options The options parameters.
*/
beginDeleteAndWait(
resourceGroupName: string,
gatewayName: string,
options?: P2SVpnGatewaysDeleteOptionalParams
): Promise<void>;
/**
* Generates VPN profile for P2S client of the P2SVpnGateway in the specified resource group.
* @param resourceGroupName The name of the resource group.
* @param gatewayName The name of the P2SVpnGateway.
* @param parameters Parameters supplied to the generate P2SVpnGateway VPN client package operation.
* @param options The options parameters.
*/
beginGenerateVpnProfile(
resourceGroupName: string,
gatewayName: string,
parameters: P2SVpnProfileParameters,
options?: P2SVpnGatewaysGenerateVpnProfileOptionalParams
): Promise<
PollerLike<
PollOperationState<P2SVpnGatewaysGenerateVpnProfileResponse>,
P2SVpnGatewaysGenerateVpnProfileResponse
>
>;
/**
* Generates VPN profile for P2S client of the P2SVpnGateway in the specified resource group.
* @param resourceGroupName The name of the resource group.
* @param gatewayName The name of the P2SVpnGateway.
* @param parameters Parameters supplied to the generate P2SVpnGateway VPN client package operation.
* @param options The options parameters.
*/
beginGenerateVpnProfileAndWait(
resourceGroupName: string,
gatewayName: string,
parameters: P2SVpnProfileParameters,
options?: P2SVpnGatewaysGenerateVpnProfileOptionalParams
): Promise<P2SVpnGatewaysGenerateVpnProfileResponse>;
/**
* Gets the connection health of P2S clients of the virtual wan P2SVpnGateway in the specified resource
* group.
* @param resourceGroupName The name of the resource group.
* @param gatewayName The name of the P2SVpnGateway.
* @param options The options parameters.
*/
beginGetP2SVpnConnectionHealth(
resourceGroupName: string,
gatewayName: string,
options?: P2SVpnGatewaysGetP2SVpnConnectionHealthOptionalParams
): Promise<
PollerLike<
PollOperationState<P2SVpnGatewaysGetP2SVpnConnectionHealthResponse>,
P2SVpnGatewaysGetP2SVpnConnectionHealthResponse
>
>;
/**
* Gets the connection health of P2S clients of the virtual wan P2SVpnGateway in the specified resource
* group.
* @param resourceGroupName The name of the resource group.
* @param gatewayName The name of the P2SVpnGateway.
* @param options The options parameters.
*/
beginGetP2SVpnConnectionHealthAndWait(
resourceGroupName: string,
gatewayName: string,
options?: P2SVpnGatewaysGetP2SVpnConnectionHealthOptionalParams
): Promise<P2SVpnGatewaysGetP2SVpnConnectionHealthResponse>;
/**
* Gets the sas url to get the connection health detail of P2S clients of the virtual wan P2SVpnGateway
* in the specified resource group.
* @param resourceGroupName The name of the resource group.
* @param gatewayName The name of the P2SVpnGateway.
* @param request Request parameters supplied to get p2s vpn connections detailed health.
* @param options The options parameters.
*/
beginGetP2SVpnConnectionHealthDetailed(
resourceGroupName: string,
gatewayName: string,
request: P2SVpnConnectionHealthRequest,
options?: P2SVpnGatewaysGetP2SVpnConnectionHealthDetailedOptionalParams
): Promise<
PollerLike<
PollOperationState<
P2SVpnGatewaysGetP2SVpnConnectionHealthDetailedResponse
>,
P2SVpnGatewaysGetP2SVpnConnectionHealthDetailedResponse
>
>;
/**
* Gets the sas url to get the connection health detail of P2S clients of the virtual wan P2SVpnGateway
* in the specified resource group.
* @param resourceGroupName The name of the resource group.
* @param gatewayName The name of the P2SVpnGateway.
* @param request Request parameters supplied to get p2s vpn connections detailed health.
* @param options The options parameters.
*/
beginGetP2SVpnConnectionHealthDetailedAndWait(
resourceGroupName: string,
gatewayName: string,
request: P2SVpnConnectionHealthRequest,
options?: P2SVpnGatewaysGetP2SVpnConnectionHealthDetailedOptionalParams
): Promise<P2SVpnGatewaysGetP2SVpnConnectionHealthDetailedResponse>;
/**
* Disconnect P2S vpn connections of the virtual wan P2SVpnGateway in the specified resource group.
* @param resourceGroupName The name of the resource group.
* @param p2SVpnGatewayName The name of the P2S Vpn Gateway.
* @param request The parameters are supplied to disconnect p2s vpn connections.
* @param options The options parameters.
*/
beginDisconnectP2SVpnConnections(
resourceGroupName: string,
p2SVpnGatewayName: string,
request: P2SVpnConnectionRequest,
options?: P2SVpnGatewaysDisconnectP2SVpnConnectionsOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Disconnect P2S vpn connections of the virtual wan P2SVpnGateway in the specified resource group.
* @param resourceGroupName The name of the resource group.
* @param p2SVpnGatewayName The name of the P2S Vpn Gateway.
* @param request The parameters are supplied to disconnect p2s vpn connections.
* @param options The options parameters.
*/
beginDisconnectP2SVpnConnectionsAndWait(
resourceGroupName: string,
p2SVpnGatewayName: string,
request: P2SVpnConnectionRequest,
options?: P2SVpnGatewaysDisconnectP2SVpnConnectionsOptionalParams
): Promise<void>;
} | the_stack |
import order from './order';
/**
* Builds and returns mongo sort object for specific querystring fields.
* Checks sort order from the order param, then checks if the sort param
* contains any of the following fields. If so, they are added to an object
* compatiable with the sort fields in a mongo query
* @param {Object} request Koa request object from ctx
* @return {Object} Mongo compatible sort object
*/
export default r => {
const query: any = {};
const direction = order(r.query);
if ('sort' in r.query) {
if (r.collection === 'launch') {
//------------------------------------------------------------
// Launch Fields
//------------------------------------------------------------
if (r.query.sort === 'flight_id') {
// Mongo _id field requires underscore dangle
// eslint-disable-next-line no-underscore-dangle
query._id = direction;
}
if (r.query.sort === 'flight_number') {
query.flight_number = direction;
}
if (r.query.sort === 'mission_name') {
query.mission_name = direction;
}
if (r.query.sort === 'mission_id') {
query.mission_id = direction;
}
if (r.query.sort === 'launch_year') {
query.launch_year = direction;
}
if (r.query.sort === 'launch_date_utc') {
query.launch_date_utc = direction;
}
if (r.query.sort === 'launch_date_local') {
query.launch_date_local = direction;
}
if (r.query.sort === 'tentative') {
query.is_tentative = direction;
}
if (r.query.sort === 'tentative_max_precision') {
query.tentative_max_precision = direction;
}
if (r.query.sort === 'tbd') {
query.tbd = direction;
}
if (r.query.sort === 'rocket_id') {
query['rocket.rocket_id'] = direction;
}
if (r.query.sort === 'rocket_name') {
query['rocket.rocket_name'] = direction;
}
if (r.query.sort === 'rocket_type') {
query['rocket.rocket_type'] = direction;
}
if (r.query.sort === 'core_serial') {
query['rocket.first_stage.cores.core_serial'] = direction;
}
if (r.query.sort === 'cap_serial') {
query['rocket.second_stage.payloads.cap_serial'] = direction;
}
if (r.query.sort === 'core_flight') {
query['rocket.first_stage.cores.flight'] = direction;
}
if (r.query.sort === 'block') {
query['rocket.first_stage.cores.block'] = direction;
}
if (r.query.sort === 'gridfins') {
query['rocket.first_stage.cores.gridfins'] = direction;
}
if (r.query.sort === 'legs') {
query['rocket.first_stage.cores.legs'] = direction;
}
if (r.query.sort === 'second_stage_block') {
query['rocket.second_stage.block'] = direction;
}
if (r.query.sort === 'core_reuse') {
query['reuse.core'] = direction;
}
if (r.query.sort === 'side_core1_reuse') {
query['reuse.side_core1'] = direction;
}
if (r.query.sort === 'side_core2_reuse') {
query['reuse.side_core2'] = direction;
}
if (r.query.sort === 'fairings_reuse') {
query['reuse.fairings'] = direction;
}
if (r.query.sort === 'capsule_reuse') {
query['reuse.capsule'] = direction;
}
if (r.query.sort === 'site_id') {
query['launch_site.site_id'] = direction;
}
if (r.query.sort === 'site_name') {
query['launch_site.site_name'] = direction;
}
if (r.query.sort === 'site_name_long') {
query['launch_site.site_name_long'] = direction;
}
if (r.query.sort === 'payload_id') {
query['rocket.second_stage.payloads.payload_id'] = direction;
}
if (r.query.sort === 'norad_id') {
query['rocket.second_stage.payloads.norad_id'] = direction;
}
if (r.query.sort === 'customer') {
query['rocket.second_stage.payloads.customers'] = direction;
}
if (r.query.sort === 'nationality') {
query['rocket.second_stage.payloads.nationality'] = direction;
}
if (r.query.sort === 'manufacturer') {
query['rocket.second_stage.payloads.manufacturer'] = direction;
}
if (r.query.sort === 'payload_type') {
query['rocket.second_stage.payloads.payload_type'] = direction;
}
if (r.query.sort === 'orbit') {
query['rocket.second_stage.payloads.orbit'] = direction;
}
if (r.query.sort === 'reference_system') {
query[
'rocket.second_stage.payloads.orbit_params.reference_system'
] = direction;
}
if (r.query.sort === 'regime') {
query['rocket.second_stage.payloads.orbit_params.regime'] = direction;
}
if (r.query.sort === 'longitude') {
query[
'rocket.second_stage.payloads.orbit_params.longitude'
] = direction;
}
if (r.query.sort === 'semi_major_axis_km') {
query[
'rocket.second_stage.payloads.orbit_params.semi_major_axis_km'
] = direction;
}
if (r.query.sort === 'eccentricity') {
query[
'rocket.second_stage.payloads.orbit_params.eccentricity'
] = direction;
}
if (r.query.sort === 'periapsis_km') {
query[
'rocket.second_stage.payloads.orbit_params.periapsis_km'
] = direction;
}
if (r.query.sort === 'apoapsis_km') {
query[
'rocket.second_stage.payloads.orbit_params.apoapsis_km'
] = direction;
}
if (r.query.sort === 'inclination_deg') {
query[
'rocket.second_stage.payloads.orbit_params.inclination_deg'
] = direction;
}
if (r.query.sort === 'period_min') {
query[
'rocket.second_stage.payloads.orbit_params.period_min'
] = direction;
}
if (r.query.sort === 'lifespan_years') {
query[
'rocket.second_stage.payloads.orbit_params.lifespan_years'
] = direction;
}
if (r.query.sort === 'epoch') {
query['rocket.second_stage.payloads.orbit_params.epoch'] = direction;
}
if (r.query.sort === 'mean_motion') {
query[
'rocket.second_stage.payloads.orbit_params.mean_motion'
] = direction;
}
if (r.query.sort === 'raan') {
query['rocket.second_stage.payloads.orbit_params.raan'] = direction;
}
if (r.query.sort === 'fairings_reused') {
query['rocket.fairings.reused'] = direction;
}
if (r.query.sort === 'fairings_recovery_attempt') {
query['rocket.fairings.recovery_attempt'] = direction;
}
if (r.query.sort === 'fairings_recovered') {
query['rocket.fairings.recovered'] = direction;
}
if (r.query.sort === 'fairings_ship') {
query['rocket.fairings.ship'] = direction;
}
if (r.query.sort === 'launch_success') {
query.launch_success = direction;
}
if (r.query.sort === 'reused') {
query['rocket.first_stage.cores.reused'] = direction;
}
if (r.query.sort === 'land_success') {
query['rocket.first_stage.cores.land_success'] = direction;
}
if (r.query.sort === 'landing_intent') {
query['rocket.first_stage.cores.landing_intent'] = direction;
}
if (r.query.sort === 'landing_type') {
query['rocket.first_stage.cores.landing_type'] = direction;
}
if (r.query.sort === 'landing_vehicle') {
query['rocket.first_stage.cores.landing_vehicle'] = direction;
}
if (r.query.sort === 'ship') {
query.ships = direction;
}
} else if (r.collection === 'capsule') {
//------------------------------------------------------------
// Capsule Fields
//------------------------------------------------------------
if (r.query.sort === 'capsule_serial') {
query.capsule_serial = direction;
}
if (r.query.sort === 'capsule_id') {
query.capsule_id = direction;
}
if (r.query.sort === 'status') {
query.status = direction;
}
if (r.query.sort === 'original_launch') {
query.original_launch = direction;
}
if (r.query.sort === 'landings') {
query.landings = direction;
}
if (r.query.sort === 'type') {
query.type = direction;
}
if (r.query.sort === 'reuse_count') {
query.reuse_count = direction;
}
} else if (r.collection === 'core') {
//------------------------------------------------------------
// Core Fields
//------------------------------------------------------------
if (r.query.sort === 'core_serial') {
query.core_serial = direction;
}
if (r.query.sort === 'block') {
query.block = direction;
}
if (r.query.sort === 'status') {
query.status = direction;
}
if (r.query.sort === 'original_launch') {
query.original_launch = direction;
}
if (r.query.sort === 'reuse_count') {
query.reuse_count = direction;
}
if (r.query.sort === 'rtls_attempts') {
query.rtls_attempts = direction;
}
if (r.query.sort === 'rtls_landings') {
query.rtls_landings = direction;
}
if (r.query.sort === 'asds_attempts') {
query.asds_attempts = direction;
}
if (r.query.sort === 'asds_landings') {
query.asds_landings = direction;
}
if (r.query.sort === 'water_landing') {
query.water_landing = direction;
}
} else if (r.collection === 'history') {
//------------------------------------------------------------
// History Fields
//------------------------------------------------------------
if (r.query.sort === 'event_date_utc') {
query.event_date_utc = direction;
}
if (r.query.sort === 'flight_number') {
query.flight_number = direction;
}
} else if (r.collection === 'ship') {
//------------------------------------------------------------
// Ships Fields
//------------------------------------------------------------
if (r.query.sort === 'ship_id') {
query.ship_id = direction;
}
if (r.query.sort === 'ship_name') {
query.ship_name = direction;
}
if (r.query.sort === 'ship_model') {
query.ship_model = direction;
}
if (r.query.sort === 'roles') {
query.roles = direction;
}
if (r.query.sort === 'active') {
query.active = direction;
}
if (r.query.sort === 'imo') {
query.imo = direction;
}
if (r.query.sort === 'mmsi') {
query.mmsi = direction;
}
if (r.query.sort === 'abs') {
query.abs = direction;
}
if (r.query.sort === 'class') {
query.class = direction;
}
if (r.query.sort === 'weight_lbs') {
query.weight_lbs = direction;
}
if (r.query.sort === 'weight_kg') {
query.weight_kg = direction;
}
if (r.query.sort === 'year_built') {
query.year_built = direction;
}
if (r.query.sort === 'home_port') {
query.home_port = direction;
}
if (r.query.sort === 'status') {
query.status = direction;
}
if (r.query.sort === 'speed_kn') {
query.speed_kn = direction;
}
if (r.query.sort === 'course_deg') {
query.course_deg = direction;
}
if (r.query.sort === 'latitude') {
query['position.latitude'] = direction;
}
if (r.query.sort === 'longitude') {
query['position.longitude'] = direction;
}
if (r.query.sort === 'successful_landings') {
query.successful_landings = direction;
}
if (r.query.sort === 'attempted_landings') {
query.attempted_landings = direction;
}
if (r.query.sort === 'missions') {
query.missions = direction;
}
}
// Set sensible defaults for endpoint to sort on if no sort or order param is passed in the url
} else if (r.collection === 'launch') {
query.flight_number = direction;
} else if (r.collection === 'history') {
query.event_date_utc = direction;
} else if (r.collection === 'capsule') {
query.original_launch = direction;
query.capsule_serial = direction;
} else if (r.collection === 'core') {
query.original_launch = direction;
query.core_serial = direction;
} else if (r.collection === 'ship') {
query.ship_id = direction;
}
return query;
}; | the_stack |
import DMP from '../../../lib/sdkdriver/src/dmp';
import {
add,
remove
} from './resources';
import {
serializeLocalParticipant,
serializeLocalTrack,
serializeLocalTrackPublication,
serializeParticipant,
serializeRemoteTrack,
serializeRoom
} from './serialize';
/**
* Send {@link MediaTrack} events to the {@link SDKDriver}.
* @param {DMP} dmp
* @param {MediaTrack} mediaTrack
* @param {(mediaTrack: any) => any} serializeMediaTrack
* @returns {void}
*/
function sendMediaTrackEvents(dmp: DMP, mediaTrack: any, serializeMediaTrack: (mediaTrack: any) => any): void {
['disabled', 'enabled', 'started'].forEach((event: string) => {
mediaTrack.on(event, () => {
dmp.sendEvent({
source: serializeMediaTrack(mediaTrack),
type: event
});
});
});
}
/**
* Send {@link LocalMediaTrack} events to the {@link SDKDriver}
* @param {DMP} dmp
* @param {LocalMediaTrack} localMediaTrack
* @returns {void}
*/
function sendLocalMediaTrackEvents(dmp: DMP, localMediaTrack: any): void {
sendMediaTrackEvents(dmp, localMediaTrack, serializeLocalTrack);
localMediaTrack.on('stopped', () => {
dmp.sendEvent({
source: serializeLocalTrack(localMediaTrack),
type: 'stopped'
});
});
}
/**
* Send {@link RemoteDataTrack} events to the {@link SDKDriver}.
* @param {DMP} dmp
* @param {RemoteDataTrack} remoteDataTrack
* @returns {void}
*/
function sendRemoteDataTrackEvents(dmp: DMP, remoteDataTrack: any): void {
remoteDataTrack.on('message', (data: string) => {
dmp.sendEvent({
args: [data],
source: serializeRemoteTrack(remoteDataTrack),
type: 'message'
});
});
}
/**
* Send {@link RemoteTrack} events to the {@link SDKDriver}.
* @param {DMP} dmp
* @param {RemoteTrack} remoteTrack
* @returns {void}
*/
function sendRemoteTrackEvents(dmp: DMP, remoteTrack: any): void {
add(remoteTrack);
if (remoteTrack.kind === 'data') {
sendRemoteDataTrackEvents(dmp, remoteTrack);
} else {
sendMediaTrackEvents(dmp, remoteTrack, serializeRemoteTrack);
}
remoteTrack.on('unsubscribed', () => {
dmp.sendEvent({
source: serializeRemoteTrack(remoteTrack),
type: 'unsubscribed'
});
});
}
/**
* Send {@link LocalParticipant} events to the {@link SDKDriver}.
* @param {DMP} dmp
* @param {LocalParticipant} localParticipant
* @returns {void}
*/
function sendLocalParticipantEvents(dmp: DMP, localParticipant: any): void {
add(localParticipant);
localParticipant.tracks.forEach((track: any) => {
sendLocalTrackEvents(dmp, track);
});
localParticipant.on('trackAdded', (track: any) => {
sendLocalTrackEvents(dmp, track);
dmp.sendEvent({
args: [serializeLocalTrack(track)],
source: serializeLocalParticipant(localParticipant),
type: 'trackAdded'
});
});
localParticipant.on('trackPublicationFailed', (error: any, track: any) => {
const { code, message } = error;
dmp.sendEvent({
args: [{ code, message }, serializeLocalTrack(track)],
source: serializeLocalParticipant(localParticipant),
type: 'trackPublicationFailed'
});
});
localParticipant.on('trackPublished', (publication: any) => {
add(publication);
dmp.sendEvent({
args: [serializeLocalTrackPublication(publication)],
source: serializeLocalParticipant(localParticipant),
type: 'trackPublished'
});
});
localParticipant.on('trackRemoved', (track: any) => {
dmp.sendEvent({
args: [serializeLocalTrack(track)],
source: serializeLocalParticipant(localParticipant),
type: 'trackRemoved'
});
});
}
/**
* Send {@link RemoteParticipant} events to the {@link SDKDriver}.
* @param {DMP} dmp
* @param {RemoteParticipant} participant
* @returns {void}
*/
function sendParticipantEvents(dmp: DMP, participant: any): void {
add(participant);
participant.tracks.forEach((track: any) => {
sendRemoteTrackEvents(dmp, track);
});
participant.on('disconnected', () => {
dmp.sendEvent({
source: serializeParticipant(participant),
type: 'disconnected'
});
});
participant.on('trackAdded', (track: any) => {
sendRemoteTrackEvents(dmp, track);
dmp.sendEvent({
args: [serializeRemoteTrack(track)],
source: serializeParticipant(participant),
type: 'trackAdded'
});
});
participant.on('trackDisabled', (track: any) => {
dmp.sendEvent({
args: [serializeRemoteTrack(track)],
source: serializeParticipant(participant),
type: 'trackDisabled'
});
});
participant.on('trackEnabled', (track: any) => {
dmp.sendEvent({
args: [serializeRemoteTrack(track)],
source: serializeParticipant(participant),
type: 'trackEnabled'
});
});
participant.on('trackMessage', (data: string, track: any) => {
dmp.sendEvent({
args: [data, serializeRemoteTrack(track)],
source: serializeParticipant(participant),
type: 'trackMessage'
});
});
participant.on('trackRemoved', (track: any) => {
dmp.sendEvent({
args: [serializeRemoteTrack(track)],
source: serializeParticipant(participant),
type: 'trackRemoved'
});
});
participant.on('trackStarted', (track: any) => {
dmp.sendEvent({
args: [serializeRemoteTrack(track)],
source: serializeParticipant(participant),
type: 'trackStarted'
});
});
participant.on('trackSubscribed', (track: any) => {
dmp.sendEvent({
args: [serializeRemoteTrack(track)],
source: serializeParticipant(participant),
type: 'trackSubscribed'
});
});
participant.on('trackUnsubscribed', (track: any) => {
dmp.sendEvent({
args: [serializeRemoteTrack(track)],
source: serializeParticipant(participant),
type: 'trackUnsubscribed'
});
});
}
/**
* Send {@link LocalTrack} events to the {@link SDKDriver}.
* @param {DMP} dmp
* @param {LocalTrack} localTrack
* @returns {void}
*/
export function sendLocalTrackEvents(dmp: DMP, localTrack: any): void {
add(localTrack);
if (localTrack.kind !== 'data') {
sendLocalMediaTrackEvents(dmp, localTrack);
}
}
/**
* Send {@link Room} events to the {@link SDKDriver}.
* @param {DMP} dmp
* @param {Room} room
* @returns {void}
*/
export function sendRoomEvents(dmp: DMP, room: any): void {
add(room);
sendLocalParticipantEvents(dmp, room.localParticipant);
room.participants.forEach((participant: any) => {
sendParticipantEvents(dmp, participant);
});
room.on('disconnected', (room: any, error: any) => {
const serializedError = error ? {
code: error.code,
message: error.message
} : null;
const serializedRoom = serializeRoom(room);
dmp.sendEvent({
args: [serializedRoom, serializedError],
source: serializedRoom,
type: 'disconnected'
});
room.participants.forEach((participant: any) => {
participant.tracks.forEach(remove);
remove(participant);
});
room.localParticipant.tracks.forEach(remove);
remove(room.localParticipant);
remove(room);
});
room.on('participantConnected', (participant: any) => {
sendParticipantEvents(dmp, participant);
dmp.sendEvent({
args: [serializeParticipant(participant)],
source: serializeRoom(room),
type: 'participantConnected'
});
});
room.on('participantDisconnected', (participant: any) => {
dmp.sendEvent({
args: [serializeParticipant(participant)],
source: serializeRoom(room),
type: 'participantDisconnected'
});
participant.tracks.forEach(remove);
remove(participant);
});
room.on('recordingStarted', () => {
const serializedRoom = serializeRoom(room);
dmp.sendEvent({
args: [serializedRoom],
source: serializedRoom,
type: 'recordingStarted'
});
});
room.on('recordingStopped', () => {
const serializedRoom = serializeRoom(room);
dmp.sendEvent({
args: [serializedRoom],
source: serializedRoom,
type: 'recordingStopped'
});
});
room.on('trackAdded', (track: any, participant: any) => {
dmp.sendEvent({
args: [serializeRemoteTrack(track), serializeParticipant(participant)],
source: serializeRoom(room),
type: 'trackAdded'
});
});
room.on('trackDisabled', (track: any, participant: any) => {
dmp.sendEvent({
args: [serializeRemoteTrack(track), serializeParticipant(participant)],
source: serializeRoom(room),
type: 'trackDisabled'
});
});
room.on('trackEnabled', (track: any, participant: any) => {
dmp.sendEvent({
args: [serializeRemoteTrack(track), serializeParticipant(participant)],
source: serializeRoom(room),
type: 'trackEnabled'
});
});
room.on('trackMessage', (data: string, track: any, participant: any) => {
dmp.sendEvent({
args: [data, serializeRemoteTrack(track), serializeParticipant(participant)],
source: serializeRoom(room),
type: 'trackMessage'
});
});
room.on('trackRemoved', (track: any, participant: any) => {
dmp.sendEvent({
args: [serializeRemoteTrack(track), serializeParticipant(participant)],
source: serializeRoom(room),
type: 'trackRemoved'
});
remove(track);
});
room.on('trackStarted', (track: any, participant: any) => {
dmp.sendEvent({
args: [serializeRemoteTrack(track), serializeParticipant(participant)],
source: serializeRoom(room),
type: 'trackStarted'
});
});
room.on('trackSubscribed', (track: any, participant: any) => {
dmp.sendEvent({
args: [serializeRemoteTrack(track), serializeParticipant(participant)],
source: serializeRoom(room),
type: 'trackSubscribed'
});
});
room.on('trackUnsubscribed', (track: any, participant: any) => {
dmp.sendEvent({
args: [serializeRemoteTrack(track), serializeParticipant(participant)],
source: serializeRoom(room),
type: 'trackUnsubscribed'
});
});
} | the_stack |
import * as bigInt from 'big-integer';
import { Buffer } from 'buffer';
import * as ConvertBase from 'convert-base';
import * as crypto from 'crypto';
import * as pad from 'pad-component';
import { from, mergeMap, Observable, of, throwError } from 'rxjs';
import { defaultIfEmpty, filter, map, take } from 'rxjs/operators';
import {
HOTPGenerateOptions,
HOTPGenerateValidatedData,
HOTPVerifyOptions,
HOTPVerifyValidatedData,
OTPVerifyResult,
} from '../schemas/interfaces';
import { Validator } from '../schemas/validator';
const converter = new ConvertBase();
/**
* HOTP class definition
*/
export class HOTP {
// 0 1 2 3 4 5 6 7 8 9 10
// @internal
private static DIGITS_POWER: number[] = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000];
// These are used to calculate the check-sum digits.
// @internal
private static DOUBLE_DIGITS: number[] = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];
/**
* Generates HOTP
*
* @param {string} key - Key for the one time password. This should be unique and secret for every user as this is the seed
* that is used to calculate the HMAC. Format can be ASCII or HEX.
* @param {HOTPGenerateOptions} options - Object options could contain:
*
* - {@code key_format} - The format of the key which can be `str` for an ASCII string
* or `hex` for a hexadecimal string - default `str`
*
* - {@code counter} - counter value. This should be stored by the application, must
* be user specific, and be incremented for each request - default `0`
*
* - {@code counter_format} - The format of the counter which can be `int` for a number
* or `hex` for a hexadecimal string - default `int`
*
* - {@code code_digits} - The number of digits in the OTP, not including the checksum, if any - default `6`
*
* - {@code add_checksum} - A flag indicates if a checksum digit should be appended to the OTP - default `false`
*
* - {@code truncation_offset} - the offset into the MAC result to begin truncation - default `-1`
*
* - {@code algorithm} - The algorithm to create HMAC: 'SHA1' | 'SHA256' | 'SHA512' - default 'SHA512'
*
* @returns {Observable<string>} - A numeric string in base 10 includes code_digits plus the optional checksum digit if requested.
*/
static generate = (key: string, options: HOTPGenerateOptions = {}): Observable<string> =>
of(
{ ...options, key }
)
.pipe(
mergeMap((data: HOTPGenerateValidatedData) =>
Validator.validateDataWithSchemaReference('/rx-otp/schemas/hotp-generate.json', data)
),
map((_: HOTPGenerateValidatedData) =>
({
key: _.key_format === 'str' ?
Buffer.from(_.key) :
Buffer.from(_.key, 'hex'),
counter: _.counter_format === 'int' ?
Buffer.from(pad.left(converter.convert(_.counter, 10, 16), 16, '0'), 'hex') :
Buffer.from(pad.left(_.counter, 16, '0'), 'hex'),
code_digits: _.code_digits,
add_checksum: _.add_checksum,
truncation_offset: _.truncation_offset,
algorithm: _.algorithm
})
),
mergeMap((_: any) =>
HOTP._generateOTP(_.key, _.counter, _.code_digits, _.add_checksum, _.truncation_offset, _.algorithm)
)
);
/**
* Verifies OTP
*
* @param {string} token - Passcode to validate
* @param {string} key - Key for the one time password. This should be unique and secret for every user as this is the seed
* that is used to calculate the HMAC. Format can be ASCII or HEX.
* @param {HOTPVerifyOptions} options - Object options could contain:
*
* - {@code key_format} - The format of the key which can be `str` for an ASCII string
* or `hex` for a hexadecimal string - default `str`
*
* - {@code window} - The allowable margin for the counter. The function will check
* 'W' codes in the future against the provided passcode. Note,
* it is the calling applications responsibility to keep track of
* 'C' and increment it for each password check, and also to adjust
* it accordingly in the case where the client and server become
* out of sync (second argument returns non zero) - default `50`
* E.g. if W = 100, and C = 5, this function will check the passcode
* against all One Time Passcodes between 5 and 105.
*
* - {@code counter} - counter value. This should be stored by the application, must
* be user specific, and be incremented for each request - default `0`
*
* - {@code counter_format} - The format of the counter which can be `int` for a number
* or `hex` for a hexadecimal string - default `int`
*
* - {@code add_checksum} - A flag indicates if a checksum digit should be appended to the OTP - default `false`
*
* - {@code truncation_offset} - the offset into the MAC result to begin truncation - default `-1`
*
* - {@code algorithm} - The algorithm to create HMAC: 'SHA1' | 'SHA256' | 'SHA512' - default 'SHA512'
*
* - {@code previous_otp_allowed} - A flag to allow OTP validation before current counter - default `false`
*
* @returns {Observable<OTPVerifyResult>} - an object {@code {delta: #, delta_format: 'int' | 'hex'},
* following counter format, if the token is valid else throw an exception
*/
static verify = (token: string, key: string, options: HOTPVerifyOptions = {}): Observable<OTPVerifyResult | {}> =>
of(
{ ...options, token, key }
)
.pipe(
mergeMap((data: HOTPVerifyValidatedData) =>
Validator.validateDataWithSchemaReference('/rx-otp/schemas/hotp-verify.json', data)
),
map((_: HOTPVerifyValidatedData) =>
({
token: _.token,
key: _.key_format === 'str' ?
Buffer.from(_.key) :
Buffer.from(_.key, 'hex'),
window: bigInt(_.window),
counter: _.counter_format === 'int' ?
bigInt(_.counter as number) :
bigInt(_.counter as string, 16),
counter_format: _.counter_format,
code_digits: _.token.length,
add_checksum: _.add_checksum,
truncation_offset: _.truncation_offset,
algorithm: _.algorithm,
previous_otp_allowed: _.previous_otp_allowed
})
),
map((_: any) =>
// Now loop through from C to C + W to determine if there is a correct code
Object.assign({}, _, { min: _.counter, max: _.counter.add(_.window) })
),
mergeMap((_: any) =>
of(_)
.pipe(
filter(__ =>
// check if previous_otp_allowed
!!__.previous_otp_allowed
),
map(__ =>
// Now loop through from C - W to C + W to determine if there is a correct code
Object.assign({}, __, { min: __.min.subtract(__.window) })
),
map(__ =>
// check if min < 0
!!__.min.isNegative() ?
// Now loop through from 0 to C + W to determine if there is a correct code
Object.assign({}, __, { min: bigInt() }) :
__
),
defaultIfEmpty(_)
)
),
mergeMap((_: any) =>
new Observable(subscriber => {
let iterator = [];
for (let i = _.min; i.lesserOrEquals(_.max); i = i.next()) {
iterator = iterator.concat(i);
}
const data = { ..._, iterator };
delete data.window;
delete data.min;
delete data.max;
subscriber.next(data);
subscriber.complete();
})
),
mergeMap((_: any) =>
HOTP._verifyWithIteration(_)
)
);
/**
* Calculates the checksum using the credit card algorithm.
* This algorithm has the advantage that it detects any single
* mistyped digit and any single transposition of
* adjacent digits.
*
* @param num the number to calculate the checksum for
* @param digits number of significant places in the number
*
* @returns the checksum of num
*
* @private
* @internal
*/
private static _calcChecksum = (num, digits): number => {
// initialize variables
let doubleDigit = true;
let total = 0;
while (0 < digits--) {
let digit = parseInt(`${num % 10}`);
num /= 10;
if (doubleDigit) {
digit = HOTP.DOUBLE_DIGITS[digit];
}
total += digit;
doubleDigit = !doubleDigit;
}
let result = total % 10;
/* istanbul ignore else */
if (result > 0) {
result = 10 - result;
}
return result;
};
/**
* Function to generate OTP
*
* @param {Buffer} key - Key for the one time password.
*
* @param {Buffer} counter - the counter, time, or other value that
* changes on a per use basis.
*
* @param {number} code_digits - the number of digits in the OTP, not
* including the checksum, if any.
*
* @param {boolean} add_checksum - a flag indicates if a checksum digit
* should be appended to the OTP.
*
* @param {number} truncation_offset - the offset into the MAC result to
* begin truncation.
*
* @param {string} algorithm - the algorithm to create HMAC - default 'SHA512'
*
* @returns A numeric string in base 10 includes code_digits plus the optional checksum digit if requested.
*
* @private
* @internal
*/
private static _generateOTP = (key: Buffer,
counter: Buffer,
code_digits: number,
add_checksum: boolean,
truncation_offset: number,
algorithm: 'SHA1' | 'SHA256' | 'SHA512'): Observable<string> =>
of(
crypto.createHmac(algorithm, key)
)
.pipe(
map(hmac => Buffer.from(hmac.update(counter).digest('hex'), 'hex')),
map(hash =>
({
hash,
offset: ((0 <= truncation_offset) && (truncation_offset < (hash.length - 4))) ?
truncation_offset :
(hash[hash.length - 1] & 0xf)
})
),
map((_: any) =>
((_.hash[_.offset] & 0x7f) << 24) |
((_.hash[_.offset + 1] & 0xff) << 16) |
((_.hash[_.offset + 2] & 0xff) << 8) |
(_.hash[_.offset + 3] & 0xff)
),
map(binary => binary % HOTP.DIGITS_POWER[code_digits]),
map(otp => add_checksum ? ((otp * 10) + HOTP._calcChecksum(otp, code_digits)) : otp),
map(otp => ({ result: otp.toString(), digits: add_checksum ? (code_digits + 1) : code_digits })),
map((_: any) => pad.left(_.result, _.digits, '0'))
);
/**
* Iterates and validates token for given parameters
*
* @param data - All parameters and iterator to verify the token
*
* @private
* @internal
*/
private static _verifyWithIteration = (data: any): Observable<OTPVerifyResult | {}> =>
from(data.iterator)
.pipe(
mergeMap((i: any) =>
of({
key: data.key,
counter: data.counter_format === 'int' ?
Buffer.from(pad.left(converter.convert(parseInt(i.toString()), 10, 16), 16, '0'), 'hex') :
Buffer.from(pad.left(i.toString(16).toUpperCase(), 16, '0'), 'hex'),
code_digits: data.code_digits,
add_checksum: data.add_checksum,
truncation_offset: data.truncation_offset,
algorithm: data.algorithm
})
.pipe(
mergeMap((params: any) =>
HOTP._generateOTP(
params.key,
params.counter,
params.code_digits,
params.add_checksum,
params.truncation_offset,
params.algorithm
)
),
map(_ => ({ token: _, it: i }))
)
),
// We have found a matching code, trigger callback and pass offset
filter(_ => _.token === data.token),
take(1),
map(_ => _.it),
// get delta
map(_ => _.subtract(data.counter)),
mergeMap((delta: any) =>
of(data.counter_format)
.pipe(
// delta in hexadecimal
filter(_ => _ === 'hex'),
map(() =>
({
// check if value < 0 to add good pad left
delta: delta.isNegative() ?
`-${pad.left(delta.toString(16).toUpperCase().substr(1), 16, '0')}` :
pad.left(delta.toString(16).toUpperCase(), 16, '0'),
delta_format: 'hex'
})
),
// delta in integer
defaultIfEmpty({
delta: parseInt(delta.toString()),
delta_format: 'int'
} as OTPVerifyResult)
)
),
defaultIfEmpty(undefined),
// If we are here then no codes have matched, throw error
mergeMap(_ =>
!!_ ?
of(_) :
throwError(() => new Error(`The token '${data.token}' doesn't match for the given parameters`))
)
);
} | the_stack |
import * as crypto from "crypto-js";
import { BundleManager } from "../bundleManager";
import { InstanceManager } from "../instanceManager";
import { decryptData, EncryptedData, PersistenceManager, PersistentData } from "../persistenceManager";
import { ServiceManager } from "../serviceManager";
import { ServiceProvider } from "../serviceProvider";
import { emptySuccess, error } from "../utils/result";
import { MockNodeCG, testBundle, testInstance, testService, testServiceInstance } from "./mocks";
describe("PersistenceManager", () => {
const validPassword = "myPassword";
const invalidPassword = "someOtherPassword";
const nodecg = new MockNodeCG();
const serviceManager = new ServiceManager(nodecg);
serviceManager.registerService(testService);
let bundleManager: BundleManager;
let instanceManager: InstanceManager;
const encryptedDataReplicant = nodecg.Replicant<EncryptedData>("encryptedConfig");
let persistenceManager: PersistenceManager;
beforeEach(() => {
encryptedDataReplicant.removeAllListeners();
encryptedDataReplicant.value = {};
bundleManager = new BundleManager(nodecg);
bundleManager.registerServiceDependency(testBundle, testService); // Would be done by a bundle at startup
instanceManager = new InstanceManager(nodecg, serviceManager, bundleManager);
persistenceManager = new PersistenceManager(nodecg, serviceManager, instanceManager, bundleManager);
testService.createClient.mockImplementation((cfg) => () => cfg);
nodecg.log.warn.mockReset();
});
/**
* Creates a basic config and encrypts it. Used to check whether load decrypts and more importantly
* restores the same configuration again.
*/
function generateEncryptedConfig(data?: PersistentData) {
const d: PersistentData = data
? data
: {
bundleDependencies: {
[testBundle]: [
{
serviceType: testService.serviceType,
serviceInstance: testInstance,
provider: new ServiceProvider(),
},
],
},
instances: {
[testInstance]: testServiceInstance,
},
};
return crypto.AES.encrypt(JSON.stringify(d), validPassword).toString();
}
describe("checkPassword", () => {
test("should return false if not loaded", () => {
expect(persistenceManager.checkPassword(validPassword)).toBe(false);
});
test("should return false if loaded but password is wrong", async () => {
await persistenceManager.load(validPassword);
expect(persistenceManager.checkPassword(invalidPassword)).toBe(false);
});
test("should return true if loaded and password is correct", async () => {
await persistenceManager.load(validPassword);
expect(persistenceManager.checkPassword(validPassword)).toBe(true);
});
});
describe("isLoaded", () => {
test("should return false if not load was not called before", async () => {
expect(persistenceManager.isLoaded()).toBe(false);
});
test("should return false if load was called but failed", async () => {
encryptedDataReplicant.value.cipherText = generateEncryptedConfig();
const res = await persistenceManager.load(invalidPassword); // Will fail because the password is invalid
expect(res.failed).toBe(true);
expect(persistenceManager.isLoaded()).toBe(false);
});
test("should return true if load was called and succeeded", async () => {
encryptedDataReplicant.value.cipherText = generateEncryptedConfig();
const res = await persistenceManager.load(validPassword); // password is correct, should work
expect(res.failed).toBe(false);
expect(persistenceManager.isLoaded()).toBe(true);
});
});
describe("isFirstStartup", () => {
test("should return true if no encrypted config exists", () => {
encryptedDataReplicant.value.cipherText = undefined; // no config = first startup
expect(persistenceManager.isFirstStartup()).toBe(true);
});
test("should return false if an encrypted config exists", () => {
encryptedDataReplicant.value.cipherText = generateEncryptedConfig(); // config = not a first startup
expect(persistenceManager.isFirstStartup()).toBe(false);
});
});
describe("load", () => {
beforeEach(() => (encryptedDataReplicant.value.cipherText = generateEncryptedConfig()));
// General
test("should error if called after configuration already has been loaded", async () => {
const res1 = await persistenceManager.load(validPassword);
expect(res1.failed).toBe(false);
const res2 = await persistenceManager.load(validPassword);
expect(res2.failed).toBe(true);
if (res2.failed) {
expect(res2.errorMessage).toContain("already been decrypted and loaded");
}
});
test("should save current state if no encrypted config was found", async () => {
const res = await persistenceManager.load(validPassword);
expect(res.failed).toBe(false);
expect(encryptedDataReplicant.value.cipherText).toBeDefined();
});
test("should error if password is wrong", async () => {
const res = await persistenceManager.load(invalidPassword);
expect(res.failed).toBe(true);
if (res.failed) {
expect(res.errorMessage).toContain("Password isn't correct");
}
});
test("should succeed if password is correct", async () => {
const res = await persistenceManager.load(validPassword);
expect(res.failed).toBe(false);
});
// Service instances
test("should load service instances including configuration", async () => {
await persistenceManager.load(validPassword);
const inst = instanceManager.getServiceInstance(testInstance);
expect(inst).toBeDefined();
if (!inst) return;
expect(inst.config).toBe(testServiceInstance.config);
expect(inst.serviceType).toBe(testService.serviceType);
});
test("should log failures when creating service instances", async () => {
encryptedDataReplicant.value.cipherText = generateEncryptedConfig({
instances: {
"": testServiceInstance, // This is invalid because the instance name is empty
},
bundleDependencies: {},
});
await persistenceManager.load(validPassword);
expect(nodecg.log.warn).toHaveBeenCalledTimes(1);
expect(nodecg.log.warn.mock.calls[0][0]).toContain("Couldn't load instance");
expect(nodecg.log.warn.mock.calls[0][0]).toContain("name must not be empty");
});
test("should not set instance config when no config is required", async () => {
testService.requiresNoConfig = true;
await persistenceManager.load(validPassword);
const inst = instanceManager.getServiceInstance(testInstance);
if (!inst) throw new Error("instance was not re-created");
// Makes sure config was not copied from the encrypted data, where it was set
// (only because testService previously required a config).
expect(inst.config).toBe(testService.defaultConfig);
expect(inst.config).not.toBe(testServiceInstance.config);
testService.requiresNoConfig = false;
});
test("should log failures when setting service instance configs", async () => {
const errorMsg = "client error message";
testService.createClient.mockImplementationOnce(() => error(errorMsg));
await persistenceManager.load(validPassword);
// Wait for all previous promises created by loading to settle.
await new Promise((res) => setImmediate(res));
expect(nodecg.log.warn).toHaveBeenCalledTimes(1);
expect(nodecg.log.warn.mock.calls[0][0]).toContain("Couldn't load config");
});
// Service dependency assignments
test("should load service dependency assignments", async () => {
await persistenceManager.load(validPassword);
const deps = bundleManager.getBundleDependencies()[testBundle];
expect(deps).toBeDefined();
if (!deps) return;
expect(deps).toHaveLength(1);
expect(deps[0]?.serviceType).toBe(testService.serviceType);
expect(deps[0]?.serviceInstance).toBe(testInstance);
});
test("should unset service dependencies when the underlying instance was deleted", async () => {
encryptedDataReplicant.value.cipherText = generateEncryptedConfig({
instances: {},
bundleDependencies: {
[testBundle]: [
{
serviceType: testService.serviceType,
serviceInstance: testInstance,
provider: new ServiceProvider(),
},
],
},
});
await persistenceManager.load(validPassword);
const deps = bundleManager.getBundleDependencies()[testBundle];
expect(deps?.[0]).toBeDefined();
expect(deps?.[0]?.serviceInstance).toBeUndefined();
});
test("should support unassigned service dependencies", async () => {
encryptedDataReplicant.value.cipherText = generateEncryptedConfig({
instances: {},
bundleDependencies: {
[testBundle]: [
{
serviceType: testService.serviceType,
serviceInstance: undefined,
provider: new ServiceProvider(),
},
],
},
});
await persistenceManager.load(validPassword);
const deps = bundleManager.getBundleDependencies()[testBundle];
expect(deps?.[0]).toBeDefined();
expect(deps?.[0]?.serviceInstance).toBeUndefined();
});
});
describe("save", () => {
test("should do nothing if framework isn't loaded", () => {
persistenceManager.save();
expect(encryptedDataReplicant.value.cipherText).toBeUndefined();
});
test("should encrypt and save configuration if framework is loaded", async () => {
const res = await persistenceManager.load(validPassword);
expect(res.failed).toBe(false);
instanceManager.createServiceInstance(testService.serviceType, testInstance);
const inst = instanceManager.getServiceInstance(testInstance);
if (!inst) throw new Error("instance was not saved");
bundleManager.setServiceDependency(testBundle, testInstance, inst);
persistenceManager.save();
// Make sure that something got saved
expect(encryptedDataReplicant.value.cipherText).toBeDefined();
expect(typeof encryptedDataReplicant.value.cipherText).toBe("string");
if (!encryptedDataReplicant.value.cipherText) return;
// Decrypt and check that the information that was saved is correct
const data = decryptData(encryptedDataReplicant.value.cipherText, validPassword);
if (data.failed) throw new Error("could not decrypt newly encrypted data");
expect(data.result.instances[testInstance]?.serviceType).toBe(testService.serviceType);
expect(data.result.instances[testInstance]?.config).toBe(testService.defaultConfig);
expect(data.result.bundleDependencies[testBundle]?.[0]?.serviceType).toBe(testService.serviceType);
expect(data.result.bundleDependencies[testBundle]?.[0]?.serviceInstance).toBe(testInstance);
});
});
describe("automatic login", () => {
const nodecgBundleReplicant = nodecg.Replicant("bundles", "nodecg");
async function triggerAutomaticLogin(bundleRepValue?: Array<string>) {
nodecg.log.info.mockReset();
nodecg.log.warn.mockReset();
nodecg.log.error.mockReset();
persistenceManager = new PersistenceManager(nodecg, serviceManager, instanceManager, bundleManager);
persistenceManager.load = jest.fn().mockImplementation(async (password: string) => {
if (password === validPassword) return emptySuccess();
else return error("password invalid");
});
nodecgBundleReplicant.value = bundleRepValue ?? [nodecg.bundleName];
}
afterEach(() => {
nodecg.bundleConfig = {};
nodecgBundleReplicant.removeAllListeners();
});
test("should be disabled when not configured in core bundle config", async () => {
await triggerAutomaticLogin();
expect(persistenceManager.load).not.toHaveBeenCalled();
expect(nodecg.log.info).not.toHaveBeenCalled();
});
test("should be disabled when configured but disabled", async () => {
nodecg.bundleConfig = {
automaticLogin: {
enabled: false,
password: validPassword,
},
};
await triggerAutomaticLogin();
expect(persistenceManager.load).not.toHaveBeenCalled();
// Warning that automatic login is setup.
// Users should remove it from the config if not automatic login is permanently not used.
expect(nodecg.log.warn).toHaveBeenCalled();
});
test("should be enabled when configured and enabled", async () => {
nodecg.bundleConfig = {
automaticLogin: {
enabled: true,
password: validPassword,
},
};
await triggerAutomaticLogin();
expect(persistenceManager.load).toHaveBeenCalled();
expect(nodecg.log.info).toHaveBeenCalled();
expect(nodecg.log.info.mock.calls[0][0]).toContain("automatically login");
});
test("should log success if loading worked", async () => {
nodecg.bundleConfig = {
automaticLogin: {
enabled: true,
password: validPassword,
},
};
await triggerAutomaticLogin();
expect(persistenceManager.load).toHaveBeenCalled();
expect(nodecg.log.info).toHaveBeenCalledTimes(2);
expect(nodecg.log.info.mock.calls[1][0]).toContain("login successful");
});
test("should log error if loading failed", async () => {
nodecg.bundleConfig = {
automaticLogin: {
enabled: true,
password: invalidPassword,
},
};
await triggerAutomaticLogin();
expect(persistenceManager.load).toHaveBeenCalled();
expect(nodecg.log.error).toHaveBeenCalledTimes(1);
expect(nodecg.log.error.mock.calls[0][0]).toContain("Failed to automatically login");
});
test("should not trigger automatic login if nodecg is not finished with loading bundles", async () => {
// If the nodecg.bundles replicant has length 0 nodecg isn't done loading and we should wait till it has a non-zero length.
// Refer to the comment in setupAutomaticLogin for further details.
nodecg.bundleConfig = {
automaticLogin: {
enabled: true,
password: validPassword,
},
};
await triggerAutomaticLogin([]); // Empty array for the nodecg.bundles replicant
expect(persistenceManager.load).not.toHaveBeenCalled();
});
});
test("should automatically save if BundleManager or InstanceManager emit a change event", async () => {
await persistenceManager.load(validPassword); // Set password so that we can save stuff
encryptedDataReplicant.value.cipherText = undefined;
bundleManager.emit("change");
expect(encryptedDataReplicant.value.cipherText).toBeDefined();
encryptedDataReplicant.value.cipherText = undefined;
instanceManager.emit("change");
expect(encryptedDataReplicant.value.cipherText).toBeDefined();
});
}); | the_stack |
import chai, { expect } from 'chai';
import path from 'path';
import { Extensions } from '../../src/constants';
import Helper from '../../src/e2e-helper/e2e-helper';
import * as fixtures from '../../src/fixtures/fixtures';
import { generateRandomStr } from '../../src/utils';
import NpmCiRegistry, { supportNpmCiRegistryTesting } from '../npm-ci-registry';
chai.use(require('chai-fs'));
const assertArrays = require('chai-arrays');
chai.use(assertArrays);
describe('dependency-resolver extension', function () {
let helper: Helper;
this.timeout(0);
before(() => {
helper = new Helper();
});
after(() => {
helper.scopeHelper.destroy();
});
describe('policies changes', function () {
describe('policies added by the user', function () {
let barFooOutput;
let isTypeOutput;
before(() => {
helper.scopeHelper.reInitLocalScopeHarmony();
helper.fixtures.createComponentBarFoo();
helper.fixtures.addComponentBarFooAsDir();
helper.fixtures.createComponentUtilsIsType();
helper.fs.outputFile(path.join('utils', 'is-type.js'), fixtures.isType);
helper.command.addComponent('utils', { i: 'utils/is-type' });
const depResolverConfig = {
policy: {
dependencies: {
'lodash.get': '4.0.0',
},
devDependencies: {
'lodash.words': '4.0.0',
},
peerDependencies: {
'lodash.set': '4.0.0',
},
},
};
helper.extensions.addExtensionToVariant('bar', 'teambit.dependencies/dependency-resolver', depResolverConfig);
barFooOutput = helper.command.showComponentParsed('bar/foo');
isTypeOutput = helper.command.showComponentParsed('utils/is-type');
});
it('should have the updated dependencies for bar/foo', function () {
expect(barFooOutput.packageDependencies).to.have.property('lodash.get', '4.0.0');
expect(barFooOutput.devPackageDependencies).to.have.property('lodash.words', '4.0.0');
expect(barFooOutput.peerPackageDependencies).to.have.property('lodash.set', '4.0.0');
});
it('should not put the dependencies for not configured component', function () {
expect(isTypeOutput.packageDependencies).to.not.have.key('lodash.get');
expect(isTypeOutput.devPackageDependencies).to.not.have.key('lodash.words');
expect(isTypeOutput.peerPackageDependencies).to.not.have.key('lodash.set');
});
});
// TODO: implement once we can extend a specific env with new methods (to apply config changes)
// and maybe to also apply custom compiler which add deps
describe('policies added by an env', function () {
let barFooOutput;
before(() => {
helper.scopeHelper.reInitLocalScopeHarmony();
helper.fixtures.createComponentBarFoo();
helper.fixtures.addComponentBarFooAsDir();
// TODO: use custom env with versions provided from outside in the config by the user
helper.extensions.addExtensionToVariant('bar', 'teambit.react/react', {});
barFooOutput = helper.command.showComponentParsed('bar/foo');
});
it('should have the updated dependencies for bar/foo from the env', function () {
expect(barFooOutput.peerPackageDependencies).to.have.property('react', '^16.8.0 || ^17.0.0');
expect(barFooOutput.devPackageDependencies).to.have.property('@types/react', '^17.0.8');
});
});
describe('policies added by extension', function () {
const EXTENSIONS_BASE_FOLDER = 'extension-add-dependencies';
const config = {};
before(() => {
helper.scopeHelper.reInitLocalScopeHarmony();
helper.fixtures.createComponentBarFoo();
helper.fixtures.addComponentBarFooAsDir();
helper.fixtures.createComponentUtilsIsType();
helper.fs.createFile('utils', 'is-type.js', fixtures.isType);
helper.command.addComponent('utils', { i: 'utils/is-type' });
});
describe('extension that add simple dependency policy', function () {
let barFooOutput;
let isTypeOutput;
before(() => {
helper.fixtures.copyFixtureExtensions(EXTENSIONS_BASE_FOLDER);
helper.command.addComponent(EXTENSIONS_BASE_FOLDER);
helper.npm.installNpmPackage('@teambit/harmony');
helper.extensions.addExtensionToVariant('bar', 'my-scope/extension-add-dependencies', config);
helper.extensions.addExtensionToVariant(EXTENSIONS_BASE_FOLDER, 'teambit.harmony/aspect');
helper.command.install();
helper.command.compile();
barFooOutput = helper.command.showComponentParsed('bar/foo');
isTypeOutput = helper.command.showComponentParsed('utils/is-type');
});
it('should have the updated dependencies for bar/foo', function () {
expect(barFooOutput.packageDependencies).to.have.property('lodash.get', '4.0.0');
expect(barFooOutput.devPackageDependencies).to.have.property('lodash.words', '4.0.0');
expect(barFooOutput.peerPackageDependencies).to.have.property('lodash.set', '4.0.0');
});
it('should not put the dependencies for not configured component', function () {
expect(isTypeOutput.packageDependencies).to.not.have.key('lodash.get');
expect(isTypeOutput.devPackageDependencies).to.not.have.key('lodash.words');
expect(isTypeOutput.peerPackageDependencies).to.not.have.key('lodash.set');
});
});
describe.skip('conflict between few extensions policies', function () {
it.skip('should merge them', function () {});
});
describe.skip('conflict between extension and user policies ', function () {
it.skip('should prefer user config', function () {});
});
});
});
(supportNpmCiRegistryTesting ? describe : describe.skip)('saving dependencies package names', function () {
let npmCiRegistry: NpmCiRegistry;
let randomStr;
before(async () => {
helper.scopeHelper.setNewLocalAndRemoteScopesHarmony();
helper.bitJsonc.setupDefault();
npmCiRegistry = new NpmCiRegistry(helper);
randomStr = generateRandomStr(4); // to avoid publishing the same package every time the test is running
const name = `react.${randomStr}.{name}`;
npmCiRegistry.configureCustomNameInPackageJsonHarmony(name);
helper.fixtures.populateComponents(4);
await npmCiRegistry.init();
helper.command.tagAllComponents();
});
after(() => {
npmCiRegistry.destroy();
});
it('should save the packageName data into the dependencyResolver extension in the model', () => {
const comp2 = helper.command.catComponent('comp2@latest');
const depResolverExt = comp2.extensions.find((e) => e.name === Extensions.dependencyResolver);
expect(depResolverExt).to.be.ok;
expect(depResolverExt.data).to.have.property('dependencies');
// some of the entries are @types/jest, @types/node, @babel/runtime coming from the node env
expect(depResolverExt.data.dependencies).to.have.lengthOf(4);
expect(depResolverExt.data.dependencies[0].componentId.name).to.equal('comp3');
expect(depResolverExt.data.dependencies[0].componentId.version).to.equal('0.0.1');
expect(depResolverExt.data.dependencies[0].packageName).to.equal(`react.${randomStr}.comp3`);
});
describe('exporting the component', () => {
before(() => {
helper.command.export();
});
it('should change the component id to include the scope name', () => {
const comp2 = helper.command.catComponent('comp2@latest');
const depResolverExt = comp2.extensions.find((e) => e.name === Extensions.dependencyResolver);
expect(depResolverExt.data.dependencies[0].componentId.scope).to.equal(helper.scopes.remote);
expect(depResolverExt.data.dependencies[0].componentId.version).to.equal('0.0.1');
expect(depResolverExt.data.dependencies[0].componentId.name).to.equal('comp3');
expect(depResolverExt.data.dependencies[0].packageName).to.equal(`react.${randomStr}.comp3`);
});
});
});
describe('overrides', function () {
// This is the dependency graph that the overrides will modify:
// is-odd 1.0.0
// └─┬ is-number 3.0.0
// └─┬ kind-of 3.2.2
// └── is-buffer 1.1.6
// rimraf 3.0.2
// └─┬ glob 7.2.0
// ├── fs.realpath 1.0.0
// ├─┬ inflight 1.0.6
// │ ├─┬ once 1.4.0
// │ │ └── wrappy 1.0.2
// │ └── wrappy 1.0.2
// ├── inherits 2.0.4
// ├─┬ minimatch 3.0.4
// │ └─┬ brace-expansion 1.1.11
// │ ├── balanced-match 1.0.2
// │ └── concat-map 0.0.1
// ├─┬ once 1.4.0
// │ └── wrappy 1.0.2
// └── path-is-absolute 1.0.1
describe('using Yarn as a package manager', () => {
before(() => {
helper.scopeHelper.reInitLocalScopeHarmony();
helper.extensions.bitJsonc.addKeyValToDependencyResolver('packageManager', 'teambit.dependencies/yarn');
helper.extensions.bitJsonc.addKeyValToDependencyResolver('overrides', {
'is-odd': '1.0.0',
'glob@^7.1.3': '6.0.4',
'inflight>once': '1.3.0',
});
helper.command.install('is-even@0.1.2 rimraf@3.0.2');
});
it('should force a newer version of a subdependency using just the dependency name', function () {
// Without the override, is-odd would be 0.1.2
expect(helper.fixtures.fs.readJsonFile('node_modules/is-odd/package.json').version).to.eq('1.0.0');
});
it('should force a newer version of a subdependency using the dependency name and version', function () {
expect(helper.fixtures.fs.readJsonFile('node_modules/glob/package.json').version).to.eq('6.0.4');
});
it('should not change the version of the package if the parent package does not match the pattern', function () {
expect(helper.fixtures.fs.readJsonFile('node_modules/glob/node_modules/once/package.json').version).to.eq(
'1.4.0'
);
});
it('should change the version of the package if the parent package matches the pattern', function () {
// This gets hoisted from the dependencies of inflight
expect(helper.fixtures.fs.readJsonFile('node_modules/once/package.json').version).to.eq('1.3.0');
});
});
describe('using pnpm as a package manager', () => {
before(() => {
helper.scopeHelper.reInitLocalScopeHarmony();
helper.extensions.bitJsonc.addKeyValToDependencyResolver('packageManager', 'teambit.dependencies/pnpm');
helper.extensions.bitJsonc.addKeyValToDependencyResolver('overrides', {
'is-odd': '1.0.0',
'glob@^7.1.3': '6.0.4',
'inflight>once': '1.3.0',
});
helper.command.install('is-even@0.1.2 rimraf@3.0.2');
});
it('should force a newer version of a subdependency using just the dependency name', function () {
// Without the override, is-odd would be 0.1.2
expect(
helper.fixtures.fs.readJsonFile(
'node_modules/.pnpm/registry.npmjs.org+is-odd@1.0.0/node_modules/is-odd/package.json'
).version
).to.eq('1.0.0');
});
it('should force a newer version of a subdependency using the dependency name and version', function () {
expect(
helper.fixtures.fs.readJsonFile(
'node_modules/.pnpm/registry.npmjs.org+glob@6.0.4/node_modules/glob/package.json'
).version
).to.eq('6.0.4');
});
it('should not change the version of the package if the parent package does not match the pattern', function () {
expect(
helper.fixtures.fs.readJsonFile(
'node_modules/.pnpm/registry.npmjs.org+glob@6.0.4/node_modules/once/package.json'
).version
).to.eq('1.4.0');
});
it('should change the version of the package if the parent package matches the pattern', function () {
expect(
helper.fixtures.fs.readJsonFile(
'node_modules/.pnpm/registry.npmjs.org+inflight@1.0.6/node_modules/once/package.json'
).version
).to.eq('1.3.0');
});
});
});
}); | the_stack |
module goog.math{
/**
* Constructs a 64-bit two's-complement integer, given its low and high 32-bit
* values as *signed* integers. See the from* functions below for more
* convenient ways of constructing Longs.
*
* The internal representation of a long is the two given signed, 32-bit values.
* We use 32-bit pieces because these are the size of integers on which
* Javascript performs bit-operations. For operations like addition and
* multiplication, we split each number into 16-bit pieces, which can easily be
* multiplied within Javascript's floating-point representation without overflow
* or change in sign.
*
* In the algorithms below, we frequently reduce the negative case to the
* positive case by negating the input(s) and then post-processing the result.
* Note that we must ALWAYS check specially whether those values are MIN_VALUE
* (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
* a positive number, it overflows back into a negative). Not handling this
* case would often result in infinite recursion.
*
* @param {number} low The low (signed) 32 bits of the long.
* @param {number} high The high (signed) 32 bits of the long.
* @constructor
*/
export class Long{
/**
* A cache of the Long representations of small integer values.
* @type {!Object}
* @private
*/
private static IntCache_ = {};
/**
* Number used repeated below in calculations. This must appear before the
* first call to any from* function below.
* @type {number}
* @private
*/
private static TWO_PWR_16_DBL_ = 1 << 16;
private static TWO_PWR_24_DBL_ = 1 << 24;
private static TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_;
private static TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2;
private static TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_;
private static TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_;
private static TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2;
private static TWO_PWR_24_ = Long.fromInt(1 << 24);
static ZERO = Long.fromInt(0);
static ONE = Long.fromInt(1);
static NEG_ONE = Long.fromInt(-1);
static MAX_VALUE = Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0);
static MIN_VALUE = Long.fromBits(0, 0x80000000 | 0);
private low_:number;
private high_:number;
/**
* Constructs a 64-bit two's-complement integer, given its low and high 32-bit
* values as *signed* integers. See the from* functions below for more
* convenient ways of constructing Longs.
*
* @param {number} low The low (signed) 32 bits of the long.
* @param {number} high The high (signed) 32 bits of the long.
* @constructor
*/
constructor(low:number, high:number) {
this.low_ = low | 0; // force into 32 signed bits.
this.high_ = high | 0; // force into 32 signed bits.
}
/** @return {number} The value, assuming it is a 32-bit integer. */
toInt():number {
return this.low_;
}
/** @return {number} The closest floating-point representation to this value. */
toNumber():number {
return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned();
}
/**
* @param {number=} opt_radix The radix in which the text should be written.
* @return {string} The textual representation of this value.
* @override
*/
toString(opt_radix:number):string {
var radix = opt_radix || 10;
if (radix < 2 || 36 < radix) {
throw Error('radix out of range: ' + radix);
}
if (this.isZero()) {
return '0';
}
if (this.isNegative()) {
if (this.equals(Long.MIN_VALUE)) {
// We need to change the Long value before it can be negated, so we remove
// the bottom-most digit in this base and then recurse to do the rest.
var radixLong = Long.fromNumber(radix);
var div = this.div(radixLong);
let rem = div.multiply(radixLong).subtract(this);
return div.toString(radix) + rem.toInt().toString(radix);
} else {
return '-' + this.negate().toString(radix);
}
}
// Do several (6) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = Long.fromNumber(Math.pow(radix, 6));
let rem:Long = this;
var result = '';
while (true) {
var remDiv = rem.div(radixToPower);
var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt();
var digits = intval.toString(radix);
rem = remDiv;
if (rem.isZero()) {
return digits + result;
} else {
while (digits.length < 6) {
digits = '0' + digits;
}
result = '' + digits + result;
}
}
}
/** @return {number} The high 32-bits as a signed value. */
getHighBits():number {
return this.high_;
}
/** @return {number} The low 32-bits as a signed value. */
getLowBits():number {
return this.low_;
}
/** @return {number} The low 32-bits as an unsigned value. */
getLowBitsUnsigned():number {
return (this.low_ >= 0) ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_;
}
/**
* @return {number} Returns the number of bits needed to represent the absolute
* value of this Long.
*/
getNumBitsAbs():number {
if (this.isNegative()) {
if (this.equals(Long.MIN_VALUE)) {
return 64;
} else {
return this.negate().getNumBitsAbs();
}
} else {
var val = this.high_ != 0 ? this.high_ : this.low_;
for (var bit = 31; bit > 0; bit--) {
if ((val & (1 << bit)) != 0) {
break;
}
}
return this.high_ != 0 ? bit + 33 : bit + 1;
}
}
/** @return {boolean} Whether this value is zero. */
isZero():boolean {
return this.high_ == 0 && this.low_ == 0;
}
/** @return {boolean} Whether this value is negative. */
isNegative():boolean {
return this.high_ < 0;
}
/** @return {boolean} Whether this value is odd. */
isOdd():boolean {
return (this.low_ & 1) == 1;
}
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long equals the other.
*/
equals(other:Long):boolean {
return (this.high_ == other.high_) && (this.low_ == other.low_);
}
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long does not equal the other.
*/
notEquals(other:Long):boolean {
return (this.high_ != other.high_) || (this.low_ != other.low_);
}
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long is less than the other.
*/
lessThan(other:Long):boolean {
return this.compare(other) < 0;
}
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long is less than or equal to the other.
*/
lessThanOrEqual(other:Long):boolean {
return this.compare(other) <= 0;
}
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long is greater than the other.
*/
greaterThan(other:Long):boolean {
return this.compare(other) > 0;
}
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long is greater than or equal to the other.
*/
greaterThanOrEqual(other:Long):boolean {
return this.compare(other) >= 0;
}
/**
* Compares this Long with the given one.
* @param {goog.math.Long} other Long to compare against.
* @return {number} 0 if they are the same, 1 if the this is greater, and -1
* if the given one is greater.
*/
compare(other:Long):number {
if (this.equals(other)) {
return 0;
}
var thisNeg = this.isNegative();
var otherNeg = other.isNegative();
if (thisNeg && !otherNeg) {
return -1;
}
if (!thisNeg && otherNeg) {
return 1;
}
// at this point, the signs are the same, so subtraction will not overflow
if (this.subtract(other).isNegative()) {
return -1;
} else {
return 1;
}
}
/** @return {!goog.math.Long} The negation of this value. */
negate():Long {
if (this.equals(Long.MIN_VALUE)) {
return Long.MIN_VALUE;
} else {
return this.not().add(Long.ONE);
}
}
/**
* Returns the sum of this and the given Long.
* @param {goog.math.Long} other Long to add to this one.
* @return {!goog.math.Long} The sum of this and the given Long.
*/
add(other:Long):Long {
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
var a48 = this.high_ >>> 16;
var a32 = this.high_ & 0xFFFF;
var a16 = this.low_ >>> 16;
var a00 = this.low_ & 0xFFFF;
var b48 = other.high_ >>> 16;
var b32 = other.high_ & 0xFFFF;
var b16 = other.low_ >>> 16;
var b00 = other.low_ & 0xFFFF;
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
c00 += a00 + b00;
c16 += c00 >>> 16;
c00 &= 0xFFFF;
c16 += a16 + b16;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c32 += a32 + b32;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c48 += a48 + b48;
c48 &= 0xFFFF;
return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
}
/**
* Returns the difference of this and the given Long.
* @param {goog.math.Long} other Long to subtract from this.
* @return {!goog.math.Long} The difference of this and the given Long.
*/
subtract(other:Long):Long {
return this.add(other.negate());
}
/**
* Returns the product of this and the given long.
* @param {goog.math.Long} other Long to multiply with this.
* @return {!goog.math.Long} The product of this and the other.
*/
multiply(other:Long):Long {
if (this.isZero()) {
return Long.ZERO;
} else if (other.isZero()) {
return Long.ZERO;
}
if (this.equals(Long.MIN_VALUE)) {
return other.isOdd() ? Long.MIN_VALUE : Long.ZERO;
} else if (other.equals(Long.MIN_VALUE)) {
return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
}
if (this.isNegative()) {
if (other.isNegative()) {
return this.negate().multiply(other.negate());
} else {
return this.negate().multiply(other).negate();
}
} else if (other.isNegative()) {
return this.multiply(other.negate()).negate();
}
// If both longs are small, use float multiplication
if (this.lessThan(Long.TWO_PWR_24_) &&
other.lessThan(Long.TWO_PWR_24_)) {
return Long.fromNumber(this.toNumber() * other.toNumber());
}
// Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
// We can skip products that would overflow.
var a48 = this.high_ >>> 16;
var a32 = this.high_ & 0xFFFF;
var a16 = this.low_ >>> 16;
var a00 = this.low_ & 0xFFFF;
var b48 = other.high_ >>> 16;
var b32 = other.high_ & 0xFFFF;
var b16 = other.low_ >>> 16;
var b00 = other.low_ & 0xFFFF;
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
c00 += a00 * b00;
c16 += c00 >>> 16;
c00 &= 0xFFFF;
c16 += a16 * b00;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c16 += a00 * b16;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c32 += a32 * b00;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c32 += a16 * b16;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c32 += a00 * b32;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
c48 &= 0xFFFF;
return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
}
/**
* Returns this Long divided by the given one.
* @param {goog.math.Long} other Long by which to divide.
* @return {!goog.math.Long} This Long divided by the given one.
*/
div(other:Long):Long {
if (other.isZero()) {
throw Error('division by zero');
} else if (this.isZero()) {
return Long.ZERO;
}
if (this.equals(Long.MIN_VALUE)) {
if (other.equals(Long.ONE) ||
other.equals(Long.NEG_ONE)) {
return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
} else if (other.equals(Long.MIN_VALUE)) {
return Long.ONE;
} else {
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
var halfThis = this.shiftRight(1);
let approx = halfThis.div(other).shiftLeft(1);
if (approx.equals(Long.ZERO)) {
return other.isNegative() ? Long.ONE : Long.NEG_ONE;
} else {
let rem = this.subtract(other.multiply(approx));
var result = approx.add(rem.div(other));
return result;
}
}
} else if (other.equals(Long.MIN_VALUE)) {
return Long.ZERO;
}
if (this.isNegative()) {
if (other.isNegative()) {
return this.negate().div(other.negate());
} else {
return this.negate().div(other).negate();
}
} else if (other.isNegative()) {
return this.div(other.negate()).negate();
}
// Repeat the following until the remainder is less than other: find a
// floating-point that approximates remainder / other *from below*, add this
// into the result, and subtract it from the remainder. It is critical that
// the approximate value is less than or equal to the real value so that the
// remainder never becomes negative.
var res = Long.ZERO;
let rem:Long = this;
while (rem.greaterThanOrEqual(other)) {
// Approximate the result of division. This may be a little greater or
// smaller than the actual value.
let approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));
// We will tweak the approximate result by changing it in the 48-th digit or
// the smallest non-fractional digit, whichever is larger.
var log2 = Math.ceil(Math.log(approx) / Math.LN2);
var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48);
// Decrease the approximation until it is smaller than the remainder. Note
// that if it is too large, the product overflows and is negative.
var approxRes = Long.fromNumber(approx);
var approxRem = approxRes.multiply(other);
while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
approx -= delta;
approxRes = Long.fromNumber(approx);
approxRem = approxRes.multiply(other);
}
// We know the answer can't be zero... and actually, zero would cause
// infinite recursion since we would make no progress.
if (approxRes.isZero()) {
approxRes = Long.ONE;
}
res = res.add(approxRes);
rem = rem.subtract(approxRem);
}
return res;
}
/**
* Returns this Long modulo the given one.
* @param {goog.math.Long} other Long by which to mod.
* @return {!goog.math.Long} This Long modulo the given one.
*/
modulo(other:Long):Long {
return this.subtract(this.div(other).multiply(other));
}
/** @return {!goog.math.Long} The bitwise-NOT of this value. */
not():Long {
return Long.fromBits(~this.low_, ~this.high_);
}
/**
* Returns the bitwise-AND of this Long and the given one.
* @param {goog.math.Long} other The Long with which to AND.
* @return {!goog.math.Long} The bitwise-AND of this and the other.
*/
and(other:Long):Long {
return Long.fromBits(this.low_ & other.low_,
this.high_ & other.high_);
}
/**
* Returns the bitwise-OR of this Long and the given one.
* @param {goog.math.Long} other The Long with which to OR.
* @return {!goog.math.Long} The bitwise-OR of this and the other.
*/
or(other:Long):Long {
return Long.fromBits(this.low_ | other.low_,
this.high_ | other.high_);
}
/**
* Returns the bitwise-XOR of this Long and the given one.
* @param {goog.math.Long} other The Long with which to XOR.
* @return {!goog.math.Long} The bitwise-XOR of this and the other.
*/
xor(other:Long):Long {
return Long.fromBits(this.low_ ^ other.low_,
this.high_ ^ other.high_);
}
/**
* Returns this Long with bits shifted to the left by the given amount.
* @param {number} numBits The number of bits by which to shift.
* @return {!goog.math.Long} This shifted to the left by the given amount.
*/
shiftLeft(numBits:number):Long {
numBits &= 63;
if (numBits == 0) {
return this;
} else {
var low = this.low_;
if (numBits < 32) {
var high = this.high_;
return Long.fromBits(
low << numBits,
(high << numBits) | (low >>> (32 - numBits)));
} else {
return Long.fromBits(0, low << (numBits - 32));
}
}
}
/**
* Returns this Long with bits shifted to the right by the given amount.
* @param {number} numBits The number of bits by which to shift.
* @return {!goog.math.Long} This shifted to the right by the given amount.
*/
shiftRight(numBits:number):Long {
numBits &= 63;
if (numBits == 0) {
return this;
} else {
var high = this.high_;
if (numBits < 32) {
var low = this.low_;
return Long.fromBits(
(low >>> numBits) | (high << (32 - numBits)),
high >> numBits);
} else {
return Long.fromBits(
high >> (numBits - 32),
high >= 0 ? 0 : -1);
}
}
}
/**
* Returns this Long with bits shifted to the right by the given amount, with
* zeros placed into the new leading bits.
* @param {number} numBits The number of bits by which to shift.
* @return {!goog.math.Long} This shifted to the right by the given amount, with
* zeros placed into the new leading bits.
*/
shiftRightUnsigned(numBits:number):Long {
numBits &= 63;
if (numBits == 0) {
return this;
} else {
var high = this.high_;
if (numBits < 32) {
var low = this.low_;
return Long.fromBits(
(low >>> numBits) | (high << (32 - numBits)),
high >>> numBits);
} else if (numBits == 32) {
return Long.fromBits(high, 0);
} else {
return Long.fromBits(high >>> (numBits - 32), 0);
}
}
}
/**
* Returns a Long representing the given (32-bit) integer value.
* @param {number} value The 32-bit integer in question.
* @return {!goog.math.Long} The corresponding Long value.
*/
static fromInt(value:number):Long {
if (-128 <= value && value < 128) {
var cachedObj = Long.IntCache_[value];
if (cachedObj) {
return cachedObj;
}
}
var obj = new Long(value | 0, value < 0 ? -1 : 0);
if (-128 <= value && value < 128) {
Long.IntCache_[value] = obj;
}
return obj;
}
/**
* Returns a Long representing the given value, provided that it is a finite
* number. Otherwise, zero is returned.
* @param {number} value The number in question.
* @return {!goog.math.Long} The corresponding Long value.
*/
static fromNumber(value:number):Long {
if (isNaN(value) || !isFinite(value)) {
return Long.ZERO;
} else if (value <= -Long.TWO_PWR_63_DBL_) {
return Long.MIN_VALUE;
} else if (value + 1 >= Long.TWO_PWR_63_DBL_) {
return Long.MAX_VALUE;
} else if (value < 0) {
return Long.fromNumber(-value).negate();
} else {
return new Long(
(value % Long.TWO_PWR_32_DBL_) | 0,
(value / Long.TWO_PWR_32_DBL_) | 0);
}
}
/**
* Returns a Long representing the 64-bit integer that comes by concatenating
* the given high and low bits. Each is assumed to use 32 bits.
* @param {number} lowBits The low 32-bits.
* @param {number} highBits The high 32-bits.
* @return {!goog.math.Long} The corresponding Long value.
*/
static fromBits(lowBits:number, highBits:number):Long {
return new Long(lowBits, highBits);
}
/**
* Returns a Long representation of the given string, written using the given
* radix.
* @param {string} str The textual representation of the Long.
* @param {number=} opt_radix The radix in which the text is written.
* @return {!goog.math.Long} The corresponding Long value.
*/
static fromString(str:string, opt_radix:number):Long {
if (str.length == 0) {
throw Error('number format error: empty string');
}
var radix = opt_radix || 10;
if (radix < 2 || 36 < radix) {
throw Error('radix out of range: ' + radix);
}
if (str.charAt(0) == '-') {
return Long.fromString(str.substring(1), radix).negate();
} else if (str.indexOf('-') >= 0) {
throw Error('number format error: interior "-" character: ' + str);
}
// Do several (8) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = Long.fromNumber(Math.pow(radix, 8));
var result = Long.ZERO;
for (var i = 0; i < str.length; i += 8) {
var size = Math.min(8, str.length - i);
var value = parseInt(str.substring(i, i + size), radix);
if (size < 8) {
var power = Long.fromNumber(Math.pow(radix, size));
result = result.multiply(power).add(Long.fromNumber(value));
} else {
result = result.multiply(radixToPower);
result = result.add(Long.fromNumber(value));
}
}
return result;
}
}
} | the_stack |
import { ReactNode } from "react"
type PrimitiveParameterTypeName =
| "string"
| "description"
| "int"
| "json"
| "javascript"
| "yaml"
| "password"
| "boolean"
| "dashDate"
| "isoUtcDate"
| "selection"
| "file"
| "oauthSecret"
type ArrayParameterTypeName = `array/${PrimitiveParameterTypeName}`
type ParameterTypeName = PrimitiveParameterTypeName | ArrayParameterTypeName
type StringParameter = {
/**
* String with regexp that specifies the allowed values
*/
pattern?: string
/**
* Defines whether to render a multiline text field
*/
multiline?: boolean
}
type NumberParameter = {
/**
* Minimum allowed value of a numeric parameter
*/
minimum?: number
/**
* Maximum allowed value of a numeric parameter
*/
maximum?: number
}
type FieldsByType<T> = T extends "string" ? StringParameter : T extends "int" ? NumberParameter : {}
/**
* Type of parameter
*/
export type ParameterType<T, N extends ParameterTypeName = ParameterTypeName> = FieldsByType<N> & {
/**
* Unique name of the type
*/
typeName: N
/**
* Additional parameters (for selects - list of options)
*/
data?: T
//not used / not implemented at the moment, reserved for future use
fromString?: (str: string) => T
toString?: (t: T) => string
}
export function hiddenValue<P, V extends number | string | bigint>(
value: V | ((config: P) => V),
hide?: (config: P) => boolean
): ConstantOrFunction<P, V> {
if (!hide) {
return undefined
} else {
return config => {
if (hide(config)) {
return typeof value === "function" ? value(config) : value
} else {
return undefined
}
}
}
}
function assertIsPrimitiveParameterTypeName(
typeName: ParameterTypeName,
errorMsg?: string
): asserts typeName is PrimitiveParameterTypeName {
if (typeName.startsWith("array/")) throw new Error(errorMsg || "Primitive parameter assertion failed")
}
export function assertIsStringParameterType(
parameterType: ParameterType<any, any>,
errorMessage?: string
): asserts parameterType is ParameterType<unknown, "string"> {
if (parameterType.typeName !== "string") throw new Error(errorMessage || "`string` parameter type assertion failed")
}
export function assertIsIntParameterType(
parameterType: ParameterType<any, any>,
errorMessage?: string
): asserts parameterType is ParameterType<unknown, "int"> {
if (parameterType.typeName !== "int") throw new Error(errorMessage || "`int` parameter type assertion failed")
}
export const stringType: ParameterType<string, "string"> = {
typeName: "string",
}
export const makeStringType = (options: StringParameter): ParameterType<string, "string"> => {
const result: ParameterType<string, "string"> = { ...stringType }
return { ...stringType, ...options }
}
export const descriptionType: ParameterType<string, "description"> = {
typeName: "description",
}
export const intType: ParameterType<bigint, "int"> = {
typeName: "int",
}
export const makeIntType = (options?: { minimum?: number; maximum?: number }): ParameterType<bigint, "int"> => {
const result: ParameterType<bigint, "int"> = { ...intType }
if (options) Object.entries(options).forEach(([key, value]) => (result[key] = value))
return result
}
export const jsonType: ParameterType<string, "json"> = {
typeName: "json" as const,
}
export const jsType: ParameterType<string, "javascript"> = {
typeName: "javascript" as const,
}
export const yamlType: ParameterType<string, "yaml"> = {
typeName: "yaml" as const,
}
export const passwordType: ParameterType<string, "password"> = {
typeName: "password" as const,
}
export const booleanType: ParameterType<boolean, "boolean"> = {
typeName: "boolean" as const,
}
export const fileType: ParameterType<string, "file"> = {
typeName: "file" as const,
}
export const oauthSecretType: ParameterType<string, "oauthSecret"> = {
typeName: "oauthSecret" as const,
}
export const arrayOf = <T>(param: ParameterType<T>): ParameterType<T[]> => {
const typeName: ParameterTypeName = param.typeName
assertIsPrimitiveParameterTypeName(typeName)
return {
typeName: `array/${typeName}` as const,
}
}
/**
* YYYY-MM-DD
*/
export const dashDateType: ParameterType<string> = {
typeName: "dashDate" as const,
}
/**
* ISO_8601 (https://en.wikipedia.org/wiki/ISO_8601) time
*/
export const isoUtcDateType: ParameterType<string> = {
typeName: "isoUtcDate" as const,
}
export interface SelectOption {
id: string
displayName: string
}
export interface SelectOptionCollection {
options: SelectOption[]
/**
* Maximum options allowed to be selected. Undefined means there's no limit in number of possible
* selected fields
*/
maxOptions?: number
}
export const singleSelectionType = (options: string[]): ParameterType<SelectOptionCollection> => {
return selectionType(options, 1)
}
export const selectionType = (options: string[], maxOptions?: number): ParameterType<SelectOptionCollection> => {
return selectionTypeWithOptions(
options.map(id => ({ displayName: id, id: id })),
maxOptions
)
}
export const selectionTypeWithOptions = (
options: SelectOption[],
maxOptions?: number
): ParameterType<SelectOptionCollection> => {
return {
data: {
options: options,
maxOptions,
},
typeName: "selection" as const,
}
}
export type Function<P, V> = (param: P) => V
export type ConstantOrFunction<P, V> = V | Function<P, V>
export function asFunction<P, V>(p: ConstantOrFunction<P, V>): Function<P, V> {
if (typeof p === "function") {
return p as Function<P, V>
} else {
return _ => p
}
}
/**
* Validates the value. Returns `null` if the value is valid otherwise returns `undefined`.
*/
export type Validator = (value: any) => string | undefined
export type Parameter = {
/**
* Display name (for UI)
*/
displayName?: string
/**
* Id (corresponds to key in yaml config)
*/
id: string
/**
* Type of parameter
*/
type?: ParameterType<any>
/**
* Default value (should be displayed by default)
*/
defaultValue?: any
/**
* Flag describes required/optional nature of the field. IF empty - field is optional
* Either constant or function of current config
*/
required?: ConstantOrFunction<any, any>
/**
* Documentation
*/
documentation?: ReactNode
/**
* IDs of parameters that should include this parameter as a nested one. The first ID
* in the array belongs to the closest parent parameter.
*/
parentParametersIds?: string[]
/**
* Either constant or function of current config (to be able to hide fields based on rules)
*
* If value is defined (!== undefined): field should be hidden and constant value
* should be put to the form.
*
* WARNING: value could be "" or null which is a valid defined value. Do not check it with if (constant),
* use `constant !== undefined` to send a hidden value to backend. To conditionally omit the field completely
* use `omitFieldRule` function.
*/
constant?: ConstantOrFunction<any, any>
/**
* Function of current config that shows whether to omit the field and its value completely.
*/
omitFieldRule?: (config: unknown) => boolean
/**
* Javascript Debugger is supported to help edit this property value.
* Debugger supports 2 mode based on expected result value: object or string
*/
jsDebugger?: "object" | "string" | null
/**
* Field use full width by omitting label and prefer higher height where applicable
*/
bigField?: boolean
/**
* Code suggestions for CodeDebugger
*/
codeSuggestions?: string
validator?: (rule, value) => Promise<void>
}
export interface CollectionParameter extends Parameter {
/**
* If defined, should be applied only to specific collections
* (see SourceConnector.collectionTypes)
*/
applyOnlyTo?: string[] | string
}
export type SourceCollection = CollectionParameter[]
type SourceConnectorId =
| "facebook_marketing"
| "google_ads"
| "google_analytics"
| "google_play"
| "firebase"
| "redis"
| "amplitude"
| `singer-${string}`
| `airbyte-source-${string}`
export interface SourceConnector {
/**
* Hints the source origin.
* */
protoType?: "singer" | "airbyte"
/**
* Enable collection Start Date parameter.
* */
isStartDateEnabled?: boolean
/**
* If connector requires expert-level knowledge (such as JSON editing)
*
* Undefined means false
*/
expertMode?: boolean
/**
* Name of connector that should be displayed
*/
displayName: string
/**
* id of connector. Corresponds to 'type' node in event native config
*/
id: SourceConnectorId
/**
* SVG icon (please, no height/width params!)
*/
pic: ReactNode
/**
* Indicates whether to use only static collections or to allow user to
* add custom ones
*/
forbidCustomCollections?: boolean
/**
* Configuration parameters
*/
configParameters: Parameter[]
/**
* `true` if need to additionally load `configParameters`
*/
hasLoadableConfigParameters?: boolean
/**
* Parameters of each collection
*/
collectionParameters: CollectionParameter[]
/**
* If collections are limited to certain names, list them here
*/
collectionTypes: string[]
/**
* Collection templates
*/
collectionTemplates?: CollectionTemplate[]
/**
* A list of non-configurable collections that can only be turned on/off
*/
staticCollections?: SourceCollection[]
/**
* API endpoint which should be requested for static streams config
* For now, if it is specified other streams (collections) will be ignored
* See SourceEditorStreams component for more detail
*/
staticStreamsConfigEndpoint?: string
/**
* API Connector documentation
*/
documentation?: ConnectorDocumentation
/**
* If true, user won't be able to add new sources of this type
* yet it will be possible to edit the existing ones
*/
deprecated?: boolean
}
/**
* Collection template: predefined configuratio for collections
*/
export interface CollectionTemplate {
templateName: string
description?: ReactNode
collections: any[]
}
/**
* Structured documentation for connector
*/
export type ConnectorDocumentation = {
/**
* Overview: just a few words about connector
*/
overview: ReactNode
/**
* Connection properties
*/
connection: ReactNode
}
export interface SingerTap {
pic: ReactNode
displayName: string
tap: string
/**
* Whether we consider this tap as stable and production ready
*/
stable: boolean
/**
* We have a native equivalent
*/
hasNativeEquivalent: boolean
/**
* If the tap uses legacy properties.json instead of catalog.json
*/
legacyProperties?: boolean
/**
* If tap defines it's own parameters instead of
* default singer params
*/
parameters?: Parameter[]
/**
* API Connector documentation
*/
documentation?: ConnectorDocumentation
/**
* Allows only editing the existing sources
*/
deprecated?: boolean
}
export interface AirbyteSource {
pic: ReactNode
docker_image_name: `airbyte/source-${string}`
displayName: string
/**
* Whether we consider this tap as stable and production ready
*/
stable: boolean
/**
* We have a native equivalent
*/
hasNativeEquivalent?: boolean
/**
* API Connector documentation
*/
documentation?: ConnectorDocumentation
} | the_stack |
import { isMobile } from 'is-mobile';
import { getChatElements, loadYaml, sleep } from '~test/utils';
import YveBotUI from '..';
jest.mock('is-mobile');
const OPTS = {
yveBotOptions: {
enableWaitForSleep: false,
},
};
beforeEach(() => {
document.body.innerHTML = '';
});
test('event binding', async () => {
const rules = loadYaml(`
- name: value
type: String
`);
const onStart = jest.fn();
const onStoreChanged = jest.fn();
const onEnd = jest.fn();
const onEndCopy = jest.fn();
const onReply = jest.fn();
new YveBotUI(rules, OPTS)
.on('start', onStart)
.on('storeChanged', onStoreChanged)
.on('end', onEnd)
.on('end', onEndCopy)
.on('reply', onReply)
.start();
const { input, submit } = getChatElements();
const msg = 'ok';
const output = { value: msg };
const session = 'session';
await sleep();
expect(onStart).toBeCalledWith(session);
input.value = msg;
submit.click();
await sleep();
expect(onReply).toBeCalledWith(msg, session);
await sleep();
expect(onStoreChanged).toBeCalledWith(
{ output, currentIdx: 1, waitingForAnswer: false },
session
);
await sleep();
expect(onEnd).toBeCalledWith(output, session);
await sleep();
expect(onEndCopy).toBeCalledWith(output, session);
});
test('passive support', async () => {
const rules = loadYaml(`
- type: Passive
- Welcome to support
- message: How can I help you?
name: help
`);
const onListen = jest.fn();
new YveBotUI(rules, OPTS)
.listen([{ includes: 'help', next: 'help' }])
.on('listen', onListen)
.start();
const { target, input, submit, getBotMessages } = getChatElements();
await sleep();
input.value = 'help me';
submit.click();
await sleep();
expect(getBotMessages()).toHaveLength(1);
expect(target).toMatchSnapshot();
});
describe('DOM behaviors', () => {
test('initial elements', async () => {
const rules = loadYaml(`
- message: Hello
`);
new YveBotUI(rules, OPTS).start();
const {
target,
conversation,
form,
input,
submit,
getTyping,
} = getChatElements();
await sleep();
expect(conversation).not.toBeNull();
expect(getTyping()).not.toBeNull();
expect(form).not.toBeNull();
expect(input).not.toBeNull();
expect(submit).not.toBeNull();
expect(target).toMatchSnapshot();
});
test('desktop: avoid losing scroll position on toggle input focused', async () => {
(isMobile as any).mockImplementation(() => false);
const rules = loadYaml(`
- message: Hello
type: SingleChoice
options:
- A
- message: Hi
type: String
`);
new YveBotUI(rules, OPTS).start();
const { input, getBubbleButtons, getBotMessages } = getChatElements();
await sleep();
getBubbleButtons()[0].click();
await sleep();
expect(document.activeElement).toEqual(input);
});
test('mobile: avoid losing scroll position on toggle input focused', async () => {
(isMobile as any).mockImplementation(() => true);
const rules = loadYaml(`
- message: Hello
type: SingleChoice
options:
- A
- message: Hi
type: String
`);
new YveBotUI(rules, OPTS).start();
const { input, getBubbleButtons, getBotMessages } = getChatElements();
await sleep();
getBubbleButtons()[0].click();
await sleep();
expect(document.activeElement).toEqual(input);
});
test('bot with name', async () => {
const rules = loadYaml(`
- message: Hello
`);
new YveBotUI(rules, { name: 'YveBot', ...OPTS }).start();
const { target, getSenderName } = getChatElements();
await sleep();
expect(getSenderName()).not.toBeNull();
expect(target).toMatchSnapshot();
});
test('bot with timestamp', async () => {
const _now = Date.now; // tslint:disable-line variable-name
Date.now = jest.fn().mockReturnValue(0);
const rules = loadYaml(`
- message: Hello
`);
new YveBotUI(rules, {
name: 'Yvebot',
timestampable: true,
...OPTS,
}).start();
const { target, getTimestamp } = getChatElements();
await sleep();
expect(getTimestamp()).not.toBeNull();
expect(target).toMatchSnapshot();
Date.now = _now;
});
test('user reply', async () => {
const rules = loadYaml(`
- message: Your name
type: String
`);
new YveBotUI(rules, OPTS).start();
const {
target,
input,
submit,
getMessages,
getUserMessages,
getBotMessages,
} = getChatElements();
await sleep();
input.value = 'James';
submit.click();
await sleep();
expect(getMessages()).toHaveLength(2);
expect(getUserMessages()).toHaveLength(1);
expect(getBotMessages()).toHaveLength(1);
expect(target).toMatchSnapshot();
});
test('user reply without message', async () => {
const rules = loadYaml(`
- message: Your name
type: String
`);
new YveBotUI(rules, OPTS).start();
const { input, submit, getUserMessages } = getChatElements();
input.value = '';
submit.click();
await sleep();
expect(getUserMessages()).toHaveLength(0);
});
test('user reply with single choice', async () => {
const rules = loadYaml(`
- message: Make your choice
type: SingleChoice
options:
- label: One
- value: Two
- label: Three
value:
- label:
value: Four
- Five
`);
new YveBotUI(rules, OPTS).start();
const {
target,
input,
submit,
getBubbleButtons,
getUserMessages,
} = getChatElements();
await sleep();
// showing the options
const bubbles = getBubbleButtons();
expect(input.hasAttribute('disabled')).toBeTruthy();
expect(input.placeholder).toContain('Choose an option');
expect(submit.hasAttribute('disabled')).toBeTruthy();
expect(bubbles).toHaveLength(5);
expect(getUserMessages()).toHaveLength(0);
expect(target).toMatchSnapshot();
// sending answer
bubbles[0].click();
await sleep();
expect(input.hasAttribute('disabled')).toBeFalsy();
expect(input.placeholder).toBe('Type your message');
expect(submit.hasAttribute('disabled')).toBeFalsy();
expect(getBubbleButtons()).toHaveLength(0);
expect(getUserMessages()).toHaveLength(1);
expect(target).toMatchSnapshot();
});
test('user reply with single choice and no options', async () => {
const rules = loadYaml(`
- message: Make your choice
type: SingleChoice
`);
new YveBotUI(rules, OPTS).start();
const { getBubbleButtons } = getChatElements();
await sleep();
expect(getBubbleButtons()).toHaveLength(0);
});
test('user reply with multiple choice', async () => {
const rules = loadYaml(`
- message: Make your choice
type: MultipleChoice
options:
- label: One
- value: Two
- Three
`);
new YveBotUI(rules, OPTS).start();
const {
target,
input,
submit,
getBubbleButtons,
getBubbleDone,
getUserMessages,
} = getChatElements();
await sleep();
const bubbles = getBubbleButtons();
const done = getBubbleDone();
// showing the options
expect(done).not.toBeNull();
expect(input.hasAttribute('disabled')).toBeTruthy();
expect(input.placeholder).toContain('Choose the options');
expect(submit.hasAttribute('disabled')).toBeTruthy();
expect(bubbles).toHaveLength(3);
expect(getUserMessages()).toHaveLength(0);
expect(target).toMatchSnapshot();
// select one
bubbles[0].click();
expect(bubbles[0].classList).toContain('selected');
expect(bubbles[1].classList).not.toContain('selected');
expect(getUserMessages()).toHaveLength(0);
// unselect
bubbles[0].click();
expect(bubbles[0].classList).not.toContain('selected');
expect(bubbles[1].classList).not.toContain('selected');
expect(getUserMessages()).toHaveLength(0);
// select all
bubbles[0].click();
bubbles[1].click();
expect(bubbles[0].classList).toContain('selected');
expect(bubbles[1].classList).toContain('selected');
expect(getUserMessages()).toHaveLength(0);
// sending answer
done.click();
expect(input.hasAttribute('disabled')).toBeFalsy();
expect(input.placeholder).toBe('Type your message');
expect(submit.hasAttribute('disabled')).toBeFalsy();
expect(getBubbleButtons()).toHaveLength(0);
expect(getUserMessages()).toHaveLength(1);
});
test('user reply with multiple choice and no options', async () => {
const rules = loadYaml(`
- message: Make your choice
type: MultipleChoice
`);
new YveBotUI(rules, OPTS).start();
const { getBubbleButtons } = getChatElements();
await sleep();
expect(getBubbleButtons()).toHaveLength(0);
});
test('user click on more options using maxOptions', async () => {
const rules = loadYaml(`
- message: Make your choice
type: SingleChoice
maxOptions: 3
options:
- One
- Two
- Three
- Four
- Five
- Six
- Seven
`);
new YveBotUI(rules, OPTS).start();
const {
target,
getBubbleButtons,
getBubbleMoreOptions,
} = getChatElements();
await sleep();
// page 1
expect(getBubbleButtons()).toHaveLength(3);
expect(getBubbleMoreOptions()).not.toBeNull();
expect(target).toMatchSnapshot();
getBubbleMoreOptions().click();
// page 2
expect(getBubbleButtons()).toHaveLength(5);
expect(getBubbleMoreOptions()).not.toBeNull();
getBubbleMoreOptions().click();
// page 3
expect(getBubbleButtons()).toHaveLength(7);
expect(getBubbleMoreOptions()).not.toBeNull();
getBubbleMoreOptions().click();
// page 4 - no more button
expect(getBubbleButtons()).toHaveLength(7);
expect(getBubbleMoreOptions()).toBeNull();
});
test('bot typing', async () => {
const rules = loadYaml(`
- message: Hello
delay: 10
`);
const bot = new YveBotUI(rules).start();
await sleep(5);
// typing
const { getTyping } = getChatElements();
expect(getTyping().classList).toContain('is-typing');
await sleep(20);
// typed
expect(getTyping().classList).not.toContain('is-typing');
// using methods
bot.typing();
await sleep(5);
expect(getTyping().classList).toContain('is-typing');
bot.typed();
await sleep(5);
expect(getTyping().classList).not.toContain('is-typing');
});
test('bot hearing', async () => {
const rules = loadYaml(`
- message: Hello
type: String
- message: name
type: String
multiline: false
- message: Nice
`);
const inputClass = '.yvebot-form-input';
new YveBotUI(rules, OPTS).start();
const { input, submit, target } = getChatElements();
await sleep();
expect(input.type).toBe('textarea');
input.value = 'msg';
submit.click();
await sleep();
let modifiedInput = target.querySelector(inputClass) as HTMLInputElement;
expect(modifiedInput.type).toBe('text');
modifiedInput.value = 'another msg';
submit.click();
await sleep();
modifiedInput = target.querySelector(inputClass) as HTMLInputElement;
expect(modifiedInput.type).toBe('textarea');
});
test('bot sleeping', async () => {
const rules = loadYaml(`
- message: Hello
delay: 1
`);
new YveBotUI(rules).start();
// sleeping
const { getTyping, getBotMessages } = getChatElements();
expect(getTyping().classList).not.toContain('is-typing');
expect(getBotMessages()).toHaveLength(0);
// typed
await sleep(5);
expect(getBotMessages()).toHaveLength(1);
});
test('autofocus', async () => {
const rules = loadYaml(`
- type: Any
- message: Make your choice
type: SingleChoice
options:
- One
- Two
`);
new YveBotUI(rules, OPTS).start();
const { input, submit, getBubbleButtons } = getChatElements();
await sleep();
// sending message
expect(document.activeElement).toEqual(input);
input.value = 'A testing message';
submit.click();
expect(document.activeElement).toEqual(input);
await sleep();
// clicking on bubble
const bubbles = getBubbleButtons();
bubbles[0].click();
expect(document.activeElement).toEqual(input);
});
test('disabled autofocus', async () => {
const rules = loadYaml(`
- type: Any
- message: Make your choice
type: SingleChoice
options:
- One
- Two
`);
new YveBotUI(rules, { autoFocus: false, ...OPTS }).start();
const { input, submit, getBubbleButtons } = getChatElements();
await sleep();
// sending message
expect(document.activeElement).not.toEqual(input);
input.value = 'A testing message';
submit.click();
expect(document.activeElement).not.toEqual(input);
await sleep();
// clicking on bubble
const bubbles = getBubbleButtons();
bubbles[0].click();
expect(document.activeElement).not.toEqual(input);
});
test('submit message when press Enter in textarea', async () => {
const rules = loadYaml(`
- message: value
type: String
- message: bye
type: String
multiline: false
`);
new YveBotUI(rules, OPTS).start();
const { input, chat } = getChatElements();
await sleep();
expect(input.type).toBe('textarea');
input.value = 'msg';
const event = new KeyboardEvent('keydown', { code: 'Enter' });
input.dispatchEvent(event);
await sleep();
const modifiedInput = chat.querySelector(
'.yvebot-form-input'
) as HTMLInputElement;
expect(modifiedInput.type).toBe('text');
});
test('should not submit msg if shift key is pressed', async () => {
const rules = loadYaml(`
- message: value
type: String
- message: bye
type: String
multiline: false
`);
new YveBotUI(rules, OPTS).start();
const { input, chat } = getChatElements();
await sleep();
expect(input.type).toBe('textarea');
input.value = 'msg';
const event = new KeyboardEvent('keydown', {
code: 'Enter',
shiftKey: true,
});
input.dispatchEvent(event);
await sleep();
const modifiedInput = chat.querySelector(
'.yvebot-form-input'
) as HTMLInputElement;
expect(modifiedInput.type).toBe('textarea');
});
test('submit message when press Enter as which prop in textarea', async () => {
const rules = loadYaml(`
- message: value
type: String
- message: bye
type: String
multiline: false
`);
new YveBotUI(rules, OPTS).start();
const { input, chat } = getChatElements();
await sleep();
expect(input.type).toBe('textarea');
input.value = 'msg';
const event = new KeyboardEvent('keydown', { code: 'Enter' });
input.dispatchEvent(event);
await sleep();
const modifiedInput = chat.querySelector(
'.yvebot-form-input'
) as HTMLInputElement;
expect(modifiedInput.type).toBe('text');
});
test('should set textarea height based on input', async () => {
const rules = loadYaml(`
- message: value
type: String
`);
new YveBotUI(rules, OPTS).start();
const { input, chat } = getChatElements();
const inputEvent = new Event('input');
expect(input.type).toBe('textarea');
input.value = 'msg';
const scrollHeight = input.scrollHeight;
input.dispatchEvent(inputEvent);
expect(input.style.height).toBe(`${scrollHeight}px`);
});
}); | the_stack |
import { Component } from '@angular/core';
import { RouterTestingModule } from '@angular/router/testing';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { SprkIconComponent } from '../sprk-icon/sprk-icon.component';
import { SprkLinkDirective } from '../../directives/sprk-link/sprk-link.directive';
import { SprkDropdownComponent } from './sprk-dropdown.component';
import { ISprkDropdownChoice } from './sprk-dropdown.interfaces';
@Component({
template: `
<sprk-dropdown
[dropdownType]="dropdownType"
[variant]="variant"
[triggerText]="triggerText"
[choices]="choices"
[additionalClasses]="additionalClasses"
[idString]="idString"
[additionalTriggerClasses]="additionalTriggerClasses"
[triggerAdditionalClasses]="triggerAdditionalClasses"
[additionalTriggerTextClasses]="additionalTriggerTextClasses"
[triggerTextAdditionalClasses]="triggerTextAdditionalClasses"
[additionalIconClasses]="additionalIconClasses"
[iconAdditionalClasses]="iconAdditionalClasses"
[screenReaderText]="screenReaderText"
[triggerIconType]="triggerIconType"
[triggerIconName]="triggerIconName"
[title]="title"
[heading]="heading"
[selector]="selector"
[analyticsString]="analyticsString"
[isOpen]="isOpen"
>
</sprk-dropdown>
`,
})
class TestWrapperComponent {
dropdownType: string;
variant: string;
triggerText: string;
choices: ISprkDropdownChoice[];
additionalClasses: string;
idString: string;
additionalTriggerClasses: string;
additionalTriggerTextClasses: string;
triggerAdditionalClasses: string;
triggerTextAdditionalClasses: string;
additionalIconClasses: string;
iconAdditionalClasses: string;
triggerIconType: string;
triggerIconName: string;
screenReaderText: string;
title: string;
heading: string;
analyticsString: string;
isOpen: boolean;
selector: string;
}
describe('SprkDropdownComponent', () => {
let fixture: ComponentFixture<TestWrapperComponent>;
let wrapperComponent: TestWrapperComponent;
let dropdownElement: HTMLElement;
let dropdownTriggerTextElement: HTMLElement;
let dropdownIconElement: HTMLElement;
let dropdownComponent: SprkDropdownComponent;
let dropdownTriggerElement: HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [
SprkDropdownComponent,
SprkIconComponent,
SprkLinkDirective,
TestWrapperComponent,
],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestWrapperComponent);
fixture.detectChanges();
wrapperComponent = fixture.componentInstance;
dropdownComponent = fixture.debugElement.query(
By.directive(SprkDropdownComponent),
).componentInstance;
dropdownTriggerElement = fixture.nativeElement.querySelector('a');
dropdownIconElement = fixture.nativeElement.querySelector('svg');
dropdownTriggerTextElement = fixture.nativeElement.querySelector('span');
dropdownComponent = fixture.debugElement.query(
By.directive(SprkDropdownComponent),
).componentInstance;
dropdownTriggerElement = fixture.nativeElement.querySelector('a');
});
it('should create', () => {
expect(dropdownComponent).toBeTruthy();
});
it('should have the correct base classes on dropdown content', () => {
expect(fixture.nativeElement.querySelector('.sprk-c-Dropdown')).toBeNull();
dropdownTriggerElement.click();
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.sprk-c-Dropdown'),
).not.toBeNull();
expect(
fixture.nativeElement.querySelector('.sprk-c-Dropdown').classList.length,
).toEqual(1);
});
it('should emit open and closed events when dropdown is opened or closed', (done) => {
let openEventEmitted = false;
let closedEventEmitted = false;
dropdownComponent.openedEvent.subscribe((g) => {
openEventEmitted = true;
done();
});
dropdownComponent.closedEvent.subscribe((g) => {
closedEventEmitted = true;
done();
});
dropdownTriggerElement.click();
expect(openEventEmitted).toEqual(true);
expect(closedEventEmitted).toEqual(false);
dropdownTriggerElement.click();
expect(closedEventEmitted).toEqual(true);
});
it('should add the correct classes if additionalClasses are supplied', () => {
wrapperComponent.additionalClasses = 'sprk-u-pam sprk-u-man';
dropdownElement = fixture.nativeElement.querySelector('.sprk-c-Dropdown');
expect(dropdownElement).toBeNull();
dropdownTriggerElement.click();
fixture.detectChanges();
dropdownElement = fixture.nativeElement.querySelector('.sprk-c-Dropdown');
expect(dropdownElement.classList).toContain('sprk-u-pam');
expect(dropdownElement.classList).toContain('sprk-u-man');
expect(dropdownElement.classList.length).toEqual(3);
});
it('should add data-id when idString has a value', () => {
const testString = 'element-id';
wrapperComponent.idString = testString;
fixture.detectChanges();
expect(dropdownTriggerElement.getAttribute('data-id')).toEqual(testString);
});
it('should not add data-id when idString has no value', () => {
wrapperComponent.idString = null;
fixture.detectChanges();
expect(dropdownTriggerElement.getAttribute('data-id')).toBeNull();
});
it('should add data-analytics when analyticsString has a value', () => {
const testString = 'element-id';
wrapperComponent.analyticsString = testString;
fixture.detectChanges();
expect(dropdownTriggerElement.getAttribute('data-analytics')).toEqual(
testString,
);
});
it('should not add data-analytics when analyticsString has no value', () => {
wrapperComponent.analyticsString = null;
fixture.detectChanges();
expect(dropdownTriggerElement.getAttribute('data-analytics')).toBeNull();
});
it('should render open with isOpen true', () => {
wrapperComponent.isOpen = true;
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.sprk-c-Dropdown'),
).not.toBeNull();
});
it('should open the dropdown on click', () => {
expect(fixture.nativeElement.querySelector('.sprk-c-Dropdown')).toBeNull();
dropdownTriggerElement.click();
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.sprk-c-Dropdown'),
).not.toBeNull();
});
it('should close the dropdown on click outside the element', () => {
dropdownTriggerElement.click();
fixture.detectChanges();
dropdownElement = fixture.nativeElement.querySelector('.sprk-c-Dropdown');
expect(dropdownElement).not.toBeNull();
dropdownElement.ownerDocument.dispatchEvent(new Event('click'));
fixture.detectChanges();
dropdownElement = fixture.nativeElement.querySelector('.sprk-c-Dropdown');
expect(dropdownElement).toBeNull();
});
it('should close the dropdown on focusin outside the element', () => {
dropdownTriggerElement.click();
fixture.detectChanges();
dropdownElement = fixture.nativeElement.querySelector('.sprk-c-Dropdown');
expect(dropdownElement).not.toBeNull();
dropdownElement.ownerDocument.dispatchEvent(new Event('focusin'));
fixture.detectChanges();
dropdownElement = fixture.nativeElement.querySelector('.sprk-c-Dropdown');
expect(dropdownElement).toBeNull();
});
it('should set active on click of a choice on an informational dropdown', () => {
fixture.detectChanges();
wrapperComponent.variant = 'informational';
wrapperComponent.choices = [
{
content: {
title: 'Choice Title',
infoLine1: 'Information about this choice',
infoLine2: 'Additional Information',
},
value: 'Choice Title 1',
active: false,
},
];
fixture.detectChanges();
dropdownTriggerElement.click();
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.sprk-c-Dropdown'),
).not.toBeNull();
const choice = fixture.nativeElement.querySelectorAll('li')[0];
choice.dispatchEvent(new Event('click'));
fixture.detectChanges();
dropdownTriggerElement.click();
fixture.detectChanges();
expect(
fixture.nativeElement.querySelectorAll('.sprk-c-Dropdown__link')[0]
.classList,
).toContain('sprk-c-Dropdown__link--active');
});
it('should set active on click of a choice on an informational dropdown if active is not defined initially', () => {
fixture.detectChanges();
wrapperComponent.variant = 'informational';
wrapperComponent.choices = [
{
content: {
title: 'Choice Title',
infoLine1: 'Information about this choice',
infoLine2: 'Additional Information',
},
value: 'Choice Title 1',
},
];
dropdownTriggerElement.click();
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.sprk-c-Dropdown'),
).not.toBeNull();
const choice = fixture.nativeElement.querySelectorAll('li')[0];
choice.dispatchEvent(new Event('click'));
fixture.detectChanges();
dropdownTriggerElement.click();
fixture.detectChanges();
expect(
fixture.nativeElement.querySelectorAll('.sprk-c-Dropdown__link')[0]
.classList,
).toContain('sprk-c-Dropdown__link--active');
});
it('should not set active on click of a choice on a base dropdown', () => {
fixture.detectChanges();
wrapperComponent.choices = [
{
text: 'Option 1',
value: 'Option 1',
},
{
text: 'Option 2',
value: 'Option 2',
},
];
dropdownTriggerElement.click();
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.sprk-c-Dropdown'),
).not.toBeNull();
const choice = fixture.nativeElement.querySelectorAll('li')[0];
choice.dispatchEvent(new Event('click'));
fixture.detectChanges();
dropdownTriggerElement.click();
fixture.detectChanges();
expect(
fixture.nativeElement.querySelectorAll('.sprk-c-Dropdown__link')[0]
.classList,
).not.toContain('sprk-c-Dropdown__link--active');
});
// TODO: #3800 remove dropdownType tests
it('should set active on click with dropdownType="informational"', () => {
wrapperComponent.dropdownType = 'informational';
wrapperComponent.choices = [{ text: 'asdf', value: 'asdf' }];
fixture.detectChanges();
dropdownTriggerElement.click();
fixture.detectChanges();
fixture.nativeElement
.querySelectorAll('li')[0]
.dispatchEvent(new Event('click'));
fixture.detectChanges();
dropdownTriggerElement.click();
fixture.detectChanges();
const isInformational = fixture.nativeElement
.querySelectorAll('.sprk-c-Dropdown__link')[0]
.classList.contains('sprk-c-Dropdown__link--active');
expect(isInformational).toEqual(true);
});
// TODO: #3800 remove dropdownType tests
it('should set active on click with dropdownType="base" and variant="informational"', () => {
wrapperComponent.dropdownType = 'base';
wrapperComponent.variant = 'informational';
wrapperComponent.choices = [{ text: 'asdf', value: 'asdf' }];
dropdownTriggerElement.click();
fixture.detectChanges();
fixture.nativeElement
.querySelectorAll('li')[0]
.dispatchEvent(new Event('click'));
fixture.detectChanges();
dropdownTriggerElement.click();
fixture.detectChanges();
const isInformational = fixture.nativeElement
.querySelectorAll('.sprk-c-Dropdown__link')[0]
.classList.contains('sprk-c-Dropdown__link--active');
expect(isInformational).toEqual(true);
});
it('should set href value if href is set on choice item', () => {
fixture.detectChanges();
wrapperComponent.choices = [
{
text: 'Option 1',
value: 'Option 1',
href: '/test',
},
];
dropdownTriggerElement.click();
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.sprk-c-Dropdown'),
).not.toBeNull();
const listLink = fixture.nativeElement.querySelector(
'.sprk-c-Dropdown__link',
);
expect(listLink.getAttribute('href')).toEqual('/test');
});
it('should set href value if routerLink is set on choice item', () => {
fixture.detectChanges();
wrapperComponent.choices = [
{
text: 'Option 1',
value: 'Option 1',
routerLink: '/router-test',
},
];
dropdownTriggerElement.click();
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.sprk-c-Dropdown'),
).not.toBeNull();
const listLink = fixture.nativeElement.querySelector(
'.sprk-c-Dropdown__link',
);
expect(listLink.getAttribute('href')).toEqual('/router-test');
});
it('should set a value if triggerAdditionalClasses has a value', () => {
wrapperComponent.triggerAdditionalClasses = 'sprk-u-man';
fixture.detectChanges();
expect(dropdownTriggerElement.classList.contains('sprk-u-man')).toEqual(
true,
);
});
it('should set a value if additionalTriggerClasses has a value', () => {
wrapperComponent.additionalTriggerClasses = 'sprk-u-man';
fixture.detectChanges();
expect(dropdownTriggerElement.classList.contains('sprk-u-man')).toEqual(
true,
);
});
// TODO: #3800 Remove `additionalTriggerClasses` tests
it('should prefer triggerAdditionalClasses over additionalTriggerClasses', () => {
wrapperComponent.additionalTriggerClasses = 'oldClass';
wrapperComponent.triggerAdditionalClasses = 'newClass';
fixture.detectChanges();
expect(dropdownTriggerElement.classList.contains('newClass')).toEqual(true);
});
// TODO: #3800 Remove `additionalTriggerTextClasses` tests
it('should set a value if additionalTriggerTextClasses has a value', () => {
wrapperComponent.additionalTriggerTextClasses = 'sprk-u-man';
fixture.detectChanges();
expect(dropdownTriggerTextElement.classList.contains('sprk-u-man')).toEqual(
true,
);
});
it('should set a value if triggerTextAdditionalClasses has a value', () => {
wrapperComponent.triggerTextAdditionalClasses = 'sprk-u-man';
fixture.detectChanges();
expect(dropdownTriggerTextElement.classList.contains('sprk-u-man')).toEqual(
true,
);
});
// TODO: #3800 Remove `additionalTriggerTextClasses` tests
it('should prefer triggerTextAdditionalClasses over additionalTriggerTextClasses', () => {
wrapperComponent.additionalTriggerTextClasses = 'oldClass';
wrapperComponent.triggerTextAdditionalClasses = 'newClass';
fixture.detectChanges();
expect(dropdownTriggerTextElement.classList.contains('newClass')).toEqual(
true,
);
});
it('should apply aria-label when triggerText is provided', () => {
wrapperComponent.triggerText = 'test';
wrapperComponent.screenReaderText = '';
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('a').getAttribute('aria-label'),
).toEqual('test');
});
it('should apply aria-label when screenReaderText is provided', () => {
wrapperComponent.triggerText = '';
wrapperComponent.screenReaderText = 'test';
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('a').getAttribute('aria-label'),
).toEqual('test');
});
it('should apply a default aria-label when none is provided', () => {
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('a').getAttribute('aria-label'),
).toEqual('Choose One');
});
// TODO: #3800 Remove `title` tests
it('should apply an aria-label to listbox when title provided', () => {
fixture.detectChanges();
wrapperComponent.title = 'test';
dropdownTriggerElement.click();
fixture.detectChanges();
const listBoxAria = fixture.nativeElement
.querySelector('.sprk-c-Dropdown__links')
.getAttribute('aria-label');
expect(listBoxAria).toEqual('test');
});
it('should apply an aria-label to listbox when heading provided', () => {
fixture.detectChanges();
wrapperComponent.heading = 'test';
dropdownTriggerElement.click();
fixture.detectChanges();
const listBoxAria = fixture.nativeElement
.querySelector('.sprk-c-Dropdown__links')
.getAttribute('aria-label');
expect(listBoxAria).toEqual('test');
});
// TODO: #3800 Remove `title` tests
it('should prefer heading over title', () => {
fixture.detectChanges();
wrapperComponent.title = 'title';
wrapperComponent.heading = 'heading';
dropdownTriggerElement.click();
fixture.detectChanges();
const listBoxAria = fixture.nativeElement
.querySelector('.sprk-c-Dropdown__links')
.getAttribute('aria-label');
expect(listBoxAria).toEqual('heading');
});
it('should apply an aria-label to listbox when screenReaderText is provided', () => {
fixture.detectChanges();
wrapperComponent.screenReaderText = 'test';
dropdownTriggerElement.click();
fixture.detectChanges();
const listBoxAria = fixture.nativeElement
.querySelector('.sprk-c-Dropdown__links')
.getAttribute('aria-label');
expect(listBoxAria).toEqual('test');
});
it('should apply a default aria-label to listbox when none is provided', () => {
dropdownTriggerElement.click();
fixture.detectChanges();
const listBoxAria = fixture.nativeElement
.querySelector('.sprk-c-Dropdown__links')
.getAttribute('aria-label');
expect(listBoxAria).toEqual('My Choices');
});
it('should not change trigger text if default choice option was not set', () => {
const expectedTriggerText = 'Make a selection...';
wrapperComponent.variant = 'informational';
wrapperComponent.choices = [
{
text: 'Option 1',
value: 'Option 1',
},
{
text: 'Option 2',
value: 'Option 2',
},
];
wrapperComponent.triggerText = expectedTriggerText;
fixture.detectChanges();
const triggerTextElement = fixture.nativeElement.getElementsByTagName(
'a',
)[0].firstElementChild;
expect(triggerTextElement.textContent).toEqual(expectedTriggerText);
});
it('should not change trigger text if default choice option specified, but type is not "informational"', () => {
wrapperComponent.choices = [
{
text: 'Option 1',
value: 'Option 1',
},
{
text: 'Option 2',
value: 'Option 2',
isDefault: true,
},
];
fixture.detectChanges();
const triggerTextElement = fixture.nativeElement.getElementsByTagName(
'a',
)[0].firstElementChild;
expect(triggerTextElement.textContent).not.toEqual(
dropdownComponent.choices[1].value,
);
});
it('should change trigger text if default choice option specified', () => {
wrapperComponent.variant = 'informational';
wrapperComponent.choices = [
{
text: 'Option 1',
value: 'Option 1',
},
{
text: 'Option 2',
value: 'Option 2',
isDefault: true,
},
];
fixture.detectChanges();
const triggerTextElement = fixture.nativeElement.getElementsByTagName(
'a',
)[0].firstElementChild;
expect(triggerTextElement.textContent).toEqual(
dropdownComponent.choices[1].value,
);
});
it('should change trigger text if choices changed', () => {
wrapperComponent.variant = 'informational';
wrapperComponent.choices = [
{
text: 'Option 1',
value: 'Option 1',
},
{
text: 'Option 2',
value: 'Option 2',
isDefault: true,
},
];
fixture.detectChanges();
wrapperComponent.choices = [
{
text: 'First Option',
value: 'First Option',
},
{
text: 'Second Option',
value: 'Second Option',
isDefault: true,
},
];
fixture.detectChanges();
const triggerTextElement = fixture.nativeElement.getElementsByTagName(
'a',
)[0].firstElementChild;
expect(triggerTextElement.textContent).toEqual(
dropdownComponent.choices[1].value,
);
});
it('should set active: true for default choice', () => {
wrapperComponent.variant = 'informational';
wrapperComponent.choices = [
{
text: 'Option 1',
value: 'Option 1',
active: true,
},
{
text: 'Option 2',
value: 'Option 2',
active: false,
isDefault: true,
},
];
dropdownTriggerElement.click();
fixture.detectChanges();
const triggerTextElement = fixture.nativeElement.querySelector(
'[aria-selected="true"]',
);
expect(triggerTextElement.textContent.trim()).toEqual(
dropdownComponent.choices[1].value,
);
});
// TODO: #3800 remove additionalIconClasses tests
it('should correctly add classes from additionalIconClasses', () => {
wrapperComponent.additionalIconClasses = 'testClass';
fixture.detectChanges();
expect(dropdownIconElement.classList.toString()).toContain('testClass');
});
it('should correctly add classes from iconAdditionalClasses', () => {
wrapperComponent.iconAdditionalClasses = 'testClass';
fixture.detectChanges();
expect(dropdownIconElement.classList.toString()).toContain('testClass');
});
// TODO: #3800 remove additionalIconClasses tests
it('should prefer iconAdditionalClasses over additionalIconClasses', () => {
wrapperComponent.additionalIconClasses = 'oldClass';
wrapperComponent.iconAdditionalClasses = 'newClass';
fixture.detectChanges();
expect(dropdownIconElement.classList.toString()).not.toContain('oldClass');
expect(dropdownIconElement.classList.toString()).toContain('newClass');
});
// TODO: #3800 remove triggerIconType tests
it('should add icon type from triggerIconType', () => {
wrapperComponent.triggerIconType = 'access';
fixture.detectChanges();
expect(
dropdownIconElement.querySelector('use').getAttribute('xlink:href'),
).toEqual('#access');
});
it('should add icon type from triggerIconName', () => {
wrapperComponent.triggerIconName = 'access';
fixture.detectChanges();
expect(
dropdownIconElement.querySelector('use').getAttribute('xlink:href'),
).toEqual('#access');
});
// TODO: #3800 remove triggerIconType tests
it('should prefer triggerIconName over triggerIconType', () => {
wrapperComponent.triggerIconType = 'bell';
wrapperComponent.triggerIconName = 'access';
fixture.detectChanges();
expect(
dropdownIconElement.querySelector('use').getAttribute('xlink:href'),
).toEqual('#access');
});
it('should not render empty paragraphs', () => {
fixture.detectChanges();
wrapperComponent.variant = 'informational';
wrapperComponent.choices = [
{
content: {
title: 'Choice Title',
infoLine1: 'Information about this choice',
infoLine2: 'Additional Information',
},
value: 'Choice Title 1',
active: false,
},
];
fixture.detectChanges();
dropdownTriggerElement.click();
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.sprk-c-Dropdown'),
).not.toBeNull();
let paragraphs = fixture.nativeElement.querySelectorAll('p');
expect(paragraphs.length).toEqual(3);
wrapperComponent.choices = [
{
content: {
title: 'Choice Title',
infoLine1: 'Information about this choice',
},
value: 'Choice Title 1',
active: false,
},
];
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.sprk-c-Dropdown'),
).not.toBeNull();
paragraphs = fixture.nativeElement.querySelectorAll('p');
expect(paragraphs.length).toEqual(2);
});
it('should not render empty paragraphs for choices using routerLink', () => {
fixture.detectChanges();
wrapperComponent.variant = 'informational';
wrapperComponent.choices = [
{
content: {
title: 'Choice Title',
infoLine1: 'Information about this choice',
infoLine2: 'Additional Information',
},
routerLink: '/router-test',
value: 'Choice Title 1',
active: false,
},
];
fixture.detectChanges();
dropdownTriggerElement.click();
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.sprk-c-Dropdown'),
).not.toBeNull();
let paragraphs = fixture.nativeElement.querySelectorAll('p');
expect(paragraphs.length).toEqual(3);
wrapperComponent.choices = [
{
content: {
title: 'Choice Title',
infoLine1: 'Information about this choice',
},
value: 'Choice Title 1',
routerLink: '/router-test',
active: false,
},
];
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.sprk-c-Dropdown'),
).not.toBeNull();
paragraphs = fixture.nativeElement.querySelectorAll('p');
expect(paragraphs.length).toEqual(2);
});
it('should apply selector Input to aria-label and title', () => {
wrapperComponent.selector = 'test';
fixture.detectChanges();
dropdownTriggerElement.click();
fixture.detectChanges();
const headerLink = fixture.nativeElement
.querySelector('.sprk-c-Dropdown__header a')
.getAttribute('aria-label');
expect(headerLink).toEqual('test');
const title = fixture.nativeElement.querySelector('.sprk-c-Dropdown__title')
.textContent;
expect(title).toEqual('test');
});
}); | the_stack |
export interface MountedSettingConf {
/**
* 配置名称
*/
ConfigDataName: string;
/**
* 挂载路径
*/
MountedPath: string;
/**
* 配置内容
*/
Data?: Array<Pair>;
}
/**
* ModifyServiceInfo返回参数结构体
*/
export interface ModifyServiceInfoResponse {
/**
* 成功与否
注意:此字段可能返回 null,表示取不到有效值。
*/
Result: boolean;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 数据卷挂载信息
*/
export interface StorageMountConf {
/**
* 数据卷名
*/
VolumeName: string;
/**
* 数据卷绑定路径
*/
MountPath: string;
}
/**
* CreateResource请求参数结构体
*/
export interface CreateResourceRequest {
/**
* 命名空间 Id
*/
NamespaceId: string;
/**
* 资源类型,目前支持文件系统:CFS;日志服务:CLS;注册中心:TSE_SRE
*/
ResourceType: string;
/**
* 资源 Id
*/
ResourceId: string;
/**
* 来源渠道
*/
SourceChannel?: number;
}
/**
* CreateServiceV2返回参数结构体
*/
export interface CreateServiceV2Response {
/**
* 服务code
*/
Result: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateCosTokenV2请求参数结构体
*/
export interface CreateCosTokenV2Request {
/**
* 服务ID
*/
ServiceId: string;
/**
* 包名
*/
PkgName: string;
/**
* optType 1上传 2查询
*/
OptType: number;
/**
* 来源 channel
*/
SourceChannel?: number;
/**
* 充当deployVersion入参
*/
TimeVersion?: string;
}
/**
* DeployServiceV2返回参数结构体
*/
export interface DeployServiceV2Response {
/**
* 版本ID(前端可忽略)
*/
Result: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 弹性伸缩配置
*/
export interface EsInfo {
/**
* 最小实例数
*/
MinAliveInstances: number;
/**
* 最大实例数
*/
MaxAliveInstances: number;
/**
* 弹性策略,1:cpu,2:内存
*/
EsStrategy: number;
/**
* 弹性扩缩容条件值
*/
Threshold: number;
/**
* 版本Id
*/
VersionId?: string;
}
/**
* DescribeNamespaces返回参数结构体
*/
export interface DescribeNamespacesResponse {
/**
* 返回结果
*/
Result: NamespacePage;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 服务端口映射
*/
export interface PortMapping {
/**
* 端口
*/
Port: number;
/**
* 映射端口
*/
TargetPort: number;
/**
* 协议栈 TCP/UDP
*/
Protocol: string;
}
/**
* RestartServiceRunPod请求参数结构体
*/
export interface RestartServiceRunPodRequest {
/**
* 环境id
*/
NamespaceId: string;
/**
* 服务名id
*/
ServiceId: string;
/**
* 名字
*/
PodName: string;
/**
* 单页条数
*/
Limit?: number;
/**
* 分页下标
*/
Offset?: number;
/**
* pod状态
*/
Status?: string;
/**
* 来源渠道
*/
SourceChannel?: number;
}
/**
* ModifyIngress返回参数结构体
*/
export interface ModifyIngressResponse {
/**
* 创建成功
注意:此字段可能返回 null,表示取不到有效值。
*/
Result: boolean;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteIngress请求参数结构体
*/
export interface DeleteIngressRequest {
/**
* tem NamespaceId
*/
NamespaceId: string;
/**
* eks namespace 名
*/
EksNamespace: string;
/**
* ingress 规则名
*/
Name: string;
/**
* 来源渠道
*/
SourceChannel?: number;
}
/**
* ModifyServiceInfo请求参数结构体
*/
export interface ModifyServiceInfoRequest {
/**
* 服务ID
*/
ServiceId: string;
/**
* 描述
*/
Description: string;
/**
* 来源渠道
*/
SourceChannel?: number;
}
/**
* CreateNamespace返回参数结构体
*/
export interface CreateNamespaceResponse {
/**
* 成功时为命名空间ID,失败为null
注意:此字段可能返回 null,表示取不到有效值。
*/
Result: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeRelatedIngresses请求参数结构体
*/
export interface DescribeRelatedIngressesRequest {
/**
* 环境 id
*/
NamespaceId?: string;
/**
* EKS namespace
*/
EksNamespace?: string;
/**
* 来源渠道
*/
SourceChannel?: number;
/**
* 服务 ID
*/
ServiceId?: string;
}
/**
* Cos token
*/
export interface CosToken {
/**
* 唯一请求 ID
*/
RequestId: string;
/**
* 存储桶桶名
*/
Bucket: string;
/**
* 存储桶所在区域
*/
Region: string;
/**
* 临时密钥的SecretId
*/
TmpSecretId: string;
/**
* 临时密钥的SecretKey
*/
TmpSecretKey: string;
/**
* 临时密钥的 sessionToken
*/
SessionToken: string;
/**
* 临时密钥获取的开始时间
*/
StartTime: string;
/**
* 临时密钥的 expiredTime
*/
ExpiredTime: string;
/**
* 包完整路径
*/
FullPath: string;
}
/**
* DescribeNamespaces请求参数结构体
*/
export interface DescribeNamespacesRequest {
/**
* 分页limit
*/
Limit?: number;
/**
* 分页下标
*/
Offset?: number;
/**
* 来源source
*/
SourceChannel?: number;
}
/**
* CreateCosToken请求参数结构体
*/
export interface CreateCosTokenRequest {
/**
* 服务ID
*/
ServiceId: string;
/**
* 服务版本ID
*/
VersionId: string;
/**
* 包名
*/
PkgName: string;
/**
* optType 1上传 2查询
*/
OptType: number;
/**
* 来源 channel
*/
SourceChannel?: number;
}
/**
* DeployServiceV2请求参数结构体
*/
export interface DeployServiceV2Request {
/**
* 服务ID
*/
ServiceId: string;
/**
* 容器端口
*/
ContainerPort: number;
/**
* 初始化 pod 数
*/
InitPodNum: number;
/**
* cpu规格
*/
CpuSpec: number;
/**
* 内存规格
*/
MemorySpec: number;
/**
* 环境ID
*/
NamespaceId: string;
/**
* 镜像仓库
*/
ImgRepo?: string;
/**
* 版本描述信息
*/
VersionDesc?: string;
/**
* 启动参数
*/
JvmOpts?: string;
/**
* 弹性伸缩配置,不传默认不启用弹性伸缩配置
*/
EsInfo?: EsInfo;
/**
* 环境变量配置
*/
EnvConf?: Array<Pair>;
/**
* 日志配置
*/
LogConfs?: Array<string>;
/**
* 数据卷配置
*/
StorageConfs?: Array<StorageConf>;
/**
* 数据卷挂载配置
*/
StorageMountConfs?: Array<StorageMountConf>;
/**
* 部署类型。
- JAR:通过 jar 包部署
- WAR:通过 war 包部署
- IMAGE:通过镜像部署
*/
DeployMode?: string;
/**
* 部署类型为 IMAGE 时,该参数表示镜像 tag。
部署类型为 JAR/WAR 时,该参数表示包版本号。
*/
DeployVersion?: string;
/**
* 包名。使用 JAR 包或者 WAR 包部署的时候必填。
*/
PkgName?: string;
/**
* JDK 版本。
- KONA:使用 kona jdk。
- OPEN:使用 open jdk。
*/
JdkVersion?: string;
/**
* 安全组ID s
*/
SecurityGroupIds?: Array<string>;
/**
* 日志输出配置
*/
LogOutputConf?: LogOutputConf;
/**
* 来源渠道
*/
SourceChannel?: number;
/**
* 版本描述
*/
Description?: string;
/**
* 镜像命令
*/
ImageCommand?: string;
/**
* 镜像命令参数
*/
ImageArgs?: Array<string>;
/**
* 服务端口映射
*/
PortMappings?: Array<PortMapping>;
/**
* 是否添加默认注册中心配置
*/
UseRegistryDefaultConfig?: boolean;
/**
* 挂载配置信息
*/
SettingConfs?: Array<MountedSettingConf>;
/**
* eks 访问设置
*/
EksService?: EksService;
/**
* 要回滚到的历史版本id
*/
VersionId?: string;
/**
* 启动后执行的脚本
*/
PostStart?: string;
/**
* 停止前执行的脚本
*/
PreStop?: string;
/**
* 分批发布策略配置
*/
DeployStrategyConf?: DeployStrategyConf;
/**
* 存活探针配置
*/
Liveness?: HealthCheckConfig;
/**
* 就绪探针配置
*/
Readiness?: HealthCheckConfig;
}
/**
* ModifyIngress请求参数结构体
*/
export interface ModifyIngressRequest {
/**
* Ingress 规则配置
*/
Ingress: IngressInfo;
/**
* 来源渠道
*/
SourceChannel?: number;
}
/**
* GenerateDownloadUrl返回参数结构体
*/
export interface GenerateDownloadUrlResponse {
/**
* 包下载临时链接
注意:此字段可能返回 null,表示取不到有效值。
*/
Result: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeRelatedIngresses返回参数结构体
*/
export interface DescribeRelatedIngressesResponse {
/**
* ingress 数组
注意:此字段可能返回 null,表示取不到有效值。
*/
Result: Array<IngressInfo>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateNamespace请求参数结构体
*/
export interface CreateNamespaceRequest {
/**
* 命名空间名称
*/
NamespaceName: string;
/**
* 私有网络名称
*/
Vpc: string;
/**
* 子网列表
*/
SubnetIds: Array<string>;
/**
* 命名空间描述
*/
Description?: string;
/**
* K8s version
*/
K8sVersion?: string;
/**
* 来源渠道
*/
SourceChannel?: number;
/**
* 是否开启tsw服务
*/
EnableTswTraceService?: boolean;
}
/**
* DescribeIngresses请求参数结构体
*/
export interface DescribeIngressesRequest {
/**
* namespace id
*/
NamespaceId?: string;
/**
* namespace
*/
EksNamespace?: string;
/**
* 来源渠道
*/
SourceChannel?: number;
/**
* ingress 规则名列表
*/
Names?: Array<string>;
}
/**
* 版本pod列表
*/
export interface DescribeRunPodPage {
/**
* 分页下标
*/
Offset: number;
/**
* 单页条数
*/
Limit: number;
/**
* 总数
*/
TotalCount: number;
/**
* 请求id
*/
RequestId: string;
/**
* 条目
*/
PodList: Array<RunVersionPod>;
}
/**
* DescribeServiceRunPodListV2请求参数结构体
*/
export interface DescribeServiceRunPodListV2Request {
/**
* 环境id
*/
NamespaceId: string;
/**
* 服务名id
*/
ServiceId: string;
/**
* 单页条数,默认值20
*/
Limit?: number;
/**
* 分页下标,默认值0
*/
Offset?: number;
/**
* 实例状态
- Running
- Pending
- Error
*/
Status?: string;
/**
* 实例名字
*/
PodName?: string;
/**
* 来源渠道
*/
SourceChannel?: number;
}
/**
* 日志输出配置
*/
export interface LogOutputConf {
/**
* 日志消费端类型
*/
OutputType: string;
/**
* cls日志集
*/
ClsLogsetName?: string;
/**
* cls日志主题
*/
ClsLogTopicId?: string;
/**
* cls日志集id
*/
ClsLogsetId?: string;
/**
* cls日志名称
*/
ClsLogTopicName?: string;
}
/**
* DescribeIngresses返回参数结构体
*/
export interface DescribeIngressesResponse {
/**
* ingress 数组
注意:此字段可能返回 null,表示取不到有效值。
*/
Result: Array<IngressInfo>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* Ingress 配置
*/
export interface IngressInfo {
/**
* tem namespaceId
注意:此字段可能返回 null,表示取不到有效值。
*/
NamespaceId: string;
/**
* eks namespace
*/
EksNamespace: string;
/**
* ip version
*/
AddressIPVersion: string;
/**
* ingress name
*/
Name: string;
/**
* rules 配置
*/
Rules: Array<IngressRule>;
/**
* clb ID
注意:此字段可能返回 null,表示取不到有效值。
*/
ClbId?: string;
/**
* tls 配置
注意:此字段可能返回 null,表示取不到有效值。
*/
Tls?: Array<IngressTls>;
/**
* eks clusterId
注意:此字段可能返回 null,表示取不到有效值。
*/
ClusterId?: string;
/**
* clb ip
注意:此字段可能返回 null,表示取不到有效值。
*/
Vip?: string;
/**
* 创建时间
注意:此字段可能返回 null,表示取不到有效值。
*/
CreateTime?: string;
/**
* 是否混合 https,默认 false,可选值 true 代表有 https 协议监听
*/
Mixed?: boolean;
}
/**
* DeleteIngress返回参数结构体
*/
export interface DeleteIngressResponse {
/**
* 是否删除成功
*/
Result: boolean;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* RestartServiceRunPod返回参数结构体
*/
export interface RestartServiceRunPodResponse {
/**
* 返回结果
注意:此字段可能返回 null,表示取不到有效值。
*/
Result: boolean;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyNamespace请求参数结构体
*/
export interface ModifyNamespaceRequest {
/**
* 环境id
*/
NamespaceId: string;
/**
* 命名空间名称
*/
NamespaceName?: string;
/**
* 命名空间描述
*/
Description?: string;
/**
* 私有网络名称
*/
Vpc?: string;
/**
* 子网网络
*/
SubnetIds?: Array<string>;
/**
* 来源渠道
*/
SourceChannel?: number;
}
/**
* Ingress 规则 backend 配置
*/
export interface IngressRuleBackend {
/**
* eks service 名
*/
ServiceName: string;
/**
* eks service 端口
*/
ServicePort: number;
}
/**
* DescribeIngress返回参数结构体
*/
export interface DescribeIngressResponse {
/**
* Ingress 规则配置
*/
Result: IngressInfo;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateCosToken返回参数结构体
*/
export interface CreateCosTokenResponse {
/**
* 成功时为CosToken对象,失败为null
注意:此字段可能返回 null,表示取不到有效值。
*/
Result: CosToken;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ingress rule 配置
*/
export interface IngressRule {
/**
* ingress rule value
*/
Http: IngressRuleValue;
/**
* host 地址
注意:此字段可能返回 null,表示取不到有效值。
*/
Host?: string;
/**
* 协议,选项为 http, https,默认为 http
*/
Protocol?: string;
}
/**
* Ingress Rule Path 配置
*/
export interface IngressRulePath {
/**
* path 信息
*/
Path: string;
/**
* backend 配置
*/
Backend: IngressRuleBackend;
}
/**
* 存储卷配置
*/
export interface StorageConf {
/**
* 存储卷名称
*/
StorageVolName: string;
/**
* 存储卷路径
*/
StorageVolPath: string;
/**
* 存储卷IP
注意:此字段可能返回 null,表示取不到有效值。
*/
StorageVolIp?: string;
}
/**
* ModifyNamespace返回参数结构体
*/
export interface ModifyNamespaceResponse {
/**
* 成功时为命名空间ID,失败为null
注意:此字段可能返回 null,表示取不到有效值。
*/
Result: boolean;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 版本pod
*/
export interface RunVersionPod {
/**
* shell地址
*/
Webshell: string;
/**
* pod的id
*/
PodId: string;
/**
* 状态
*/
Status: string;
/**
* 创建时间
*/
CreateTime: string;
/**
* 实例的ip
*/
PodIp: string;
/**
* 可用区
注意:此字段可能返回 null,表示取不到有效值。
*/
Zone: string;
/**
* 部署版本
注意:此字段可能返回 null,表示取不到有效值。
*/
DeployVersion: string;
/**
* 重启次数
注意:此字段可能返回 null,表示取不到有效值。
*/
RestartCount: number;
}
/**
* Ingress Rule Value 配置
*/
export interface IngressRuleValue {
/**
* rule 整体配置
*/
Paths: Array<IngressRulePath>;
}
/**
* CreateResource返回参数结构体
*/
export interface CreateResourceResponse {
/**
* 成功与否
注意:此字段可能返回 null,表示取不到有效值。
*/
Result: boolean;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeServiceRunPodListV2返回参数结构体
*/
export interface DescribeServiceRunPodListV2Response {
/**
* 返回结果
*/
Result: DescribeRunPodPage;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 命名空间对象
*/
export interface TemNamespaceInfo {
/**
* 命名空间id
*/
NamespaceId: string;
/**
* 渠道
*/
Channel: string;
/**
* 命名空间名称
*/
NamespaceName: string;
/**
* 区域名称
*/
Region: string;
/**
* 命名空间描述
注意:此字段可能返回 null,表示取不到有效值。
*/
Description: string;
/**
* 状态,1:已销毁;0:正常
*/
Status: number;
/**
* vpc网络
*/
Vpc: string;
/**
* 创建时间
*/
CreateDate: string;
/**
* 修改时间
*/
ModifyDate: string;
/**
* 修改人
*/
Modifier: string;
/**
* 创建人
*/
Creator: string;
/**
* 服务数
*/
ServiceNum: number;
/**
* 运行实例数
*/
RunInstancesNum: number;
/**
* 子网络
*/
SubnetId: string;
/**
* tcb环境状态
*/
TcbEnvStatus: string;
/**
* eks cluster status
*/
ClusterStatus: string;
/**
* 是否开启tsw
*/
EnableTswTraceService: boolean;
}
/**
* 命名空间分页
*/
export interface NamespacePage {
/**
* 分页内容
*/
Records: Array<TemNamespaceInfo>;
/**
* 总数
*/
Total: number;
/**
* 条目数
*/
Size: number;
/**
* 页数
*/
Pages: number;
}
/**
* 健康检查配置
*/
export interface HealthCheckConfig {
/**
* 支持的健康检查类型,如 HttpGet,TcpSocket,Exec
*/
Type: string;
/**
* 仅当健康检查类型为 HttpGet 时有效,表示协议类型,如 HTTP,HTTPS
*/
Protocol?: string;
/**
* 仅当健康检查类型为 HttpGet 时有效,表示请求路径
*/
Path?: string;
/**
* 仅当健康检查类型为 Exec 时有效,表示执行的脚本内容
*/
Exec?: string;
/**
* 仅当健康检查类型为 HttpGet\TcpSocket 时有效,表示请求路径
*/
Port?: number;
/**
* 检查延迟开始时间,单位为秒,默认为 0
*/
InitialDelaySeconds?: number;
/**
* 超时时间,单位为秒,默认为 1
*/
TimeoutSeconds?: number;
/**
* 间隔时间,单位为秒,默认为 10
*/
PeriodSeconds?: number;
}
/**
* CreateCosTokenV2返回参数结构体
*/
export interface CreateCosTokenV2Response {
/**
* 成功时为CosToken对象,失败为null
注意:此字段可能返回 null,表示取不到有效值。
*/
Result: CosToken;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ingress tls 配置
*/
export interface IngressTls {
/**
* host 数组, 空数组表示全部域名的默认证书
*/
Hosts: Array<string>;
/**
* secret name,如使用证书,则填空字符串
*/
SecretName: string;
/**
* SSL Certificate Id
*/
CertificateId?: string;
}
/**
* GenerateDownloadUrl请求参数结构体
*/
export interface GenerateDownloadUrlRequest {
/**
* 服务ID
*/
ServiceId: string;
/**
* 包名
*/
PkgName: string;
/**
* 需要下载的包版本
*/
DeployVersion: string;
/**
* 来源 channel
*/
SourceChannel?: number;
}
/**
* 分批发布策略配置
*/
export interface DeployStrategyConf {
/**
* 总分批数
*/
TotalBatchCount?: number;
/**
* beta分批实例数
*/
BetaBatchNum?: number;
/**
* 分批策略:0-全自动,1-全手动,beta分批一定是手动的,这里的策略指定的是剩余批次
*/
DeployStrategyType?: number;
/**
* 每批暂停间隔
*/
BatchInterval?: number;
}
/**
* DescribeIngress请求参数结构体
*/
export interface DescribeIngressRequest {
/**
* tem namespaceId
*/
NamespaceId: string;
/**
* eks namespace 名
*/
EksNamespace: string;
/**
* ingress 规则名
*/
Name: string;
/**
* 来源渠道
*/
SourceChannel?: number;
}
/**
* CreateServiceV2请求参数结构体
*/
export interface CreateServiceV2Request {
/**
* 服务名
*/
ServiceName: string;
/**
* 描述
*/
Description: string;
/**
* 是否使用默认镜像服务 1-是,0-否
*/
UseDefaultImageService?: number;
/**
* 如果是绑定仓库,绑定的仓库类型,0-个人版,1-企业版
*/
RepoType?: number;
/**
* 企业版镜像服务的实例id
*/
InstanceId?: string;
/**
* 绑定镜像服务器地址
*/
RepoServer?: string;
/**
* 绑定镜像仓库名
*/
RepoName?: string;
/**
* 来源渠道
*/
SourceChannel?: number;
/**
* 服务所在子网
*/
SubnetList?: Array<string>;
/**
* 编程语言
- JAVA
- OTHER
*/
CodingLanguage?: string;
/**
* 部署方式
- IMAGE
- JAR
- WAR
*/
DeployMode?: string;
}
/**
* eks service info
*/
export interface EksService {
/**
* service name
*/
Name?: string;
/**
* 可用端口
*/
Ports?: Array<number>;
/**
* yaml 内容
*/
Yaml?: string;
/**
* 服务名
注意:此字段可能返回 null,表示取不到有效值。
*/
ServiceName?: string;
/**
* 版本名
注意:此字段可能返回 null,表示取不到有效值。
*/
VersionName?: string;
/**
* 内网ip
注意:此字段可能返回 null,表示取不到有效值。
*/
ClusterIp?: Array<string>;
/**
* 外网ip
注意:此字段可能返回 null,表示取不到有效值。
*/
ExternalIp?: string;
/**
* 访问类型,可选值:
- EXTERNAL(公网访问)
- VPC(vpc内访问)
- CLUSTER(集群内访问)
注意:此字段可能返回 null,表示取不到有效值。
*/
Type?: string;
/**
* 子网ID,只在类型为vpc访问时才有值
注意:此字段可能返回 null,表示取不到有效值。
*/
SubnetId?: string;
/**
* 负载均衡ID,只在外网访问和vpc内访问才有值,默认自动创建
注意:此字段可能返回 null,表示取不到有效值。
*/
LoadBalanceId?: string;
/**
* 端口映射
注意:此字段可能返回 null,表示取不到有效值。
*/
PortMappings?: Array<PortMapping>;
}
/**
* 键值对
*/
export interface Pair {
/**
* 建
*/
Key: string;
/**
* 值
*/
Value: string;
} | the_stack |
import {BacklogClientImpl, issueToObject, objectToPayload, DateFormatter} from "./BacklogClient"
import {Issue, IssueType, Priority, User, Category, Version, CustomField} from "./datas"
import {None, Some} from "./Option"
import {Http} from "./Http"
import {isEmptyList} from "./List"
describe("BacklogClient", function () {
class FakeHttp implements Http {
public get(uri: string): JSON {
if (uri === "https://testspace.backlog.jp/api/v2/projects/SPR?apiKey=testapikeystring") {
return this.toJson(this.getProject())
}
if (uri === "https://testspace.backlog.jp/api/v2/projects/12345/users?apiKey=testapikeystring") {
return this.toJson(this.getUsers())
}
if (uri === "https://testspace.backlog.jp/api/v2/projects/12345/issueTypes?apiKey=testapikeystring") {
return this.toJson(this.getIssueTypes())
}
if (uri === "https://testspace.backlog.jp/api/v2/projects/12345/categories?apiKey=testapikeystring") {
return this.toJson(this.getCategories())
}
if (uri === "https://testspace.backlog.jp/api/v2/projects/12345/versions?apiKey=testapikeystring") {
return this.toJson(this.getVersions())
}
if (uri === "https://testspace.backlog.jp/api/v2/issues/1234567890?apiKey=testapikeystring") {
return this.toJson(this.getIssue())
}
if (uri === "https://testspace.backlog.jp/api/v2/projects/12345/customFields?apiKey=testapikeystring") {
return this.toJson(this.getCustomFields())
}
return this.toJson("{}")
}
public post(uri: string, data: any): JSON {
return this.toJson("{}")
}
private toJson(text): JSON {
return JSON.parse(text)
}
private getProject(): string {
return `{
"id": 12345,
"projectKey": "SPR",
"name": "SPR",
"chartEnabled": true,
"subtaskingEnabled": true,
"projectLeaderCanEditProjectLeader": false,
"useWikiTreeView": true,
"textFormattingRule": "backlog",
"archived": false,
"displayOrder": 2147483646
}`
}
private getUsers(): string {
return `[
{
"id": 111222,
"userId": "shomatan",
"name": "shomatan",
"roleType": 1,
"lang": "en",
"mailAddress": "shoma.nishitateno@gas-test.com",
"nulabAccount": null
},
{
"id": 777666,
"userId": "USER2",
"name": "USER2",
"roleType": 2,
"lang": null,
"mailAddress": "user2@gas-test.com",
"nulabAccount": null
}]`
}
private getIssueTypes(): string {
return `[
{
"id": 12200,
"projectId": 12345,
"name": "Task",
"color": "#7ea800",
"displayOrder": 0
},
{
"id": 12201,
"projectId": 12345,
"name": "Bug",
"color": "#990000",
"displayOrder": 1
},
{
"id": 12202,
"projectId": 12345,
"name": "Request",
"color": "#ff9200",
"displayOrder": 2
}]`
}
private getCategories(): string {
return `[
{
"id": 88765,
"name": "CatA",
"displayOrder": 2147483646
}]`
}
private getVersions(): string {
return `[
{
"id": 121212,
"projectId": 12345,
"name": "1.0.0",
"description": null,
"startDate": null,
"releaseDueDate": null,
"archived": false,
"displayOrder": 0
},
{
"id": 121209,
"projectId": 12345,
"name": "0.1.0",
"description": null,
"startDate": null,
"releaseDueDate": null,
"archived": true,
"displayOrder": 2
},
{
"id": 121213,
"projectId": 12345,
"name": "0.9.0",
"description": null,
"startDate": null,
"releaseDueDate": null,
"archived": false,
"displayOrder": 3
}]`
}
private getIssue(): string {
return `{
"id": 1234567890,
"projectId": 12345,
"issueKey": "SPR-777",
"keyId": 777,
"issueType": {
"id": 400999,
"projectId": 12345,
"name": "Task",
"color": "#7ea800",
"displayOrder": 0
},
"summary": "This is a test issue",
"description": "- [ ] aa - [ ] bb",
"resolution": null,
"priority": {
"id": 3,
"name": "Normal"
},
"status": {
"id": 1,
"name": "Open"
},
"assignee": {
"id": 123321,
"userId": "shomatan",
"name": "shomatan",
"roleType": 1,
"lang": "en",
"mailAddress": "shoma.nishitateno@gas-test.com",
"nulabAccount": null
},
"category": [],
"versions": [],
"milestone": [],
"startDate": null,
"dueDate": "2018-05-10T00:00:00Z",
"estimatedHours": null,
"actualHours": null,
"parentIssueId": 7777777,
"createdUser": {
"id": 123321,
"userId": "shomatan",
"name": "shomatan",
"roleType": 1,
"lang": "en",
"mailAddress": "shoma.nishitateno@gas-test.com",
"nulabAccount": null
},
"created": "2018-05-10T23:38:48Z",
"updatedUser": {
"id": 123321,
"userId": "shomatan",
"name": "shomatan",
"roleType": 1,
"lang": "en",
"mailAddress": "shoma.nishitateno@gas-test.com",
"nulabAccount": null
},
"updated": "2018-05-10T23:38:48Z",
"customFields": [],
"attachments": [],
"sharedFiles": [],
"stars": []
}`
}
private getCustomFields(): string {
return `[
{
"id": 51218,
"typeId": 3,
"version": 1528072392000,
"name": "number",
"description": "",
"required": false,
"useIssueType": false,
"applicableIssueTypes": [],
"displayOrder": 2141183646,
"min": null,
"max": null,
"initialValue": null,
"unit": null
},
{
"id": 51129,
"typeId": 1,
"version": 1528075236000,
"name": "text",
"description": "",
"required": true,
"useIssueType": false,
"applicableIssueTypes": [111],
"displayOrder": 2147223646
},
{
"id": 83747,
"typeId": 5,
"version": 1528075236340,
"name": "single",
"description": "",
"required": false,
"useIssueType": false,
"applicableIssueTypes": [],
"displayOrder": 2147223646,
"items": [
{
"id": 1,
"name": "Windows 8",
"displayOrder": 0
},
{
"id": 2,
"name": "macOS",
"displayOrder": 0
}
]
}]`
}
}
class FakeDateFormatter implements DateFormatter {
public dateToString = (date: Date): string => ""
}
const client = new BacklogClientImpl(new FakeHttp, "testspace", "backlog.jp", "testapikeystring", new FakeDateFormatter)
test("Get project", function () {
const result = client.getProjectV2("SPR")
expect(result.isRight).toBe(true)
result.map(project => {
expect(project.projectKey).toBe("SPR")
expect(project.id).toBe(12345)
})
})
test("Get users", function () {
const users = client.getUsersV2(12345)
expect(users.length).toBe(2)
expect(users[0].name).toBe("shomatan")
expect(users[1].id).toBe(777666)
expect(users[1].name).toBe("USER2")
})
test("Get issue types", function () {
const issueTypes = client.getIssueTypesV2(12345)
expect(issueTypes.length).toBe(3)
expect(issueTypes[0].name).toBe("Task")
expect(issueTypes[1].name).toBe("Bug")
expect(issueTypes[2].name).toBe("Request")
})
test("Get categories", function () {
const categories = client.getCategoriesV2(12345)
expect(categories.length).toBe(1)
expect(categories[0].id).toBe(88765)
expect(categories[0].name).toBe("CatA")
})
test("Get versions", function () {
const versions = client.getVersionsV2(12345)
expect(versions.length).toBe(2)
expect(versions[0].id).toBe(121212)
expect(versions[0].name).toBe("1.0.0")
expect(versions[1].id).toBe(121213)
expect(versions[1].name).toBe("0.9.0")
})
test("Get an issue", function () {
const maybeIssue = client.getIssueV2("1234567890")
expect(maybeIssue.isDefined).toBe(true)
maybeIssue.map(issue => {
expect(issue.id).toBe(1234567890)
expect(issue.summary).toBe("This is a test issue")
issue.description.map(description => expect(description).toBe("- [ ] aa - [ ] bb"))
expect(issue.startDate.isDefined).toBe(false)
expect(issue.dueDate.isDefined).toBe(true)
expect(issue.estimatedHours.isDefined).toBe(false)
expect(issue.actualHours.isDefined).toBe(false)
expect(issue.issueType.name).toBe("Task")
expect(issue.categories.length).toBe(0)
expect(issue.versions.length).toBe(0)
expect(issue.milestones.length).toBe(0)
expect(issue.priority.name).toBe("Normal")
expect(issue.assignee.isDefined).toBe(true)
expect(issue.parentIssueId.isDefined).toBe(true)
issue.parentIssueId.map(parentIssueId => expect(parentIssueId).toBe(7777777))
})
})
test("Get custom field definitions", function () {
const CustomFieldDefinitions = client.getCustomFieldsV2(12345)
expect(CustomFieldDefinitions.length).toBe(3)
expect(CustomFieldDefinitions[0].id).toBe(51218)
expect(CustomFieldDefinitions[0].name).toBe("number")
expect(CustomFieldDefinitions[0].required).toBe(false)
expect(isEmptyList(CustomFieldDefinitions[0].applicableIssueTypes)).toBe(true)
expect(CustomFieldDefinitions[1].id).toBe(51129)
expect(CustomFieldDefinitions[1].name).toBe("text")
expect(CustomFieldDefinitions[1].required).toBe(true)
expect(CustomFieldDefinitions[1].items.isDefined).toBe(false)
expect(isEmptyList(CustomFieldDefinitions[1].applicableIssueTypes)).toBe(false)
expect(CustomFieldDefinitions[1].applicableIssueTypes[0]).toBe(111)
expect(CustomFieldDefinitions[2].id).toBe(83747)
expect(CustomFieldDefinitions[2].name).toBe("single")
expect(CustomFieldDefinitions[2].required).toBe(false)
expect(isEmptyList(CustomFieldDefinitions[2].applicableIssueTypes)).toBe(true)
expect(CustomFieldDefinitions[2].items.isDefined).toBe(true)
CustomFieldDefinitions[2].items.map(items => expect(items.length).toBe(2))
})
})
describe("BacklogClient", function () {
class FakeDateFormatter implements DateFormatter {
public dateToString = (date: Date): string => `${date.getUTCFullYear()}-${this.padding2(date.getUTCMonth() + 1)}-${this.padding2(date.getUTCDate())}`
padding2 = (num: number): string => (`0` + num).slice(-2)
}
const maxIssue = Issue(
0,
"",
123,
"test summary",
Some("description"),
Some(new Date("Sun Jul 01 2018 00:00:00 GMT")), // startDate
Some(new Date("Sun Jul 02 2018 00:00:00 GMT")), // dueDate
Some(1.25), // estimatedHours
Some(3.3), // actualHours
IssueType(1, "issue type"),
[Category(11, "cat1"), Category(12, "cat2")], // category
[Version(23, "v1"), Version(24, "v2"), Version(44, "v3")], // version
[Version(50, "m1")], // milestone
Priority(2, "priority"),
Some(User(3, "user")),
Some("*"),
[CustomField(1, 3, "abc"), CustomField(2, 1, 123)]
)
const minIssue = Issue(
0,
"",
12345,
"test 1",
None(),
None(), // startDate
None(), // dueDate
None(), // estimatedHours
None(), // actualHours
IssueType(12, "issue type12"),
[], // category
[], // version
[], // milestone
Priority(100, "priority100"),
None(),
None(),
[] // custom field
)
test("issue to object", function () {
const actual1 = issueToObject(maxIssue, new FakeDateFormatter)
expect(actual1.projectId).toBe(123)
expect(actual1.summary).toBe("test summary")
expect(actual1.description).toBe("description")
expect(actual1.startDate).toEqual("2018-07-01")
expect(actual1.dueDate).toEqual("2018-07-02")
expect(actual1.estimatedHours).toEqual(1.25)
expect(actual1.actualHours).toEqual(3.3)
expect(actual1.issueTypeId).toEqual(1)
expect(actual1.categoryId).toEqual([11, 12])
expect(actual1.versionId).toEqual([23, 24, 44])
expect(actual1.milestoneId).toEqual([50])
expect(actual1.priorityId).toEqual(2)
expect(actual1.assigneeId).toEqual(3)
expect(actual1.parentIssueId).toEqual("*")
const actual2 = issueToObject(minIssue, new FakeDateFormatter)
expect(actual2.projectId).toBe(12345)
expect(actual2.summary).toBe("test 1")
expect(actual2.description).toBe(undefined)
expect(actual2.startDate).toEqual(undefined)
expect(actual2.dueDate).toEqual(undefined)
expect(actual2.estimatedHours).toEqual(undefined)
expect(actual2.actualHours).toEqual(undefined)
expect(actual2.issueTypeId).toEqual(12)
expect(actual2.categoryIds).toEqual(undefined)
expect(actual2.versionIds).toEqual(undefined)
expect(actual2.milestoneIds).toEqual(undefined)
expect(actual2.priorityId).toEqual(100)
expect(actual2.assigneeId).toEqual(undefined)
expect(actual2.parentIssueId).toEqual(undefined)
})
test("issue to object", function () {
const obj1 = issueToObject(minIssue, new FakeDateFormatter)
const actual1 = objectToPayload(obj1)
expect(actual1).toEqual("projectId=12345&summary=test%201&issueTypeId=12&priorityId=100")
const obj2 = issueToObject(maxIssue, new FakeDateFormatter)
const actual2 = objectToPayload(obj2)
expect(actual2).toEqual(
"projectId=123&summary=test%20summary&description=description&startDate=2018-07-01&dueDate=2018-07-02&estimatedHours=1.25&actualHours=3.3&issueTypeId=1&categoryId[]=11&categoryId[]=12&versionId[]=23&versionId[]=24&versionId[]=44&milestoneId[]=50&priorityId=2&assigneeId=3&parentIssueId=*&customField_1=abc&customField_2=123"
)
})
}) | the_stack |
import { arrayiffy } from "arrayiffy-if-string";
interface Obj {
[key: string]: any;
}
function isObj(something: any): boolean {
return (
something && typeof something === "object" && !Array.isArray(something)
);
}
function isStr(something: any): boolean {
return typeof something === "string";
}
interface Opts {
cb:
| undefined
| null
| ((
wholeCharacterOutside?: string | undefined,
theRemainderOfTheString?: string,
firstCharOutsideIndex?: number
) => string | boolean);
i: boolean;
trimBeforeMatching: boolean;
trimCharsBeforeMatching: string | string[];
maxMismatches: number;
firstMustMatch: boolean;
lastMustMatch: boolean;
hungry: boolean;
}
const defaults: Opts = {
cb: undefined,
i: false,
trimBeforeMatching: false,
trimCharsBeforeMatching: [],
maxMismatches: 0,
firstMustMatch: false,
lastMustMatch: false,
hungry: false,
};
const defaultGetNextIdx = (index: number) => index + 1;
// eslint-disable-next-line consistent-return
function march(
str: string,
position: number,
whatToMatchVal: (() => string) | string,
originalOpts?: Partial<Opts>,
special = false,
getNextIdx = defaultGetNextIdx
) {
console.log(`057 \u001b[${35}m${"CALLED march()"}\u001b[${39}m`);
console.log(
`======\nargs:
${`\u001b[${33}m${`str`}\u001b[${39}m`} = ${str}
${`\u001b[${33}m${`position`}\u001b[${39}m`} = ${position}
${`\u001b[${33}m${`whatToMatchVal`}\u001b[${39}m`} = ${whatToMatchVal}
${`\u001b[${33}m${`originalOpts`}\u001b[${39}m`} = ${JSON.stringify(
originalOpts,
null,
4
)}
${`\u001b[${33}m${`special`}\u001b[${39}m`} = ${special}
======`
);
const whatToMatchValVal =
typeof whatToMatchVal === "function" ? whatToMatchVal() : whatToMatchVal;
// early ending case if matching EOL being at 0-th index:
if (+position < 0 && special && whatToMatchValVal === "EOL") {
console.log("077 EARLY ENDING, return true");
return whatToMatchValVal;
}
const opts: Opts = { ...defaults, ...originalOpts };
console.log(
`084 ${`\u001b[${33}m${"position"}\u001b[${39}m`} = ${JSON.stringify(
position,
null,
4
)}`
);
if (position >= str.length && !special) {
console.log(
`093 starting index is beyond the string length so RETURN FALSE`
);
return false;
}
// The "charsToCheckCount" varies, it decreases with skipped characters,
// as long as "maxMismatches" allows. It's not the count of how many
// characters de-facto have been matched from the source.
let charsToCheckCount = special ? 1 : whatToMatchVal.length;
console.log(`102 starting charsToCheckCount = ${charsToCheckCount}`);
// this is the counter of real characters matched. It is not reduced
// from the holes in matched. For example, if source is "abc" and
// maxMismatches=1 and we have "ac", result of the match will be true,
// the following var will be equal to 2, meaning we matched two
// characters:
let charsMatchedTotal = 0;
// used to catch frontal false positives, where too-eager matching
// depletes the mismatches allowance before precisely matching the exact
// string that follows, yielding too early false-positive start
let patienceReducedBeforeFirstMatch = false;
let lastWasMismatched: false | number = false; // value is "false" or index of where it was activated
// if no character was ever matched, even through if opts.maxMismatches
// would otherwise allow to skip characters, this will act as a last
// insurance - at least one character must have been matched to yield a
// positive result!
let atLeastSomethingWasMatched = false;
let patience = opts.maxMismatches;
let i = position;
console.log(
`128 FIY, ${`\u001b[${33}m${`i`}\u001b[${39}m`} = ${JSON.stringify(
i,
null,
4
)}`
);
console.log(
`135 FIY, ${`\u001b[${33}m${`str`}\u001b[${39}m`} = ${JSON.stringify(
str,
null,
4
)}`
);
// internal-use flag, not the same as "atLeastSomethingWasMatched":
let somethingFound = false;
// these two drive opts.firstMustMatch and opts.lastMustMatch:
let firstCharacterMatched = false;
let lastCharacterMatched = false;
// bail early if there's whitespace in front, imagine:
// abc important}
// ^
// start, match ["!important"], matchRightIncl()
//
// in case above, "c" consumed 1 patience, let's say 1 is left,
// we stumble upon "i" where "!" is missing. "c" is false start.
function whitespaceInFrontOfFirstChar() {
return (
// it's a first letter match
charsMatchedTotal === 1 &&
// and character in front exists
// str[i - 1] &&
// and it's whitespace
// !str[i - 1].trim() &&
// some patience has been consumed already
patience < opts.maxMismatches - 1
);
}
while (str[i]) {
const nextIdx = getNextIdx(i);
console.log(
`173 \u001b[${36}m${`===============================`}\u001b[${39}m \u001b[${35}m${`str[ ${i} ] = ${
str[i] && str[i].trim() ? str[i] : JSON.stringify(str[i], null, 4)
}`}\u001b[${39}m \u001b[${36}m${`===============================`}\u001b[${39}m\n`
);
if (opts.trimBeforeMatching && str[i].trim() === "") {
console.log("179 trimmed");
if (!str[nextIdx] && special && whatToMatchVal === "EOL") {
console.log(
"182 start/end of string reached, matching to EOL, so return true"
);
return true;
}
i = getNextIdx(i);
continue;
}
console.log(
`191 ${`\u001b[${33}m${"opts.trimCharsBeforeMatching"}\u001b[${39}m`} = ${JSON.stringify(
opts.trimCharsBeforeMatching,
null,
4
)}`
);
console.log(
`198 ${`\u001b[${33}m${`opts.trimCharsBeforeMatching.includes("${str[i]}")`}\u001b[${39}m`} = ${JSON.stringify(
(opts as Obj).trimCharsBeforeMatching.includes(str[i]),
null,
4
)}`
);
if (
(opts &&
!opts.i &&
opts.trimCharsBeforeMatching &&
opts.trimCharsBeforeMatching.includes(str[i])) ||
(opts &&
opts.i &&
opts.trimCharsBeforeMatching &&
(opts.trimCharsBeforeMatching as string[])
.map((val) => val.toLowerCase())
.includes(str[i].toLowerCase()))
) {
console.log("217 char is in the skip list");
if (special && whatToMatchVal === "EOL" && !str[nextIdx]) {
// return true because we reached the zero'th index, exactly what we're looking for
console.log(
"221 RETURN true because it's EOL next, exactly what we're looking for"
);
return true;
}
i = getNextIdx(i);
continue;
}
console.log(
`229 ${`\u001b[${33}m${"charsToCheckCount"}\u001b[${39}m`} = ${JSON.stringify(
charsToCheckCount,
null,
4
)}`
);
console.log(
`236 whatToMatchVal[charsToCheckCount - 1] = whatToMatchVal[${
charsToCheckCount - 1
}] = ${(whatToMatchVal as string)[charsToCheckCount - 1]}`
);
console.log(
`241 whatToMatchVal[charsToCheckCount - 2]whatToMatchVal[charsToCheckCount - 1] = whatToMatchVal[${
charsToCheckCount - 2
}]whatToMatchVal[${charsToCheckCount - 1}] = ${
(whatToMatchVal as string)[charsToCheckCount - 2]
}${(whatToMatchVal as string)[charsToCheckCount - 1]}`
);
const charToCompareAgainst =
nextIdx > i
? (whatToMatchVal as string)[whatToMatchVal.length - charsToCheckCount]
: (whatToMatchVal as string)[charsToCheckCount - 1];
console.log(" ");
console.log(`254 \u001b[${35}m${"██ str[i]"}\u001b[${39}m = ${str[i]}`);
console.log(
`256 \u001b[${35}m${"██ charToCompareAgainst"}\u001b[${39}m = ${charToCompareAgainst}`
);
// let's match
if (
(!opts.i && str[i] === charToCompareAgainst) ||
(opts.i && str[i].toLowerCase() === charToCompareAgainst.toLowerCase())
) {
if (!somethingFound) {
somethingFound = true;
}
if (!atLeastSomethingWasMatched) {
atLeastSomethingWasMatched = true;
}
// if this was the first character from the "to-match" list, flip the flag
if (charsToCheckCount === whatToMatchVal.length) {
firstCharacterMatched = true;
console.log(
`275 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} firstCharacterMatched = true`
);
// now, if the first character was matched and yet, patience was
// reduced already, this means there's a false beginning in front
if (patience !== opts.maxMismatches) {
console.log(
`282 RETURN ${`\u001b[${31}m${`false`}\u001b[${39}m`} because patience was consumed already, before matching this first character!`
);
return false;
}
} else if (charsToCheckCount === 1) {
lastCharacterMatched = true;
console.log(
`289 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} lastCharacterMatched = true`
);
}
console.log(" ");
console.log(`294 ${`\u001b[${32}m${`MATCHED!`}\u001b[${39}m`}`);
console.log(" ");
charsToCheckCount -= 1;
charsMatchedTotal++;
console.log(
`299 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`charsToCheckCount`}\u001b[${39}m`} = ${charsToCheckCount}; ${`\u001b[${33}m${`charsMatchedTotal`}\u001b[${39}m`} = ${charsMatchedTotal}`
);
// bail early if there's whitespace in front, imagine:
// abc important}
// ^
// start, match ["!important"], matchRightIncl()
//
// in case above, "c" consumed 1 patience, let's say 1 is left,
// we stumble upon "i" where "!" is missing. "c" is false start.
if (whitespaceInFrontOfFirstChar()) {
console.log(`310 ${`\u001b[${31}m${`RETURN false.`}\u001b[${39}m`}`);
return false;
}
if (!charsToCheckCount) {
console.log(
`316 all chars matched, ${`\u001b[${32}m${`RETURN`}\u001b[${39}m`}: ${i}; charsToCheckCount = ${charsToCheckCount}; patience = ${patience}`
);
return (
// either it was not a perfect match
charsMatchedTotal !== whatToMatchVal.length ||
// or it was, and in that case, no patience was reduced
// (if a perfect match was found, yet some "patience" was reduced,
// that means we have false positive characters)
patience === opts.maxMismatches ||
// mind you, it can be a case of rogue characters in-between
// the what was matched, imagine:
// source: "abxcd", matching ["bc"], maxMismatches=1
// in above case, charsMatchedTotal === 2 and whatToMatchVal ("bc") === 2
// - we want to exclude cases of frontal false positives, like:
// source: "xy abc", match "abc", maxMismatches=2, start at 0
// ^
// match form here to the right
!patienceReducedBeforeFirstMatch
? i
: false
);
}
console.log(
`340 ${`\u001b[${32}m${`${`\u001b[${32}m${`OK.`}\u001b[${39}m`} Reduced charsToCheckCount to ${charsToCheckCount}`}\u001b[${39}m`}`
);
} else {
console.log(" ");
console.log(`344 ${`\u001b[${31}m${`DIDN'T MATCH!`}\u001b[${39}m`}`);
console.log(" ");
console.log(`346 str[i = ${i}] = ${JSON.stringify(str[i], null, 4)}`);
console.log(
`348 whatToMatchVal[whatToMatchVal.length - charsToCheckCount = ${
whatToMatchVal.length - charsToCheckCount
}] = ${JSON.stringify(
(whatToMatchVal as string)[whatToMatchVal.length - charsToCheckCount],
null,
4
)}`
);
if (!patienceReducedBeforeFirstMatch && !charsMatchedTotal) {
patienceReducedBeforeFirstMatch = true;
console.log(
`360 SET ${`\u001b[${33}m${`patienceReducedBeforeFirstMatch`}\u001b[${39}m`} = ${JSON.stringify(
patienceReducedBeforeFirstMatch,
null,
4
)}`
);
}
if (opts.maxMismatches && patience && i) {
patience -= 1;
console.log(
`371 ${`\u001b[${31}m${`DECREASE`}\u001b[${39}m`} patience to ${patience}`
);
// the bigger the maxMismatches, the further away we must check for
// alternative matches
for (let y = 0; y <= patience; y++) {
console.log(
`378 █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ current mismatch limit = ${y}`
);
// maybe str[i] will match against next charToCompareAgainst?
const nextCharToCompareAgainst =
nextIdx > i
? (whatToMatchVal as string)[
whatToMatchVal.length - charsToCheckCount + 1 + y
]
: (whatToMatchVal as string)[charsToCheckCount - 2 - y];
console.log(" ");
console.log(
`██ ${`\u001b[${33}m${`whatToMatchVal.length`}\u001b[${39}m`} = ${JSON.stringify(
whatToMatchVal.length,
null,
4
)}`
);
console.log(
`██ ${`\u001b[${33}m${`charsToCheckCount`}\u001b[${39}m`} = ${JSON.stringify(
charsToCheckCount,
null,
4
)}`
);
console.log(
`405 ${`\u001b[${35}m${`██ MAYBE NEXT CHAR WILL MATCH?`}\u001b[${39}m`}`
);
console.log(
`408 \u001b[${35}m${"██ str[i]"}\u001b[${39}m = ${str[i]}`
);
console.log(
`411 \u001b[${35}m${"██ nextCharToCompareAgainst"}\u001b[${39}m = ${nextCharToCompareAgainst}`
);
console.log(" ");
const nextCharInSource = str[getNextIdx(i)];
console.log(
`418 ${`\u001b[${35}m${`██ OR MAYBE CURRENT CHAR CAN BE SKIPPED?`}\u001b[${39}m`}`
);
console.log(
`421 \u001b[${35}m${"██ nextCharInSource"}\u001b[${39}m = ${nextCharInSource}`
);
console.log(
`424 \u001b[${35}m${"██ nextCharToCompareAgainst"}\u001b[${39}m = ${nextCharToCompareAgainst}`
);
console.log(" ");
if (
nextCharToCompareAgainst &&
((!opts.i && str[i] === nextCharToCompareAgainst) ||
(opts.i &&
str[i].toLowerCase() ===
nextCharToCompareAgainst.toLowerCase())) &&
// ensure we're not skipping the first enforced character:
(!opts.firstMustMatch ||
charsToCheckCount !== whatToMatchVal.length)
) {
console.log(" ");
console.log(`439 ${`\u001b[${32}m${`MATCHED!`}\u001b[${39}m`}`);
console.log(" ");
charsMatchedTotal++;
// bail early if there's whitespace in front, imagine:
// abc important}
// ^
// start, match ["!important"], matchRightIncl()
//
// in case above, "c" consumed 1 patience, let's say 1 is left,
// we stumble upon "i" where "!" is missing. "c" is false start.
if (whitespaceInFrontOfFirstChar()) {
console.log(
`452 ${`\u001b[${31}m${`RETURN false.`}\u001b[${39}m`}`
);
return false;
}
charsToCheckCount -= 2;
console.log(
`459 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`charsToCheckCount`}\u001b[${39}m`} = ${JSON.stringify(
charsToCheckCount,
null,
4
)}`
);
somethingFound = true;
break;
} else if (
nextCharInSource &&
nextCharToCompareAgainst &&
((!opts.i && nextCharInSource === nextCharToCompareAgainst) ||
(opts.i &&
nextCharInSource.toLowerCase() ===
nextCharToCompareAgainst.toLowerCase())) &&
// ensure we're not skipping the first enforced character:
(!opts.firstMustMatch ||
charsToCheckCount !== whatToMatchVal.length)
) {
console.log(" ");
console.log(`480 ${`\u001b[${32}m${`MATCHED!`}\u001b[${39}m`}`);
console.log(" ");
if (!charsMatchedTotal && !opts.hungry) {
console.log(
`485 ${`\u001b[${32}m${`RETURN`}\u001b[${39}m`} ${`\u001b[${31}m${`false`}\u001b[${39}m`}`
);
return false;
}
charsToCheckCount -= 1;
console.log(
`492 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`charsToCheckCount`}\u001b[${39}m`} = ${JSON.stringify(
charsToCheckCount,
null,
4
)}`
);
somethingFound = true;
break;
} else if (
nextCharToCompareAgainst === undefined &&
patience >= 0 &&
somethingFound &&
(!opts.firstMustMatch || firstCharacterMatched) &&
(!opts.lastMustMatch || lastCharacterMatched)
) {
// If "nextCharToCompareAgainst" is undefined, this
// means there are no more characters left to match,
// this is the last character to be matched.
// This means, if patience >= 0, this is it,
// the match is still positive.
console.log(
`514 ${`\u001b[${32}m${`STILL MATCHED DESPITE MISMATCH`}\u001b[${39}m`}, RETURN "${i}"`
);
return i;
}
// ███████████████████████████████████████
}
console.log(`521 █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ `);
if (!somethingFound) {
// if the character was rogue, we mark it:
lastWasMismatched = i;
console.log(
`527 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`lastWasMismatched`}\u001b[${39}m`} = ${lastWasMismatched}`
);
// patience--;
// console.log(
// `350 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`patience`}\u001b[${39}m`} = ${patience}`
// );
}
} else if (
i === 0 &&
charsToCheckCount === 1 &&
!opts.lastMustMatch &&
atLeastSomethingWasMatched
) {
console.log(`540 LAST CHARACTER. RETURN 0.`);
return 0;
} else {
console.log(`543 ${`\u001b[${31}m${`RETURN false.`}\u001b[${39}m`}`);
return false;
}
}
// turn off "lastWasMismatched" if it's on and it hasn't been activated
// on this current index:
if (lastWasMismatched !== false && lastWasMismatched !== i) {
lastWasMismatched = false;
console.log(
`553 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`lastWasMismatched`}\u001b[${39}m`} = ${lastWasMismatched}`
);
}
// if all was matched, happy days
if (charsToCheckCount < 1) {
console.log(
`560 all chars matched, ${`\u001b[${32}m${`RETURN`}\u001b[${39}m`} i: ${i}; charsToCheckCount = ${charsToCheckCount}`
);
return i;
}
// iterate onto the next index, otherwise while would loop infinitely
i = getNextIdx(i);
console.log(
`${`\u001b[${90}m${`--------------------- ending with: ---------------------`}\u001b[${39}m`}`
);
console.log(
`${`\u001b[${90}m${`charsToCheckCount = ${JSON.stringify(
charsToCheckCount,
null,
4
)}`}\u001b[${39}m`}`
);
console.log(
`${`\u001b[${90}m${`charsMatchedTotal = ${JSON.stringify(
charsMatchedTotal,
null,
4
)}`}\u001b[${39}m`}`
);
console.log(
`${`\u001b[${90}m${`lastWasMismatched = ${JSON.stringify(
lastWasMismatched,
null,
4
)}`}\u001b[${39}m`}`
);
console.log(
`${`\u001b[${90}m${`patience = ${JSON.stringify(
patience,
null,
4
)}`}\u001b[${39}m`}`
);
console.log(
`${`\u001b[${90}m${`atLeastSomethingWasMatched = ${JSON.stringify(
atLeastSomethingWasMatched,
null,
4
)}`}\u001b[${39}m`}`
);
console.log(
`${`\u001b[${90}m${`firstCharacterMatched = ${JSON.stringify(
firstCharacterMatched,
null,
4
)}`}\u001b[${39}m`}`
);
console.log(
`${`\u001b[${90}m${`lastCharacterMatched = ${JSON.stringify(
lastCharacterMatched,
null,
4
)}`}\u001b[${39}m`}`
);
}
console.log(`622 AFTER THE WHILE LOOP`);
if (charsToCheckCount > 0) {
if (special && whatToMatchValVal === "EOL") {
console.log(
`627 charsToCheckCount = ${charsToCheckCount};\nwent past the beginning of the string and EOL was queried to ${`\u001b[${32}m${`return TRUE`}\u001b[${39}m`}`
);
return true;
}
if (
opts &&
(opts as Obj).maxMismatches >= charsToCheckCount &&
atLeastSomethingWasMatched
) {
console.log(`636 RETURN ${lastWasMismatched || 0}`);
return lastWasMismatched || 0;
}
console.log(
`640 ${`\u001b[${31}m${`charsToCheckCount = ${charsToCheckCount} THEREFORE, returning FALSE`}\u001b[${39}m`}`
);
return false;
}
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
// Real deal
function main(
mode: "matchLeftIncl" | "matchLeft" | "matchRightIncl" | "matchRight",
str: string,
position: number,
originalWhatToMatch: (() => string) | string | string[],
originalOpts?: Partial<Opts>
): boolean | string {
// insurance
if (
isObj(originalOpts) &&
Object.prototype.hasOwnProperty.call(originalOpts, "trimBeforeMatching") &&
typeof (originalOpts as Obj).trimBeforeMatching !== "boolean"
) {
throw new Error(
`string-match-left-right/${mode}(): [THROW_ID_09] opts.trimBeforeMatching should be boolean!${
Array.isArray((originalOpts as Obj).trimBeforeMatching)
? ` Did you mean to use opts.trimCharsBeforeMatching?`
: ""
}`
);
}
const opts: Opts = { ...defaults, ...originalOpts };
if (typeof opts.trimCharsBeforeMatching === "string") {
// arrayiffy if needed:
opts.trimCharsBeforeMatching = arrayiffy(opts.trimCharsBeforeMatching);
}
// stringify all:
opts.trimCharsBeforeMatching = (opts as Obj).trimCharsBeforeMatching.map(
(el: any) => (isStr(el) ? el : String(el))
);
if (!isStr(str)) {
return false;
}
if (!str.length) {
return false;
}
if (!Number.isInteger(position) || position < 0) {
throw new Error(
`string-match-left-right/${mode}(): [THROW_ID_03] the second argument should be a natural number. Currently it's of a type: ${typeof position}, equal to:\n${JSON.stringify(
position,
null,
4
)}`
);
}
let whatToMatch;
let special;
if (isStr(originalWhatToMatch)) {
console.log("736");
whatToMatch = [originalWhatToMatch];
} else if (Array.isArray(originalWhatToMatch)) {
console.log("739");
whatToMatch = originalWhatToMatch;
} else if (!originalWhatToMatch) {
console.log("742");
whatToMatch = originalWhatToMatch;
} else if (typeof originalWhatToMatch === "function") {
console.log("745");
whatToMatch = [];
whatToMatch.push(originalWhatToMatch);
console.log(
`749 whatToMatch = ${whatToMatch}; Array.isArray(whatToMatch) = ${Array.isArray(
whatToMatch
)}; whatToMatch.length = ${whatToMatch.length}`
);
} else {
console.log("754");
throw new Error(
`string-match-left-right/${mode}(): [THROW_ID_05] the third argument, whatToMatch, is neither string nor array of strings! It's ${typeof originalWhatToMatch}, equal to:\n${JSON.stringify(
originalWhatToMatch,
null,
4
)}`
);
}
console.log("\n\n");
console.log(`765 whatToMatch = ${JSON.stringify(whatToMatch, null, 4)}`);
if (originalOpts && !isObj(originalOpts)) {
throw new Error(
`string-match-left-right/${mode}(): [THROW_ID_06] the fourth argument, options object, should be a plain object. Currently it's of a type "${typeof originalOpts}", and equal to:\n${JSON.stringify(
originalOpts,
null,
4
)}`
);
}
let culpritsIndex = 0;
let culpritsVal = "";
if (
opts &&
opts.trimCharsBeforeMatching &&
(opts.trimCharsBeforeMatching as string[]).some((el, i) => {
if (el.length > 1) {
culpritsIndex = i;
culpritsVal = el;
return true;
}
return false;
})
) {
throw new Error(
`string-match-left-right/${mode}(): [THROW_ID_07] the fourth argument, options object contains trimCharsBeforeMatching. It was meant to list the single characters but one of the entries at index ${culpritsIndex} is longer than 1 character, ${culpritsVal.length} (equals to ${culpritsVal}). Please split it into separate characters and put into array as separate elements.`
);
}
// action
// CASE 1. If it's driven by callback-only, the 3rd input argument, what to look
// for - is falsey - empty string within array (or not), OR given null
if (
!whatToMatch ||
!Array.isArray(whatToMatch) || // 0
(Array.isArray(whatToMatch) && !whatToMatch.length) || // []
(Array.isArray(whatToMatch) &&
whatToMatch.length === 1 &&
isStr(whatToMatch[0]) &&
!(whatToMatch[0] as string).trim()) // [""]
) {
if (typeof opts.cb === "function") {
console.log("811");
let firstCharOutsideIndex;
// matchLeft() or matchRightIncl() methods start at index "position"
let startingPosition = position;
if (mode === "matchLeftIncl" || mode === "matchRight") {
startingPosition += 1;
}
if (mode[5] === "L") {
for (let y = startingPosition; y--; ) {
// assemble the value of the current character
const currentChar = str[y];
// do the actual evaluation, is the current character non-whitespace/non-skiped
if (
(!opts.trimBeforeMatching ||
(opts.trimBeforeMatching &&
currentChar !== undefined &&
currentChar.trim())) &&
(!opts.trimCharsBeforeMatching ||
!opts.trimCharsBeforeMatching.length ||
(currentChar !== undefined &&
!opts.trimCharsBeforeMatching.includes(currentChar)))
) {
firstCharOutsideIndex = y;
break;
}
}
} else if (mode.startsWith("matchRight")) {
for (let y = startingPosition; y < str.length; y++) {
// assemble the value of the current character
const currentChar = str[y];
console.log(
`844 ${`\u001b[${33}m${"currentChar"}\u001b[${39}m`} = ${JSON.stringify(
currentChar,
null,
4
)}`
);
// do the actual evaluation, is the current character non-whitespace/non-skiped
if (
(!opts.trimBeforeMatching ||
(opts.trimBeforeMatching && currentChar.trim())) &&
(!opts.trimCharsBeforeMatching ||
!opts.trimCharsBeforeMatching.length ||
!opts.trimCharsBeforeMatching.includes(currentChar))
) {
console.log("858 breaking!");
firstCharOutsideIndex = y;
break;
}
}
}
if (firstCharOutsideIndex === undefined) {
console.log("865 RETURN false");
return false;
}
const wholeCharacterOutside = str[firstCharOutsideIndex];
const indexOfTheCharacterAfter = firstCharOutsideIndex + 1;
let theRemainderOfTheString = "";
if (indexOfTheCharacterAfter && indexOfTheCharacterAfter > 0) {
theRemainderOfTheString = str.slice(0, indexOfTheCharacterAfter);
}
if (mode[5] === "L") {
console.log(`877 ${`\u001b[${32}m${`CALL THE CB()`}\u001b[${39}m`}`);
return opts.cb(
wholeCharacterOutside,
theRemainderOfTheString,
firstCharOutsideIndex
);
}
// ELSE matchRight & matchRightIncl
if (firstCharOutsideIndex && firstCharOutsideIndex > 0) {
theRemainderOfTheString = str.slice(firstCharOutsideIndex);
}
console.log(`889 ${`\u001b[${32}m${`CALL THE CB()`}\u001b[${39}m`}`);
return opts.cb(
wholeCharacterOutside,
theRemainderOfTheString,
firstCharOutsideIndex
);
}
let extraNote = "";
if (!originalOpts) {
extraNote =
" More so, the whole options object, the fourth input argument, is missing!";
}
throw new Error(
`string-match-left-right/${mode}(): [THROW_ID_08] the third argument, "whatToMatch", was given as an empty string. This means, you intend to match purely by a callback. The callback was not set though, the opts key "cb" is not set!${extraNote}`
);
}
// Case 2. Normal operation where callback may or may not be present, but it is
// only accompanying the matching of what was given in 3rd input argument.
// Then if 3rd arg's contents were matched, callback is checked and its Boolean
// result is merged using logical "AND" - meaning both have to be true to yield
// final result "true".
for (let i = 0, len = whatToMatch.length; i < len; i++) {
console.log(
`914 matchLeft() LOOP ${i} ${`\u001b[${32}m${`=================================================================================`}\u001b[${39}m`} \n\n`
);
special = typeof whatToMatch[i] === "function";
console.log(`918 special = ${special}`);
console.log(
`921 🔥 whatToMatch no. ${i} = ${
whatToMatch[i]
} (type ${typeof whatToMatch[i]})`
);
console.log(`925 🔥 special = ${special}`);
// since input can be function, we need to grab the value explicitly:
const whatToMatchVal = whatToMatch[i];
let fullCharacterInFront;
let indexOfTheCharacterInFront;
let restOfStringInFront = "";
let startingPosition = position;
if (mode === "matchRight") {
startingPosition += 1;
} else if (mode === "matchLeft") {
startingPosition -= 1;
}
console.log(
`942 \u001b[${33}m${"march() called with:"}\u001b[${39}m\n* startingPosition = ${JSON.stringify(
startingPosition,
null,
4
)}\n* whatToMatchVal = "${whatToMatchVal}"\n`
);
console.log("\n\n\n\n\n\n");
console.log(
`950 ███████████████████████████████████████ march() STARTS BELOW ███████████████████████████████████████`
);
const found = march(
str,
startingPosition,
whatToMatchVal as string,
opts,
special,
(i2) => (mode[5] === "L" ? i2 - 1 : i2 + 1)
);
console.log(
`961 ███████████████████████████████████████ march() ENDED ABOVE ███████████████████████████████████████\n\n\n\n\n\n`
);
console.log(
`964 \u001b[${33}m${"found"}\u001b[${39}m = ${JSON.stringify(
found,
null,
4
)}`
);
// if march() returned positive result and it was "special" case,
// Bob's your uncle, here's the result:
if (
found &&
special &&
typeof whatToMatchVal === "function" &&
whatToMatchVal() === "EOL"
) {
console.log(`979 returning whatToMatchVal() = ${whatToMatchVal()}`);
return whatToMatchVal() &&
(opts.cb
? opts.cb(
fullCharacterInFront as string,
restOfStringInFront,
indexOfTheCharacterInFront as number
)
: true)
? whatToMatchVal()
: false;
}
// now, the "found" is the index of the first character of what was found.
// we need to calculate the character to the left/right of it:
if (Number.isInteger(found)) {
indexOfTheCharacterInFront = mode.startsWith("matchLeft")
? (found as number) - 1
: (found as number) + 1;
//
if (mode[5] === "L") {
restOfStringInFront = str.slice(0, found as number);
} else {
restOfStringInFront = str.slice(indexOfTheCharacterInFront);
}
}
if ((indexOfTheCharacterInFront as number) < 0) {
indexOfTheCharacterInFront = undefined;
}
if (str[indexOfTheCharacterInFront as number]) {
fullCharacterInFront = str[indexOfTheCharacterInFront as number];
}
console.log(
`1017 FINAL ${`\u001b[${33}m${`indexOfTheCharacterInFront`}\u001b[${39}m`} = ${JSON.stringify(
indexOfTheCharacterInFront,
null,
4
)}
${`\u001b[${33}m${`fullCharacterInFront`}\u001b[${39}m`} = ${JSON.stringify(
fullCharacterInFront,
null,
4
)}
${`\u001b[${33}m${`restOfStringInFront`}\u001b[${39}m`} = ${JSON.stringify(
restOfStringInFront,
null,
4
)}`
);
if (
Number.isInteger(found) &&
(opts.cb
? opts.cb(
fullCharacterInFront as string,
restOfStringInFront,
indexOfTheCharacterInFront as number
)
: true)
) {
console.log(
`1045 ${`\u001b[${32}m${`RETURN`}\u001b[${39}m`} ${`\u001b[${33}m${`whatToMatchVal`}\u001b[${39}m`} = ${JSON.stringify(
whatToMatchVal,
null,
4
)}`
);
return whatToMatchVal as string;
}
}
console.log(`1054 ${`\u001b[${32}m${`RETURN`}\u001b[${39}m`} false`);
return false;
}
// External API functions
function matchLeftIncl(
str: string,
position: number,
whatToMatch: (() => string) | string | string[],
opts?: Partial<Opts>
): boolean | string {
return main("matchLeftIncl", str, position, whatToMatch, opts);
}
function matchLeft(
str: string,
position: number,
whatToMatch: (() => string) | string | string[],
opts?: Partial<Opts>
): boolean | string {
return main("matchLeft", str, position, whatToMatch, opts);
}
function matchRightIncl(
str: string,
position: number,
whatToMatch: (() => string) | string | string[],
opts?: Partial<Opts>
): boolean | string {
return main("matchRightIncl", str, position, whatToMatch, opts);
}
function matchRight(
str: string,
position: number,
whatToMatch: (() => string) | string | string[],
opts?: Partial<Opts>
): boolean | string {
return main("matchRight", str, position, whatToMatch, opts);
}
export { matchLeftIncl, matchRightIncl, matchLeft, matchRight }; | the_stack |
import base = require("./crema-code-base");
import reader = require("./crema-code-reader");
import types = require("./crema-code-types");
// ------------------------------------------------------------------------------
// dataBase: default
// revision: 412
// requested revision: -1
// devmode: False
// hash value: f52bdea30268729d366eaeb9bd320df505a16dbf
// tags: All
// ------------------------------------------------------------------------------
export class ProjectInfoExportInfoRow extends base.CremaRow {
private tableExportInfo: ProjectInfoExportInfo;
private fieldID: number;
private fieldFileName: string;
private fieldTableName: string;
public constructor(row: reader.IRow, table: ProjectInfoExportInfo) {
super(row);
this.tableExportInfo = table;
this.fieldID = row.toInt32(0);
if (row.hasValue(1)) {
this.fieldFileName = row.toString(1);
}
if (row.hasValue(2)) {
this.fieldTableName = row.toString(2);
}
this.setKey(this.fieldID);
}
// creator: admin
// createdDateTime: 2017-10-26 오전 6:21:11
// modifier: admin
// modifiedDateTime: 2017-10-26 오전 6:21:41
public get ID(): number {
return this.fieldID;
}
// creator: admin
// createdDateTime: 2017-10-25 오전 8:35:20
// modifier: admin
// modifiedDateTime: 2017-10-26 오전 8:42:54
public get fileName(): string {
return this.fieldFileName;
}
// creator: admin
// createdDateTime: 2017-10-25 오전 8:35:02
// modifier: admin
// modifiedDateTime: 2017-10-26 오전 6:20:29
public get tableName(): string {
return this.fieldTableName;
}
public get table(): ProjectInfoExportInfo {
return this.tableExportInfo;
}
public get parent(): ProjectInfoRow {
return (<ProjectInfoRow>(this.parentInternal));
}
}
// createdDateTime: 2017-10-25 오전 8:34:43
// modifiedDateTime: 2017-10-26 오전 8:06:01
// contentsModifier: s2quake
// contentsModifiedDateTime: 2018-03-27 오전 5:13:04
export class ProjectInfoExportInfo extends base.CremaTable<ProjectInfoExportInfoRow> {
public static createFromTable(table: reader.ITable): ProjectInfoExportInfo {
if ((table.hashValue !== "06e32bd7a3bb2e2ca4e256312e847b3413b4bb5a")) {
throw new Error("ProjectInfo.ExportInfo 테이블과 데이터의 형식이 맞지 않습니다.");
}
let instance: ProjectInfoExportInfo = new ProjectInfoExportInfo();
instance.readFromTable(table);
return instance;
}
public static createFromRows(name: string, rows: ProjectInfoExportInfoRow[]): ProjectInfoExportInfo {
let instance: ProjectInfoExportInfo = new ProjectInfoExportInfo();
instance.readFromRows(name, rows);
return instance;
}
protected readFromRows(name: string, rows: ProjectInfoExportInfoRow[]): void {
super.readFromRows(name, rows);
}
public find(ID: number): ProjectInfoExportInfoRow {
return super.findRow(ID);
}
protected createRowInstance(row: reader.IRow, table: any): ProjectInfoExportInfoRow {
return new ProjectInfoExportInfoRow(row, (<ProjectInfoExportInfo>(table)));
}
protected readFromTable(table: reader.ITable): void {
super.readFromTable(table);
}
}
export class ProjectInfoRow extends base.CremaRow {
private static tableExportInfoEmpty: ProjectInfoExportInfo = new ProjectInfoExportInfo();
private tableProjectInfo: ProjectInfo;
private fieldKindType: types.KindType;
private fieldProjectType: types.ProjectType;
private fieldName: string;
private fieldProjectPath: string;
private tableExportInfo: ProjectInfoExportInfo;
public constructor(row: reader.IRow, table: ProjectInfo) {
super(row);
this.tableProjectInfo = table;
this.fieldKindType = row.toInt32(0);
this.fieldProjectType = row.toInt32(1);
this.fieldName = row.toString(2);
if (row.hasValue(3)) {
this.fieldProjectPath = row.toString(3);
}
this.setKey(this.fieldKindType, this.fieldProjectType, this.fieldName);
}
// creator: admin
// createdDateTime: 2017-10-25 오전 8:40:56
// modifier: admin
// modifiedDateTime: 2017-11-01 오전 8:22:11
public get kindType(): types.KindType {
return this.fieldKindType;
}
// creator: admin
// createdDateTime: 2017-11-01 오전 8:22:24
// modifier: admin
// modifiedDateTime: 2017-11-01 오전 8:23:24
public get projectType(): types.ProjectType {
return this.fieldProjectType;
}
// creator: admin
// createdDateTime: 2017-10-25 오전 8:38:54
// modifier: admin
// modifiedDateTime: 2017-10-25 오전 8:42:24
public get name(): string {
return this.fieldName;
}
// creator: admin
// createdDateTime: 2017-10-25 오전 8:25:15
// modifier: admin
// modifiedDateTime: 2017-10-25 오전 8:42:25
public get projectPath(): string {
return this.fieldProjectPath;
}
public get exportInfo(): ProjectInfoExportInfo {
if ((this.tableExportInfo == null)) {
return ProjectInfoRow.tableExportInfoEmpty;
}
return this.tableExportInfo;
}
public get table(): ProjectInfo {
return this.tableProjectInfo;
}
static setExportInfo(target: ProjectInfoRow, childName: string, childs: ProjectInfoExportInfoRow[]): void {
ProjectInfoRow.setParent<ProjectInfoRow, ProjectInfoExportInfoRow>(target, childs);
target.tableExportInfo = ProjectInfoExportInfo.createFromRows(childName, childs);
}
}
// modifier: admin
// modifiedDateTime: 2017-11-01 오전 8:22:24
// contentsModifier: s2quake
// contentsModifiedDateTime: 2018-03-27 오전 5:12:57
export class ProjectInfo extends base.CremaTable<ProjectInfoRow> {
private tableExportInfo: ProjectInfoExportInfo;
public get exportInfo(): ProjectInfoExportInfo {
return this.tableExportInfo;
}
public static createFromTable(table: reader.ITable): ProjectInfo {
if ((table.hashValue !== "b576d4aab4aaa0f758549efab982de6ceb5b7b66")) {
throw new Error("ProjectInfo 테이블과 데이터의 형식이 맞지 않습니다.");
}
let instance: ProjectInfo = new ProjectInfo();
instance.readFromTable(table);
return instance;
}
public static createFromRows(name: string, rows: ProjectInfoRow[]): ProjectInfo {
let instance: ProjectInfo = new ProjectInfo();
instance.readFromRows(name, rows);
return instance;
}
public find(kindType: types.KindType, projectType: types.ProjectType, name: string): ProjectInfoRow {
return super.findRow(kindType, projectType, name);
}
protected createRowInstance(row: reader.IRow, table: any): ProjectInfoRow {
return new ProjectInfoRow(row, (<ProjectInfo>(table)));
}
protected readFromTable(table: reader.ITable): void {
super.readFromTable(table);
this.tableExportInfo = ProjectInfoExportInfo.createFromTable(table.dataSet.tables[(table.name + ".ExportInfo")]);
this.setRelations((table.name + ".ExportInfo"), this.tableExportInfo.rows, ProjectInfoRow.setExportInfo);
}
}
export class StringTableRow extends base.CremaRow {
private tableStringTable: StringTable;
private fieldType: types.StringType;
private fieldName: string;
private fieldComment: string;
private fieldValue: string;
private fieldko_KR: string;
public constructor(row: reader.IRow, table: StringTable) {
super(row);
this.tableStringTable = table;
this.fieldType = row.toInt32(0);
this.fieldName = row.toString(1);
if (row.hasValue(2)) {
this.fieldComment = row.toString(2);
}
if (row.hasValue(3)) {
this.fieldValue = row.toString(3);
}
if (row.hasValue(4)) {
this.fieldko_KR = row.toString(4);
}
this.setKey(this.fieldType, this.fieldName);
}
// creator: admin
// createdDateTime: 2017-10-23 오전 7:16:08
// modifier: admin
// modifiedDateTime: 2017-10-23 오전 7:16:24
public get type(): types.StringType {
return this.fieldType;
}
// creator: admin
// createdDateTime: 2017-10-23 오전 7:16:14
// modifier: admin
// modifiedDateTime: 2017-10-23 오전 7:16:25
public get name(): string {
return this.fieldName;
}
// creator: admin
// createdDateTime: 2017-10-23 오전 7:16:18
// modifier: admin
// modifiedDateTime: 2017-10-23 오전 7:16:18
public get comment(): string {
return this.fieldComment;
}
// creator: admin
// createdDateTime: 2017-10-23 오전 7:16:22
// modifier: admin
// modifiedDateTime: 2017-10-23 오전 7:16:22
public get value(): string {
return this.fieldValue;
}
// creator: admin
// createdDateTime: 2017-10-23 오전 9:20:19
// modifier: admin
// modifiedDateTime: 2017-10-23 오전 9:20:19
public get ko_KR(): string {
return this.fieldko_KR;
}
public get table(): StringTable {
return this.tableStringTable;
}
}
// creator: admin
// createdDateTime: 2017-10-23 오전 7:16:01
// modifier: admin
// modifiedDateTime: 2017-10-25 오전 5:30:21
export class StringTable extends base.CremaTable<StringTableRow> {
public static createFromTable(table: reader.ITable): StringTable {
if ((table.hashValue !== "6c66b01d950836901feeeed701a0b36f5f3d58c1")) {
throw new Error("StringTable 테이블과 데이터의 형식이 맞지 않습니다.");
}
let instance: StringTable = new StringTable();
instance.readFromTable(table);
return instance;
}
public static createFromRows(name: string, rows: StringTableRow[]): StringTable {
let instance: StringTable = new StringTable();
instance.readFromRows(name, rows);
return instance;
}
public find(type: types.StringType, name: string): StringTableRow {
return super.findRow(type, name);
}
protected createRowInstance(row: reader.IRow, table: any): StringTableRow {
return new StringTableRow(row, (<StringTable>(table)));
}
protected readFromTable(table: reader.ITable): void {
super.readFromTable(table);
}
}
export class TestTableRow extends base.CremaRow {
private tableTestTable: TestTable;
private fieldKey: number;
private fieldValue: string;
private fieldDateTimePicker: Date;
private fieldTimePicker: number;
public constructor(row: reader.IRow, table: TestTable) {
super(row);
this.tableTestTable = table;
this.fieldKey = row.toInt32(0);
if (row.hasValue(1)) {
this.fieldValue = row.toString(1);
}
if (row.hasValue(2)) {
this.fieldDateTimePicker = row.toDateTime(2);
}
if (row.hasValue(3)) {
this.fieldTimePicker = row.toDuration(3);
}
this.setKey(this.fieldKey);
}
// creator: admin
// createdDateTime: 2017-11-01 오전 2:37:44
// modifier: admin
// modifiedDateTime: 2017-11-01 오전 2:38:12
public get key(): number {
return this.fieldKey;
}
// creator: admin
// createdDateTime: 2017-11-01 오전 2:37:57
// modifier: admin
// modifiedDateTime: 2017-11-01 오전 2:37:57
public get value(): string {
return this.fieldValue;
}
// creator: admin
// createdDateTime: 2017-11-01 오전 2:38:09
// modifier: admin
// modifiedDateTime: 2017-11-01 오전 2:38:09
public get dateTimePicker(): Date {
return this.fieldDateTimePicker;
}
// creator: admin
// createdDateTime: 2017-11-01 오전 4:10:41
// modifier: admin
// modifiedDateTime: 2017-11-01 오전 4:10:41
public get timePicker(): number {
return this.fieldTimePicker;
}
public get table(): TestTable {
return this.tableTestTable;
}
}
// modifier: admin
// modifiedDateTime: 2017-11-01 오전 4:10:41
// contentsModifier: admin
// contentsModifiedDateTime: 2017-11-01 오전 4:21:18
export class TestTable extends base.CremaTable<TestTableRow> {
public static createFromTable(table: reader.ITable): TestTable {
if ((table.hashValue !== "148d8eee57fb716dc0914b646b2f965325693a55")) {
throw new Error("TestTable 테이블과 데이터의 형식이 맞지 않습니다.");
}
let instance: TestTable = new TestTable();
instance.readFromTable(table);
return instance;
}
public static createFromRows(name: string, rows: TestTableRow[]): TestTable {
let instance: TestTable = new TestTable();
instance.readFromRows(name, rows);
return instance;
}
public find(key: number): TestTableRow {
return super.findRow(key);
}
protected createRowInstance(row: reader.IRow, table: any): TestTableRow {
return new TestTableRow(row, (<TestTable>(table)));
}
protected readFromTable(table: reader.ITable): void {
super.readFromTable(table);
}
}
export class CremaDataSet extends base.CremaData {
private _name: string;
private _revision: number;
private _typesHashValue: string;
private _tablesHashValue: string;
private _tags: string;
private tableClientApplicationHost: StringTable;
private tableClientBase: StringTable;
private tableClientConsole: StringTable;
private tableClientConverters: StringTable;
private tableClientDifferences: StringTable;
private tableClientFramework: StringTable;
private tableClientServices: StringTable;
private tableClientSmartSet: StringTable;
private tableClientTables: StringTable;
private tableClientTypes: StringTable;
private tableClientUsers: StringTable;
private tableCommonPresentation: StringTable;
private tableCommonServiceModel: StringTable;
private tableCommonServiceModel_Event: StringTable;
private tableCremaData: StringTable;
private tableCremaProjectInfo: ProjectInfo;
private tableModernUIFramework: StringTable;
private tableNtreevLibrary: StringTable;
private tableProjectInfo: ProjectInfo;
private tableServerServiceHosts: StringTable;
private tableStringTable: StringTable;
private tableStringTable11: StringTable;
private tableTestTable: TestTable;
public get name(): string {
return this._name;
}
public get revision(): number {
return this._revision;
}
public get typesHashValue(): string {
return this._typesHashValue;
}
public get tablesHashValue(): string {
return this._tablesHashValue;
}
public get tags(): string {
return this._tags;
}
public get clientApplicationHost(): StringTable {
return this.tableClientApplicationHost;
}
public get clientBase(): StringTable {
return this.tableClientBase;
}
public get clientConsole(): StringTable {
return this.tableClientConsole;
}
public get clientConverters(): StringTable {
return this.tableClientConverters;
}
public get clientDifferences(): StringTable {
return this.tableClientDifferences;
}
public get clientFramework(): StringTable {
return this.tableClientFramework;
}
public get clientServices(): StringTable {
return this.tableClientServices;
}
public get clientSmartSet(): StringTable {
return this.tableClientSmartSet;
}
public get clientTables(): StringTable {
return this.tableClientTables;
}
public get clientTypes(): StringTable {
return this.tableClientTypes;
}
public get clientUsers(): StringTable {
return this.tableClientUsers;
}
public get commonPresentation(): StringTable {
return this.tableCommonPresentation;
}
public get commonServiceModel(): StringTable {
return this.tableCommonServiceModel;
}
public get commonServiceModel_Event(): StringTable {
return this.tableCommonServiceModel_Event;
}
public get cremaData(): StringTable {
return this.tableCremaData;
}
public get cremaProjectInfo(): ProjectInfo {
return this.tableCremaProjectInfo;
}
public get modernUIFramework(): StringTable {
return this.tableModernUIFramework;
}
public get ntreevLibrary(): StringTable {
return this.tableNtreevLibrary;
}
public get projectInfo(): ProjectInfo {
return this.tableProjectInfo;
}
public get serverServiceHosts(): StringTable {
return this.tableServerServiceHosts;
}
public get stringTable(): StringTable {
return this.tableStringTable;
}
public get stringTable11(): StringTable {
return this.tableStringTable11;
}
public get testTable(): TestTable {
return this.tableTestTable;
}
public static createFromDataSet(dataSet: reader.IDataSet, verifyRevision: boolean): CremaDataSet {
let instance: CremaDataSet = new CremaDataSet();
instance.readFromDataSet(dataSet, verifyRevision);
return instance;
}
public static createFromFile(filename: string, verifyRevision: boolean): CremaDataSet {
let instance: CremaDataSet = new CremaDataSet();
instance.readFromFile(filename, verifyRevision);
return instance;
}
public readFromDataSet(dataSet: reader.IDataSet, verifyRevision: boolean): void {
if (("default" !== dataSet.name)) {
throw new Error("데이터의 이름이 코드 이름(default)과 다릅니다.");
}
if (("4b1da7ae630f37090a4cee6e3e446893c6ad9297" !== dataSet.typesHashValue)) {
throw new Error("타입 해시값이 \'4b1da7ae630f37090a4cee6e3e446893c6ad9297\'이 아닙니다.");
}
if (("f52bdea30268729d366eaeb9bd320df505a16dbf" !== dataSet.tablesHashValue)) {
throw new Error("테이블 해시값이 \'f52bdea30268729d366eaeb9bd320df505a16dbf\'이 아닙니다.");
}
if (((verifyRevision === true) && ((<number>(412)) !== dataSet.revision))) {
throw new Error("데이터의 리비전 코드 리비전(412)과 다릅니다.");
}
this._name = dataSet.name;
this._revision = dataSet.revision;
this._typesHashValue = dataSet.typesHashValue;
this._tablesHashValue = dataSet.tablesHashValue;
this._tags = dataSet.tags;
this.tableClientApplicationHost = StringTable.createFromTable(dataSet.tables.ClientApplicationHost);
this.tableClientBase = StringTable.createFromTable(dataSet.tables.ClientBase);
this.tableClientConsole = StringTable.createFromTable(dataSet.tables.ClientConsole);
this.tableClientConverters = StringTable.createFromTable(dataSet.tables.ClientConverters);
this.tableClientDifferences = StringTable.createFromTable(dataSet.tables.ClientDifferences);
this.tableClientFramework = StringTable.createFromTable(dataSet.tables.ClientFramework);
this.tableClientServices = StringTable.createFromTable(dataSet.tables.ClientServices);
this.tableClientSmartSet = StringTable.createFromTable(dataSet.tables.ClientSmartSet);
this.tableClientTables = StringTable.createFromTable(dataSet.tables.ClientTables);
this.tableClientTypes = StringTable.createFromTable(dataSet.tables.ClientTypes);
this.tableClientUsers = StringTable.createFromTable(dataSet.tables.ClientUsers);
this.tableCommonPresentation = StringTable.createFromTable(dataSet.tables.CommonPresentation);
this.tableCommonServiceModel = StringTable.createFromTable(dataSet.tables.CommonServiceModel);
this.tableCommonServiceModel_Event = StringTable.createFromTable(dataSet.tables.CommonServiceModel_Event);
this.tableCremaData = StringTable.createFromTable(dataSet.tables.CremaData);
this.tableCremaProjectInfo = ProjectInfo.createFromTable(dataSet.tables.CremaProjectInfo);
this.tableModernUIFramework = StringTable.createFromTable(dataSet.tables.ModernUIFramework);
this.tableNtreevLibrary = StringTable.createFromTable(dataSet.tables.NtreevLibrary);
this.tableProjectInfo = ProjectInfo.createFromTable(dataSet.tables.ProjectInfo);
this.tableServerServiceHosts = StringTable.createFromTable(dataSet.tables.ServerServiceHosts);
this.tableStringTable = StringTable.createFromTable(dataSet.tables.StringTable);
this.tableStringTable11 = StringTable.createFromTable(dataSet.tables.StringTable11);
this.tableTestTable = TestTable.createFromTable(dataSet.tables.TestTable);
}
public readFromFile(filename: string, verifyRevision: boolean): void {
this.readFromDataSet(reader.CremaReader.readFromFile(filename), verifyRevision);
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
/**
* Denotes one policy tag in a taxonomy.
*
* To get more information about PolicyTag, see:
*
* * [API documentation](https://cloud.google.com/data-catalog/docs/reference/rest/v1beta1/projects.locations.taxonomies.policyTags)
* * How-to Guides
* * [Official Documentation](https://cloud.google.com/data-catalog/docs)
*
* ## Example Usage
* ### Data Catalog Taxonomies Policy Tag Basic
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const myTaxonomy = new gcp.datacatalog.Taxonomy("myTaxonomy", {
* region: "us",
* displayName: "taxonomy_display_name",
* description: "A collection of policy tags",
* activatedPolicyTypes: ["FINE_GRAINED_ACCESS_CONTROL"],
* }, {
* provider: google_beta,
* });
* const basicPolicyTag = new gcp.datacatalog.PolicyTag("basicPolicyTag", {
* taxonomy: myTaxonomy.id,
* displayName: "Low security",
* description: "A policy tag normally associated with low security items",
* }, {
* provider: google_beta,
* });
* ```
* ### Data Catalog Taxonomies Policy Tag Child Policies
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const myTaxonomy = new gcp.datacatalog.Taxonomy("myTaxonomy", {
* region: "us",
* displayName: "taxonomy_display_name",
* description: "A collection of policy tags",
* activatedPolicyTypes: ["FINE_GRAINED_ACCESS_CONTROL"],
* }, {
* provider: google_beta,
* });
* const parentPolicy = new gcp.datacatalog.PolicyTag("parentPolicy", {
* taxonomy: myTaxonomy.id,
* displayName: "High",
* description: "A policy tag category used for high security access",
* }, {
* provider: google_beta,
* });
* const childPolicy = new gcp.datacatalog.PolicyTag("childPolicy", {
* taxonomy: myTaxonomy.id,
* displayName: "ssn",
* description: "A hash of the users ssn",
* parentPolicyTag: parentPolicy.id,
* }, {
* provider: google_beta,
* });
* const childPolicy2 = new gcp.datacatalog.PolicyTag("childPolicy2", {
* taxonomy: myTaxonomy.id,
* displayName: "dob",
* description: "The users date of birth",
* parentPolicyTag: parentPolicy.id,
* }, {
* provider: google_beta,
* dependsOn: [childPolicy],
* });
* ```
*
* ## Import
*
* PolicyTag can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:datacatalog/policyTag:PolicyTag default {{name}}
* ```
*/
export class PolicyTag extends pulumi.CustomResource {
/**
* Get an existing PolicyTag 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?: PolicyTagState, opts?: pulumi.CustomResourceOptions): PolicyTag {
return new PolicyTag(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:datacatalog/policyTag:PolicyTag';
/**
* Returns true if the given object is an instance of PolicyTag. 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 PolicyTag {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === PolicyTag.__pulumiType;
}
/**
* Resource names of child policy tags of this policy tag.
*/
public /*out*/ readonly childPolicyTags!: pulumi.Output<string[]>;
/**
* Description of this policy tag. It must: contain only unicode characters, tabs,
* newlines, carriage returns and page breaks; and be at most 2000 bytes long when
* encoded in UTF-8. If not set, defaults to an empty description.
* If not set, defaults to an empty description.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* User defined name of this policy tag. It must: be unique within the parent
* taxonomy; contain only unicode letters, numbers, underscores, dashes and spaces;
* not start or end with spaces; and be at most 200 bytes long when encoded in UTF-8.
*/
public readonly displayName!: pulumi.Output<string>;
/**
* Resource name of this policy tag, whose format is:
* "projects/{project}/locations/{region}/taxonomies/{taxonomy}/policyTags/{policytag}"
*/
public /*out*/ readonly name!: pulumi.Output<string>;
/**
* Resource name of this policy tag's parent policy tag.
* If empty, it means this policy tag is a top level policy tag.
* If not set, defaults to an empty string.
*/
public readonly parentPolicyTag!: pulumi.Output<string | undefined>;
/**
* Taxonomy the policy tag is associated with
*/
public readonly taxonomy!: pulumi.Output<string>;
/**
* Create a PolicyTag 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: PolicyTagArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: PolicyTagArgs | PolicyTagState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as PolicyTagState | undefined;
inputs["childPolicyTags"] = state ? state.childPolicyTags : undefined;
inputs["description"] = state ? state.description : undefined;
inputs["displayName"] = state ? state.displayName : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["parentPolicyTag"] = state ? state.parentPolicyTag : undefined;
inputs["taxonomy"] = state ? state.taxonomy : undefined;
} else {
const args = argsOrState as PolicyTagArgs | undefined;
if ((!args || args.displayName === undefined) && !opts.urn) {
throw new Error("Missing required property 'displayName'");
}
if ((!args || args.taxonomy === undefined) && !opts.urn) {
throw new Error("Missing required property 'taxonomy'");
}
inputs["description"] = args ? args.description : undefined;
inputs["displayName"] = args ? args.displayName : undefined;
inputs["parentPolicyTag"] = args ? args.parentPolicyTag : undefined;
inputs["taxonomy"] = args ? args.taxonomy : undefined;
inputs["childPolicyTags"] = undefined /*out*/;
inputs["name"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(PolicyTag.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering PolicyTag resources.
*/
export interface PolicyTagState {
/**
* Resource names of child policy tags of this policy tag.
*/
childPolicyTags?: pulumi.Input<pulumi.Input<string>[]>;
/**
* Description of this policy tag. It must: contain only unicode characters, tabs,
* newlines, carriage returns and page breaks; and be at most 2000 bytes long when
* encoded in UTF-8. If not set, defaults to an empty description.
* If not set, defaults to an empty description.
*/
description?: pulumi.Input<string>;
/**
* User defined name of this policy tag. It must: be unique within the parent
* taxonomy; contain only unicode letters, numbers, underscores, dashes and spaces;
* not start or end with spaces; and be at most 200 bytes long when encoded in UTF-8.
*/
displayName?: pulumi.Input<string>;
/**
* Resource name of this policy tag, whose format is:
* "projects/{project}/locations/{region}/taxonomies/{taxonomy}/policyTags/{policytag}"
*/
name?: pulumi.Input<string>;
/**
* Resource name of this policy tag's parent policy tag.
* If empty, it means this policy tag is a top level policy tag.
* If not set, defaults to an empty string.
*/
parentPolicyTag?: pulumi.Input<string>;
/**
* Taxonomy the policy tag is associated with
*/
taxonomy?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a PolicyTag resource.
*/
export interface PolicyTagArgs {
/**
* Description of this policy tag. It must: contain only unicode characters, tabs,
* newlines, carriage returns and page breaks; and be at most 2000 bytes long when
* encoded in UTF-8. If not set, defaults to an empty description.
* If not set, defaults to an empty description.
*/
description?: pulumi.Input<string>;
/**
* User defined name of this policy tag. It must: be unique within the parent
* taxonomy; contain only unicode letters, numbers, underscores, dashes and spaces;
* not start or end with spaces; and be at most 200 bytes long when encoded in UTF-8.
*/
displayName: pulumi.Input<string>;
/**
* Resource name of this policy tag's parent policy tag.
* If empty, it means this policy tag is a top level policy tag.
* If not set, defaults to an empty string.
*/
parentPolicyTag?: pulumi.Input<string>;
/**
* Taxonomy the policy tag is associated with
*/
taxonomy: pulumi.Input<string>;
} | the_stack |
import {Component, DebugElement, Input} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {AbstractControl, FormControl, FormGroup} from '@angular/forms';
import {By} from '@angular/platform-browser';
import {FormatterParserDirective} from '../formatter-parser.directive';
import {FormatterParserCollectorService} from '../formatter-parser.service';
import {FormatterParserModule} from '../index';
import {IFormatterParserConfig} from '../struct/formatter-parser-config';
@Component({
selector: 'content-component',
template: `
<p>
This is the component that displays formatter parser in the over
ng-content
</p>
<ng-content></ng-content>
`,
})
class NgContentComponent {
}
@Component({
selector: 'wrap-component',
template: `
<p>
This is the component that displays formatter parser in the over
ng-content
</p>
<input type="text" value="" [formControlName]="name" id="wrapped">
`,
})
class WrapContentComponent {
@Input()
name: string;
}
@Component({
template: `
<form [formGroup]="fg">
<input type="text" value="" [formControlName]="'both'" id="both"
[formatterParser]="formatterParserConfigBasic">
<input type="text" value="" [formControlName]="'format'" id="format"
[formatterParser]="formatterParserConfigFormat">
<input type="text" value="" [formControlName]="'parse'" id="parse"
[formatterParser]="formatterParserConfigParse">
<input type="text" value="" [formControlName]="'params'" id="params"
[formatterParser]="formatterParserConfigParams">
<input type="text" value="" [formControlName]="'empty'" id="empty"
[formatterParser]>
<content-component>
<input type="text" value="" id="content" [formControlName]="'content'"
[formatterParser]="formatterParserConfigContent">
</content-component>
<!--
<wrap-component [name]="'wrapped'"></wrap-component>
-->
</form>
`,
})
class TestComponent {
fg: FormGroup = new FormGroup({
'both': new FormControl(''),
'format': new FormControl(''),
'parse': new FormControl(''),
'params': new FormControl(''),
'empty': new FormControl(''),
'content': new FormControl(''),
'wrapped': new FormControl('')
});
formatterParserConfigBasic: IFormatterParserConfig = {
formatterParser: [
{name: 'toUpperCase'}
]
};
formatterParserConfigFormat: IFormatterParserConfig = {
formatterParser: [
{name: 'toUpperCase', target: 1}
]
};
formatterParserConfigParse: IFormatterParserConfig = {
formatterParser: [
{name: 'toUpperCase', target: 0}
]
};
formatterParserConfigParams: IFormatterParserConfig = {
formatterParser: [
{name: 'replaceString', params: [/[a]/g, 'b']}
]
};
formatterParserConfigWrapped: IFormatterParserConfig = {
formatterParser: [
{name: 'toUpperCase'}
]
};
formatterParserConfigContent: IFormatterParserConfig = {
formatterParser: [
{name: 'toUpperCase'}
]
}
}
describe('FormatterParserDirective', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let el: DebugElement;
let bothInput: DebugElement;
let bothInputControl: AbstractControl;
let formatInput: DebugElement;
let formatInputControl: AbstractControl;
let parseInput: DebugElement;
let parseInputControl: AbstractControl;
let paramsInput: DebugElement;
let paramsInputControl: AbstractControl;
let emptyInput: DebugElement;
let emptyInputControl: AbstractControl;
let contentInput: DebugElement;
let contentInputControl: AbstractControl;
let wrappedInput: DebugElement;
let wrappedInputControl: AbstractControl;
function setInputValue(inputElem: DebugElement, value) {
inputElem.nativeElement.value = value;
inputElem.triggerEventHandler('input', {target: {value: value}});
fixture.detectChanges()
}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
FormatterParserModule.forRoot()
],
declarations: [
NgContentComponent,
WrapContentComponent,
TestComponent
],
providers: [
FormatterParserCollectorService
]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
el = fixture.debugElement;
bothInput = el.query(By.css('#both'));
bothInputControl = component.fg.get('both');
formatInput = el.query(By.css('#format'));
formatInputControl = component.fg.get('format');
parseInput = el.query(By.css('#parse'));
parseInputControl = component.fg.get('parse');
paramsInput = el.query(By.css('#params'));
paramsInputControl = component.fg.get('params');
emptyInput = el.query(By.css('#empty'));
emptyInputControl = component.fg.get('empty');
contentInput = el.query(By.css('#content'));
contentInputControl = component.fg.get('content');
wrappedInput = el.query(By.css('#wrapped'));
wrappedInputControl = component.fg.get('wrapped')
});
it('should format model value to view value with built in transform function', () => {
fixture.detectChanges();
expect(formatInputControl.value).toBe('');
formatInputControl.setValue('ABCdef');
expect(formatInputControl.value).toBe('ABCDEF')
});
it('should parse view value to model value with built in transform function', () => {
fixture.detectChanges();
setInputValue(parseInput, 'ABCdef');
expect(parseInput.nativeElement.value).toBe('ABCDEF')
});
it('should transform model and view value with built in transform function', () => {
const inputValue = 'ABCdef';
const resultValue = 'ABCDEF';
fixture.detectChanges();
// set model value
setInputValue(bothInput, inputValue);
expect(bothInput.nativeElement.value).toBe(resultValue);
expect(bothInputControl.value).toBe(resultValue);
// reset
setInputValue(bothInput, '');
fixture.detectChanges();
expect(bothInput.nativeElement.value).toBe('');
expect(bothInputControl.value).toBe(null);
// set view value
setInputValue(bothInput, inputValue);
expect(bothInput.nativeElement.value).toBe(resultValue);
expect(bothInputControl.value).toBe(resultValue)
});
it('should transform value with built in transform function and params', () => {
fixture.detectChanges();
const inputValue = 'abc';
const resultValue = 'bbc';
fixture.detectChanges();
// set model value
setInputValue(paramsInput, inputValue);
expect(paramsInput.nativeElement.value).toBe(resultValue);
expect(paramsInputControl.value).toBe(resultValue);
// reset
setInputValue(paramsInput, '');
fixture.detectChanges();
expect(paramsInput.nativeElement.value).toBe('');
expect(paramsInputControl.value).toBe(null);
// set view value
setInputValue(paramsInput, inputValue);
expect(paramsInput.nativeElement.value).toBe(resultValue);
expect(paramsInputControl.value).toBe(resultValue)
});
it('should pass value with empty config', () => {
fixture.detectChanges();
const inputValue = 'abc';
const resultValue = 'abc';
fixture.detectChanges();
// set model value
setInputValue(emptyInput, inputValue);
expect(emptyInput.nativeElement.value).toBe(resultValue);
expect(emptyInputControl.value).toBe(resultValue);
// reset
setInputValue(emptyInput, '');
fixture.detectChanges();
expect(emptyInput.nativeElement.value).toBe('');
expect(emptyInputControl.value).toBe(null);
// set view value
setInputValue(emptyInput, inputValue);
expect(emptyInput.nativeElement.value).toBe(resultValue);
expect(emptyInputControl.value).toBe(resultValue)
});
it('should transform model and view value with built in transform function in content section', () => {
const inputValue = 'ABCdef';
const resultValue = 'ABCDEF';
fixture.detectChanges();
// set model value
setInputValue(contentInput, inputValue);
expect(contentInput.nativeElement.value).toBe(resultValue);
expect(contentInputControl.value).toBe(resultValue);
// reset
setInputValue(contentInput, '');
fixture.detectChanges();
expect(contentInput.nativeElement.value).toBe('');
expect(contentInputControl.value).toBe(null);
// set view value
setInputValue(contentInput, inputValue);
expect(contentInput.nativeElement.value).toBe(resultValue);
expect(contentInputControl.value).toBe(resultValue)
});
xit('should transform model and view value with built in transform function on wrapped inputs', () => {
const inputValue = 'ABCdef';
const resultValue = 'ABCDEF';
fixture.detectChanges();
// set model value
setInputValue(wrappedInput, inputValue);
expect(wrappedInput.nativeElement.value).toBe(resultValue);
expect(wrappedInputControl.value).toBe(resultValue);
// reset
setInputValue(wrappedInput, '');
fixture.detectChanges();
expect(wrappedInput.nativeElement.value).toBe('');
expect(wrappedInputControl.value).toBe(null);
// set view value
setInputValue(wrappedInput, inputValue);
expect(wrappedInput.nativeElement.value).toBe(resultValue);
expect(wrappedInputControl.value).toBe(resultValue)
})
});
@Component({
template: `
<div [formatterParser]="false"></div>`
})
class ErrorTestComponent {
}
describe('FormatterParserDirective Errors', () => {
let fixture: ComponentFixture<ErrorTestComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
FormatterParserModule.forRoot()
],
declarations: [
ErrorTestComponent
],
providers: [
FormatterParserCollectorService
]
})
});
it('should throw if not input is present', () => {
const emptyConfigMessage = 'You can applied the "formatterParser" directive only on inputs or elements containing inputs';
expect(() => {
fixture = TestBed.createComponent(ErrorTestComponent);
fixture.detectChanges()
}).toThrowError(emptyConfigMessage)
})
}); | the_stack |
import {
Collab,
ICollabParent,
InitToken,
MessageMeta,
Pre,
Message,
int64AsNumber,
Optional,
BatchingLayer,
} from "@collabs/core";
import { CRDTMetaLayerSave } from "../../../generated/proto_compiled";
import { CRDTMeta, CRDTMetaRequestee } from "../crdt_meta";
import { CausalMessageBuffer } from "./causal_message_buffer";
import { SendCRDTMetaBatch, ReceiveCRDTMetaBatch } from "./crdt_meta_batches";
import { ReceiveCRDTMeta, SendCRDTMeta } from "./crdt_meta_implementations";
import { ReceiveTransaction } from "./receive_transaction";
/**
* Collab that provides [[CRDTMeta]] to its
* descendants.
*
* The added [[CRDTMeta]] is stored in [[MessageMeta]]'s
* index signature
* keyed by [[CRDTMeta.MESSAGE_META_KEY]].
*
* All messages in the same transaction are assigned
* the same [[CRDTMeta]], where transactions are delimited
* (ended) by either:
* - Serializing the most recent [[SerializableMessage]]
* sent by this class.
* E.g., when using this class inside [[BatchingLayer]]
* like in [[CRDTRuntime]], this occurs when
* [[BatchingLayer.commitBatch]] is called. (Note that the same [[SerializableMessage]]
* is reused until it is serialized.
* E.g., when using this class inside [[BatchingLayer]]
* like in [[CRDTRuntime]], this occurs when
* [[BatchingLayer.commitBatch]] is called.)
* - Receiving a message from another replica.
*
* When the `causalityGuaranteed` constructor option
* is false (the default), it is assumed that no ancestor [[Collab]]s
* provide extra metadata fields. These fields will be
* forgotten during saving, if there are queued
* not-yet-causally-ready messages.
* (Exception: BatchingLayer.BATCH_SIZE_KEY, which we extract and don't need
* after loading.)
*/
export class CRDTMetaLayer extends Collab implements ICollabParent {
private child!: Collab;
/**
* Includes this.runtime.replicaID.
*/
private readonly currentVC = new Map<string, number>();
/**
* The current Lamport meta, i.e., the max meta
* sent or received so far.
* Note the next message's senderCounter will be one greater.
* @param newInitToken("",this [description]
* @return [description]
*/
private currentLamportTimestamp = 0;
/**
* Whether we have started, but not yet ended, a send
* transaction.
*/
private isInTransaction = false;
readonly causalityGuaranteed: boolean;
/**
* null iff causalityGuaranteed.
*/
private readonly messageBuffer: CausalMessageBuffer | null;
/**
* `causalityGuaranteed` option: Optimization flag.
* If you can guarantee that messages will always be
* delivered in causal order (i.e., after all of their
* causal predecessors), then you may set this to true.
* Then this class will not bother attaching the
* vector clock entries needed to ensure causal order
* delivery.
* - Important: if any replica (not necessarily
* the local one), on any network, is not guaranteed
* causality, then this flag must be false.
* - When true, redundant re-deliveries are still okay -
* they will be filtered out as usual.
*/
constructor(
initToken: InitToken,
options?: { causalityGuaranteed?: boolean }
) {
super(initToken);
this.causalityGuaranteed = options?.causalityGuaranteed ?? false;
this.currentVC.set(this.runtime.replicaID, 0);
if (!this.causalityGuaranteed) {
this.messageBuffer = new CausalMessageBuffer(
this.runtime.replicaID,
this.currentVC,
this.deliverRemoteTransaction.bind(this)
);
} else {
this.messageBuffer = null;
}
}
setChild<C extends Collab>(preChild: Pre<C>): C {
const child = preChild(new InitToken("", this));
this.child = child;
return child;
}
getAddedContext(key: symbol): unknown {
if (key === CRDTMetaRequestee.CONTEXT_KEY) {
return this.currentSendMeta();
}
if (key === MessageMeta.NEXT_MESSAGE_META) {
const meta = <MessageMeta>(
this.getContext(MessageMeta.NEXT_MESSAGE_META)
) ?? { sender: this.runtime.replicaID, isLocalEcho: true };
meta[CRDTMeta.MESSAGE_META_KEY] = this.currentSendMeta();
return meta;
}
return undefined;
}
/**
* Cache for currentSendMeta().
*/
private _currentSendMeta: SendCRDTMeta | null = null;
/**
* The CRDTMeta for the current (or upcoming, if not
* interrupted by a received message)
* transaction.
*/
private currentSendMeta(): SendCRDTMeta {
if (this._currentSendMeta === null) {
this._currentSendMeta = new SendCRDTMeta(
this.runtime.replicaID,
this.currentVC.get(this.runtime.replicaID)! + 1,
this.currentVC,
Date.now(),
this.currentLamportTimestamp + 1,
this.messageBuffer?.getCausallyMaximalVCKeys() ?? new Set()
);
}
return this._currentSendMeta;
}
/**
* Cache for currentSendBatch().
*/
private _currentSendBatch: SendCRDTMetaBatch | null = null;
/**
* The SendCRDTMetaBatch for the current batch.
*/
private currentSendBatch(): SendCRDTMetaBatch {
if (this._currentSendBatch === null) {
this._currentSendBatch = new SendCRDTMetaBatch(this.onBatchSerialize);
}
return this._currentSendBatch;
}
/**
* Callback for _currentSendBatch's onSerialize.
*
* Defined as a var so we don't have to bind it as the
* CRDTMetaBatch callback.
*/
private onBatchSerialize = () => {
// End the current transaction, if any.
// Note this may modify the batch (pushing current
// transaction's meta onto batch.metas).
this.endTransaction();
// Make room for the next batch.
this._currentSendBatch = null;
};
/**
* Ends the current transaction, if any.
*
* This must be called once per transaction at the end,
* before processing any other messages (delivering or
* updating our metadata).
*
* It may also be called outside of any transaction
* (doing nothing).
*
* Specifically, it is called:
* - Just before processing a message from another user,
* in case there is a current transaction (which gets ended
* by the received message).
* - in onBatchSerialize, since that
* indicates the end of the batch, hence current transaction
* (if any - it might have already been ended by a processed
* message).
*/
private endTransaction() {
if (this.isInTransaction) {
this.isInTransaction = false;
// Disallow further requests.
this._currentSendMeta!.freeze();
// Add the currentSendMeta to the batch.
this.currentSendBatch().metas.push(this._currentSendMeta!);
// Make room for the next transaction to have a different
// CRDTMeta.
this._currentSendMeta = null;
// Update "current" metadata to account for the end of
// our current message.
this.currentVC.set(
this.runtime.replicaID,
this.currentVC.get(this.runtime.replicaID)! + 1
);
this.currentLamportTimestamp++;
}
}
childSend(child: Collab, messagePath: Message[]): void {
if (child !== this.child) {
throw new Error(`childSend called by non-child: ${child}`);
}
this.isInTransaction = true;
this.currentSendMeta().count++;
messagePath.push(this.currentSendBatch());
this.send(messagePath);
}
/**
* The CRDTMetaReceiveMessage for the batch of messages
* currently being received.
*
* null if we are not in the middle of receiving a batch.
* Also, not used for local echos.
*/
private currentReceiveBatch: ReceiveCRDTMetaBatch | null = null;
receive(messagePath: Message[], meta: MessageMeta): void {
if (messagePath.length === 0) {
throw new Error("messagePath.length === 0");
}
if (meta.isLocalEcho) {
// Due to immediate local echos, we can assume that this
// message corresponds to the current transaction.
const crdtMeta = this.currentSendMeta();
// Remove our message.
messagePath.length--;
// Deliver immediately. No need to check the
// buffer since our local echo cannot make any
// previously received messages causally ready.
if (!this.causalityGuaranteed) {
this.messageBuffer!.processOwnDelivery();
}
this.deliverMessage(messagePath, meta, crdtMeta);
// Reset isAutomatic, since we're done receiving.
// (Otherwise future messages in the transaction will
// inherit isAutomatic.)
crdtMeta.isAutomatic = false;
} else {
if (meta.sender === this.runtime.replicaID) {
// We got redelivered our own message not as a
// local echo. Redundant; do nothing.
// (In fact the calls to isAlreadyDelivered below
// should be sufficient to check for this.)
return;
}
if (this.currentReceiveBatch === null) {
// It's a new batch with a new CRDTMetaReceiveMessage.
this.currentReceiveBatch = new ReceiveCRDTMetaBatch(
meta.sender,
<number | undefined>meta[BatchingLayer.BATCH_SIZE_KEY] ?? 1,
<Uint8Array>messagePath[messagePath.length - 1]
);
}
// Remove our message.
messagePath.length--;
// Since the message is not a local echo, we can
// assume messagePath is all (Uint8Array | string).
// Also, here we are implicitly using the assumption
// that meta is just `{ sender, isLocalEcho }`,
// by forgetting it.
if (
this.currentReceiveBatch.received(<(Uint8Array | string)[]>messagePath)
) {
// Deliver/buffer the current transaction.
const transaction = this.currentReceiveBatch.completeTransaction();
if (this.causalityGuaranteed) {
// We're assured that the transaction is causally
// ready; we just need to ensure that it has
// not already been delivered.
// (That includes the case of getting delivered
// our own message as not a local echo).
if (!this.isAlreadyDelivered(transaction.crdtMeta)) {
this.deliverRemoteTransaction(transaction);
}
} else {
// Buffer the message and attempt to deliver it or
// other messages.
this.messageBuffer!.pushRemoteTransaction(transaction);
this.messageBuffer!.check();
}
if (this.currentReceiveBatch.isFinished()) {
// Done with the batch; make room for the next one.
this.currentReceiveBatch = null;
}
}
}
}
/**
* @return whether a message with the given sender and
* senderCounter
* has already been delivered.
*/
private isAlreadyDelivered(crdtMeta: ReceiveCRDTMeta): boolean {
const senderEntry = this.currentVC.get(crdtMeta.sender);
if (senderEntry !== undefined) {
if (senderEntry >= crdtMeta.senderCounter) return true;
}
return false;
}
/**
* Called for non-local messages only.
* @param transaction [description]
* @return [description]
*/
private deliverRemoteTransaction(transaction: ReceiveTransaction) {
// End our current transaction, if any.
// Note this immediately updates our own VC entry and
// Lamport timestamp.
this.endTransaction();
// Update our own state to reflect the received crdtMeta.
this.currentVC.set(
transaction.crdtMeta.sender,
transaction.crdtMeta.senderCounter
);
if (transaction.crdtMeta.lamportTimestamp !== null) {
// TODO: note that this is a restricted kind of
// Lamport timestamp: only updates when you use it.
// I think that should still give the causality
// guarantees for actual uses, but need to check.
this.currentLamportTimestamp = Math.max(
transaction.crdtMeta.lamportTimestamp,
this.currentLamportTimestamp
);
}
// Deliver messages.
for (const message of transaction.messages) {
this.deliverMessage(
message,
{ sender: transaction.crdtMeta.sender, isLocalEcho: false },
transaction.crdtMeta
);
}
}
private deliverMessage(
messagePath: Message[],
meta: MessageMeta,
crdtMeta: CRDTMeta
) {
// Add the CRDTMeta to meta.
meta[CRDTMeta.MESSAGE_META_KEY] = crdtMeta;
try {
this.child.receive(messagePath, meta);
} catch (err) {
if (meta.isLocalEcho) {
// Propagate the error back to the original
// operation.
throw err;
} else {
// Don't let the error block other messages'
// delivery or affect the deliverer, but still make it print
// its error like it was unhandled.
void Promise.resolve().then(() => {
throw err;
});
}
}
}
save(): Uint8Array {
if (this.isInTransaction) {
throw new Error(
"Cannot call save during a send transaction; commit the pending batch first"
);
}
if (this.currentReceiveBatch !== null) {
throw new Error(
"Cannot call save during a received transaction; let the current received batch be processed first"
);
}
const vectorClock = Object.fromEntries(this.currentVC);
const saveMessage = CRDTMetaLayerSave.create({
vectorClock,
lamportTimestamp: this.currentLamportTimestamp,
childSave: this.child.save(),
messageBufferSave: this.messageBuffer?.save(),
});
return CRDTMetaLayerSave.encode(saveMessage).finish();
}
load(saveData: Optional<Uint8Array>): void {
if (!saveData.isPresent) {
// Indicates skipped loading. Pass on the message.
this.child.load(saveData);
} else {
const saveMessage = CRDTMetaLayerSave.decode(saveData.get());
for (const [replicaID, entry] of Object.entries(
saveMessage.vectorClock
)) {
this.currentVC.set(replicaID, int64AsNumber(entry));
}
this.currentLamportTimestamp = int64AsNumber(
saveMessage.lamportTimestamp
);
this.child.load(Optional.of(saveMessage.childSave));
if (this.messageBuffer !== null) {
this.messageBuffer.load(saveMessage.messageBufferSave);
}
}
}
getDescendant(namePath: string[]): Collab | undefined {
if (namePath.length === 0) return this;
if (namePath[namePath.length - 1] !== "") {
throw new Error("Unrecognized child: " + namePath[namePath.length - 1]);
}
namePath.length--;
return this.child.getDescendant(namePath);
}
canGC(): boolean {
// Vector clock state is never trivial after the
// first message. Approximate as never trivial.
return false;
}
} | the_stack |
import { BaseResource } from 'ms-rest-azure';
import { CloudError } from 'ms-rest-azure';
import * as moment from 'moment';
export { BaseResource } from 'ms-rest-azure';
export { CloudError } from 'ms-rest-azure';
/**
* @class
* Initializes a new instance of the OperationDisplay class.
* @constructor
* Display metadata associated with the operation.
*
* @member {string} [provider] Service provider: Microsoft
* OperationsManagement.
* @member {string} [resource] Resource on which the operation is performed
* etc.
* @member {string} [operation] Type of operation: get, read, delete, etc.
*/
export interface OperationDisplay {
provider?: string;
resource?: string;
operation?: string;
}
/**
* @class
* Initializes a new instance of the Operation class.
* @constructor
* Supported operation of OperationalInsights resource provider.
*
* @member {string} [name] Operation name: {provider}/{resource}/{operation}
* @member {object} [display] Display metadata associated with the operation.
* @member {string} [display.provider] Service provider: Microsoft
* OperationsManagement.
* @member {string} [display.resource] Resource on which the operation is
* performed etc.
* @member {string} [display.operation] Type of operation: get, read, delete,
* etc.
*/
export interface Operation {
name?: string;
display?: OperationDisplay;
}
/**
* @class
* Initializes a new instance of the LinkedService class.
* @constructor
* The top level Linked service resource container.
*
* @member {string} resourceId The resource id of the resource that will be
* linked to the workspace.
*/
export interface LinkedService extends BaseResource {
resourceId: string;
}
/**
* @class
* Initializes a new instance of the DataSource class.
* @constructor
* Datasources under OMS Workspace.
*
* @member {object} properties The data source properties in raw json format,
* each kind of data source have it's own schema.
* @member {string} [eTag] The ETag of the data source.
* @member {string} kind Possible values include: 'AzureActivityLog',
* 'ChangeTrackingPath', 'ChangeTrackingDefaultPath',
* 'ChangeTrackingDefaultRegistry', 'ChangeTrackingCustomRegistry',
* 'CustomLog', 'CustomLogCollection', 'GenericDataSource', 'IISLogs',
* 'LinuxPerformanceObject', 'LinuxPerformanceCollection', 'LinuxSyslog',
* 'LinuxSyslogCollection', 'WindowsEvent', 'WindowsPerformanceCounter'
*/
export interface DataSource extends BaseResource {
properties: any;
eTag?: string;
kind: string;
}
/**
* @class
* Initializes a new instance of the DataSourceFilter class.
* @constructor
* DataSource filter. Right now, only filter by kind is supported.
*
* @member {string} [kind] Possible values include: 'AzureActivityLog',
* 'ChangeTrackingPath', 'ChangeTrackingDefaultPath',
* 'ChangeTrackingDefaultRegistry', 'ChangeTrackingCustomRegistry',
* 'CustomLog', 'CustomLogCollection', 'GenericDataSource', 'IISLogs',
* 'LinuxPerformanceObject', 'LinuxPerformanceCollection', 'LinuxSyslog',
* 'LinuxSyslogCollection', 'WindowsEvent', 'WindowsPerformanceCounter'
*/
export interface DataSourceFilter {
kind?: string;
}
/**
* @class
* Initializes a new instance of the IntelligencePack class.
* @constructor
* Intelligence Pack containing a string name and boolean indicating if it's
* enabled.
*
* @member {string} [name] The name of the intelligence pack.
* @member {boolean} [enabled] The enabled boolean for the intelligence pack.
* @member {string} [displayName] The display name of the intelligence pack.
*/
export interface IntelligencePack {
name?: string;
enabled?: boolean;
displayName?: string;
}
/**
* @class
* Initializes a new instance of the SharedKeys class.
* @constructor
* The shared keys for a workspace.
*
* @member {string} [primarySharedKey] The primary shared key of a workspace.
* @member {string} [secondarySharedKey] The secondary shared key of a
* workspace.
*/
export interface SharedKeys {
primarySharedKey?: string;
secondarySharedKey?: string;
}
/**
* @class
* Initializes a new instance of the MetricName class.
* @constructor
* The name of a metric.
*
* @member {string} [value] The system name of the metric.
* @member {string} [localizedValue] The localized name of the metric.
*/
export interface MetricName {
value?: string;
localizedValue?: string;
}
/**
* @class
* Initializes a new instance of the UsageMetric class.
* @constructor
* A metric describing the usage of a resource.
*
* @member {object} [name] The name of the metric.
* @member {string} [name.value] The system name of the metric.
* @member {string} [name.localizedValue] The localized name of the metric.
* @member {string} [unit] The units used for the metric.
* @member {number} [currentValue] The current value of the metric.
* @member {number} [limit] The quota limit for the metric.
* @member {date} [nextResetTime] The time that the metric's value will reset.
* @member {string} [quotaPeriod] The quota period that determines the length
* of time between value resets.
*/
export interface UsageMetric {
name?: MetricName;
unit?: string;
currentValue?: number;
limit?: number;
nextResetTime?: Date;
quotaPeriod?: string;
}
/**
* @class
* Initializes a new instance of the ManagementGroup class.
* @constructor
* A management group that is connected to a workspace
*
* @member {number} [serverCount] The number of servers connected to the
* management group.
* @member {boolean} [isGateway] Gets or sets a value indicating whether the
* management group is a gateway.
* @member {string} [name] The name of the management group.
* @member {string} [id] The unique ID of the management group.
* @member {date} [created] The datetime that the management group was created.
* @member {date} [dataReceived] The last datetime that the management group
* received data.
* @member {string} [version] The version of System Center that is managing the
* management group.
* @member {string} [sku] The SKU of System Center that is managing the
* management group.
*/
export interface ManagementGroup {
serverCount?: number;
isGateway?: boolean;
name?: string;
id?: string;
created?: Date;
dataReceived?: Date;
version?: string;
sku?: string;
}
/**
* @class
* Initializes a new instance of the Sku class.
* @constructor
* The SKU (tier) of a workspace.
*
* @member {string} name The name of the SKU. Possible values include: 'Free',
* 'Standard', 'Premium', 'Unlimited', 'PerNode', 'PerGB2018', 'Standalone'
*/
export interface Sku {
name: string;
}
/**
* @class
* Initializes a new instance of the Workspace class.
* @constructor
* The top level Workspace resource container.
*
* @member {string} [provisioningState] The provisioning state of the
* workspace. Possible values include: 'Creating', 'Succeeded', 'Failed',
* 'Canceled', 'Deleting', 'ProvisioningAccount'
* @member {string} [source] The source of the workspace. Source defines where
* the workspace was created. 'Azure' implies it was created in Azure.
* 'External' implies it was created via the Operational Insights Portal. This
* value is set on the service side and read-only on the client side.
* @member {string} [customerId] The ID associated with the workspace. Setting
* this value at creation time allows the workspace being created to be linked
* to an existing workspace.
* @member {string} [portalUrl] The URL of the Operational Insights portal for
* this workspace. This value is set on the service side and read-only on the
* client side.
* @member {object} [sku] The SKU of the workspace.
* @member {string} [sku.name] The name of the SKU. Possible values include:
* 'Free', 'Standard', 'Premium', 'Unlimited', 'PerNode', 'PerGB2018',
* 'Standalone'
* @member {number} [retentionInDays] The workspace data retention in days. -1
* means Unlimited retention for the Unlimited Sku. 730 days is the maximum
* allowed for all other Skus.
* @member {string} [eTag] The ETag of the workspace.
*/
export interface Workspace extends BaseResource {
provisioningState?: string;
source?: string;
customerId?: string;
portalUrl?: string;
sku?: Sku;
retentionInDays?: number;
eTag?: string;
}
/**
* @class
* Initializes a new instance of the Resource class.
* @constructor
* The resource definition.
*
* @member {string} [id] Resource Id
* @member {string} [name] Resource name
* @member {string} [type] Resource type
* @member {string} [location] Resource location
* @member {object} [tags] Resource tags
*/
export interface Resource extends BaseResource {
readonly id?: string;
readonly name?: string;
readonly type?: string;
location?: string;
tags?: { [propertyName: string]: string };
}
/**
* @class
* Initializes a new instance of the ProxyResource class.
* @constructor
* Common properties of proxy resource.
*
* @member {string} [id] Resource ID.
* @member {string} [name] Resource name.
* @member {string} [type] Resource type.
* @member {object} [tags] Resource tags
*/
export interface ProxyResource {
readonly id?: string;
readonly name?: string;
readonly type?: string;
tags?: { [propertyName: string]: string };
}
/**
* @class
* Initializes a new instance of the LinkedServiceListResult class.
* @constructor
* The list linked service operation response.
*
*/
export interface LinkedServiceListResult extends Array<LinkedService> {
}
/**
* @class
* Initializes a new instance of the DataSourceListResult class.
* @constructor
* The list data source by workspace operation response.
*
* @member {string} [nextLink] The link (url) to the next page of datasources.
*/
export interface DataSourceListResult extends Array<DataSource> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the WorkspaceListUsagesResult class.
* @constructor
* The list workspace usages operation response.
*
*/
export interface WorkspaceListUsagesResult extends Array<UsageMetric> {
}
/**
* @class
* Initializes a new instance of the WorkspaceListManagementGroupsResult class.
* @constructor
* The list workspace managmement groups operation response.
*
*/
export interface WorkspaceListManagementGroupsResult extends Array<ManagementGroup> {
}
/**
* @class
* Initializes a new instance of the WorkspaceListResult class.
* @constructor
* The list workspaces operation response.
*
*/
export interface WorkspaceListResult extends Array<Workspace> {
}
/**
* @class
* Initializes a new instance of the OperationListResult class.
* @constructor
* Result of the request to list solution operations.
*
* @member {string} [nextLink] URL to get the next set of operation list
* results if there are any.
*/
export interface OperationListResult extends Array<Operation> {
readonly nextLink?: string;
} | the_stack |
import { Controller, Post, Body, Get, Param, ParseUUIDPipe, Put, Delete, HttpCode, HttpStatus, UseGuards, Request, UseInterceptors, Res } from '@nestjs/common';
// import { AccountsService } from './accounts.service';
import { ApiCreatedResponse, ApiBadRequestResponse, ApiUseTags, ApiOkResponse, ApiNotFoundResponse, ApiConflictResponse, ApiUnauthorizedResponse, ApiForbiddenResponse } from '@nestjs/swagger';
import { CreateAccountDto } from './dto/create-account.dto';
import { RolesGuard } from '../auth/guards/roles.guard';
import { VerifyUuidDto } from './dto/verify-uuid.dto';
import { RefreshAccessTokenDto } from './dto/refresh-access-token.dto';
import { CreateForgotPasswordDto } from './dto/create-forgot-password.dto';
import { ResetPasswordDto } from './dto/reset-password.dto';
import { Roles } from '../auth/decorators/roles.decorator';
import { Request as ExpressRequest } from 'express';
import { AccountsErrorInterceptor } from './common/accounts-error.interceptor';
import { InetLocationDto } from './dto/inet-location.dto';
import { LoginGuard } from '../auth/guards/login.guard';
import { Response } from 'express';
import { InjectConnection } from '@nestjs/typeorm';
import { Connection } from 'typeorm';
import { GetByIdAccountFacade } from './api.get-by-id/get-by-id.accounts.facade';
import { GetByEmailAccountFacade } from './api.get-by-email/get-by-email.accounts.facade';
import { UpdateAccountDto } from './dto/update-account.dto';
import { PutAccountFacade } from './api.put/put.accounts.facade';
import { DeleteAccountFacade } from './api.delete/delete.accounts.facade';
import { CreateAccountFacade } from './api.create/create.accounts.facade';
import { VerifyEmailAccountFacade } from './api.verify-email/verify-email.accounts.facade';
import { LoginAccountFacade } from './api.login/login.accounts.facade';
import { LoggedInUser } from '@btcp/bootcamp-entities';
import { RefreshAccessTokenAccountFacade } from './api.refresh-access-token/refresh.access.token.accounts.facade';
import { ForgotPasswordAccountFacade } from './api.forgot-pasword/forgot-password.accounts.facade';
import { ForgotPasswordVerifyAccountFacade } from './api.forgot-password-verify/forgot-password-verify.accounts.facade';
import { ResetPasswordAccountFacade } from './api.reset-password/reset-password.accounts.facade';
import { GetAllAccountFacade } from './api.get-all/get-all.accounts.facade';
import { GetAllAccountFactory } from './api.get-all/get-all.accounts.factory';
import { GetByEmailAccountFactory } from './api.get-by-email/get-by-email.accounts.factory';
import { GetByIdAccountFactory } from './api.get-by-id/get-by-id.accounts.factory';
import { PutAccountFactory } from './api.put/put.accounts.factory';
import { DeleteAccountFactory } from './api.delete/delete.accounts.factory';
import { CreateAccountFactory } from './api.create/create.accounts.factory';
import { VerifyEmailAccountFactory } from './api.verify-email/verify-email.accounts.factory';
import { LoginAccountFactory } from './api.login/login.accounts.factory';
import { RefreshAccessTokenAccountFactory } from './api.refresh-access-token/refresh.access.token.accounts.factory';
import { ForgotPasswordAccountFactory } from './api.forgot-pasword/forgot-password.accounts.factory';
import { ForgotPasswordVerifyAccountFactory } from './api.forgot-password-verify/forgot-password-verify.accounts.factory';
import { ResetPasswordAccountFactory } from './api.reset-password/reset-password.accounts.factory';
@Controller('accounts')
@ApiUseTags('Accounts')
export class AccountsController {
constructor(@InjectConnection() private readonly connection: Connection) {}
@Get()
@UseGuards(RolesGuard)
@Roles('admin')
@HttpCode(HttpStatus.OK)
@ApiOkResponse({description: 'Data recieved'})
@ApiUnauthorizedResponse({ description: 'Not authorized.'})
@ApiForbiddenResponse({description: 'User has not permitted to this api.'})
public async getAllAccounts(@Res() res: Response) {
await new GetAllAccountFacade(new GetAllAccountFactory(this.connection, res)).exec();
}
@Get('email/:email')
public async findOneByEmail(
@Res() res: Response,
@Param('email') email: string
) {
const controller = new GetByEmailAccountFactory(this.connection, res);
await new GetByEmailAccountFacade(controller).exec(email);
}
@Get(':id')
public async findOneById(
@Res() res: Response,
@Param('id', new ParseUUIDPipe()) id: string) {
await new GetByIdAccountFacade(new GetByIdAccountFactory(this.connection, res)).exec(id);
}
@Put(':id')
public async update(
@Res() res: Response,
@Param('id', new ParseUUIDPipe()) id: string,
@Body() updateAccountDto: UpdateAccountDto) {
updateAccountDto.id = id;
await new PutAccountFacade(new PutAccountFactory(this.connection, res)).exec(updateAccountDto);
}
@Delete(':id')
@UseGuards(RolesGuard)
@Roles('admin')
@UseInterceptors(AccountsErrorInterceptor)
@HttpCode(HttpStatus.OK)
@ApiOkResponse({description: 'The record has been successfully deleted.'})
@ApiBadRequestResponse({description: 'account does not exist.'})
@ApiUnauthorizedResponse({ description: 'Not authorized.'})
@ApiForbiddenResponse({description: 'User has not permitted to this api.'})
public async delete(
@Res() res: Response,
@Param('id') id: string) {
await new DeleteAccountFacade(new DeleteAccountFactory(this.connection, res)).exec(id);
}
// ╔═╗╦ ╦╔╦╗╦ ╦╔═╗╔╗╔╔╦╗╦╔═╗╔═╗╔╦╗╔═╗
// ╠═╣║ ║ ║ ╠═╣║╣ ║║║ ║ ║║ ╠═╣ ║ ║╣
// ╩ ╩╚═╝ ╩ ╩ ╩╚═╝╝╚╝ ╩ ╩╚═╝╩ ╩ ╩ ╚═╝
@Post()
@UseInterceptors(AccountsErrorInterceptor)
@HttpCode(HttpStatus.CREATED)
@ApiCreatedResponse({description: 'The record has been successfully created.'})
@ApiBadRequestResponse({description: 'email address most be unique.'})
@ApiBadRequestResponse({description: 'Data validation failed or Bad request..'})
public async register(
@Res() res: Response,
@Body() createUserDto: CreateAccountDto) {
// const tCreateUserDto = new CreateAccountDto();
// tCreateUserDto.email = createUserDto.email
// tCreateUserDto.firstName = createUserDto.firstName
// tCreateUserDto.lastName = createUserDto.lastName
// tCreateUserDto.password = createUserDto.password
// tCreateUserDto.passwordRepeat = createUserDto.passwordRepeat
const controller = new CreateAccountFactory(this.connection, res);
await new CreateAccountFacade(controller).exec(createUserDto);
}
@Post('auth/verify-email')
@HttpCode(HttpStatus.OK)
@ApiOkResponse({description: 'User has been successfully verified.'})
@ApiBadRequestResponse({description: 'Data validation failed or Bad request..'})
async verifyEmail(
@Res() res: Response,
@Request() req: ExpressRequest,
@Body() verifyUuidDto: VerifyUuidDto) {
verifyUuidDto.inetLocation = new InetLocationDto(req);
await new VerifyEmailAccountFacade(new VerifyEmailAccountFactory(this.connection, res))
.exec(verifyUuidDto);
}
//@UseGuards(AuthGuard('local'))
@UseGuards(LoginGuard)
@Post('auth/login')
@HttpCode(HttpStatus.OK)
@ApiOkResponse({description: 'User has been successfully logged in and tokens generated.'})
@ApiNotFoundResponse({description: 'Wrong email or password.'})
@ApiConflictResponse({description: 'User blocked try later.'})
@ApiBadRequestResponse({description: 'Data validation failed or Bad request.'})
async login(
@Res() res: Response,
@Request() req: ExpressRequest) {
// console.log('accounts.controller::login::CP1::req.user');
// console.dir(req.user);
await new LoginAccountFacade(new LoginAccountFactory(this.connection, res))
.exec(req.user as LoggedInUser, new InetLocationDto(req));
// console.log('accounts.controller::login::CP2::req.user');
// console.dir(req.user);
// return user;
}
//@UseGuards(AuthGuard('jwt'))
//@UseGuards(AuthenticatedGuard)
@Get('me/profile')
@UseGuards(RolesGuard)
@Roles('admin')
async getProfile(@Request() req: ExpressRequest) {
console.log('AccountController::getProfile::CP1::req.user');
console.dir(req.user);
return await req.user;
}
@Post('auth/refresh-access-token')
@HttpCode(HttpStatus.CREATED)
@ApiCreatedResponse({description: 'Access token has been generated successfully.'})
@ApiUnauthorizedResponse({description: 'User has been Logged out.'})
@ApiBadRequestResponse({description: 'Data validation failed or Bad request.'})
async refreshAccessToken(
@Res() res: Response,
@Request() req: ExpressRequest,
@Body() refreshAccessTokenDto: RefreshAccessTokenDto) {
refreshAccessTokenDto.inetLocation = new InetLocationDto(req);
await new RefreshAccessTokenAccountFacade(new RefreshAccessTokenAccountFactory(this.connection, res))
.exec(refreshAccessTokenDto);
}
@Post('auth/forgot-password')
@HttpCode(HttpStatus.OK)
@ApiOkResponse({description: 'Verification has been sent.'})
@ApiNotFoundResponse({description: 'Wrong email or password..'})
@ApiBadRequestResponse({description: 'Data validation failed or Bad request.'})
async forgotPassword(
@Res() res: Response,
@Request() req: ExpressRequest,
@Body() createForgotPasswordDto: CreateForgotPasswordDto) {
await new ForgotPasswordAccountFacade(new ForgotPasswordAccountFactory(this.connection, res))
.exec(createForgotPasswordDto, new InetLocationDto(req));
}
@Post('auth/forgot-password-verify')
@HttpCode(HttpStatus.OK)
@ApiOkResponse({description: 'Now user can reset his/her password.'})
@ApiBadRequestResponse({description: 'Data validation failed or Bad request.'})
async forgotPasswordVerify(
@Res() res: Response,
@Request() req: ExpressRequest,
@Body() verifyUuidDto: VerifyUuidDto) {
await new ForgotPasswordVerifyAccountFacade(new ForgotPasswordVerifyAccountFactory(this.connection, res))
.exec(verifyUuidDto, new InetLocationDto(req));
}
@Post('auth/reset-password')
@HttpCode(HttpStatus.OK)
@ApiOkResponse({description: 'Password has been successfully changed.'})
@ApiBadRequestResponse({description: 'Data validation failed or Bad request.'})
async resetPassword(
@Res() res: Response,
@Body() resetPasswordDto: ResetPasswordDto) {
// return await this.accountService.resetPassword(resetPasswordDto);
await new ResetPasswordAccountFacade(new ResetPasswordAccountFactory(this.connection, res)).exec(resetPasswordDto);
}
} | the_stack |
import { BaseImageryPlugin, ImageryPlugin, IVisualizerEntity, IVisualizerStyle, VisualizersConfig, IVisualizersConfig } from '@ansyn/imagery';
import { uniq } from 'lodash';
import { select, Store } from '@ngrx/store';
import { selectActiveMapId, selectOverlayByMapId } from '@ansyn/map-facade';
import { combineLatest, merge, Observable } from 'rxjs';
import { Inject } from '@angular/core';
import { distinctUntilChanged, map, mergeMap, take, tap, withLatestFrom, filter, skip, switchMapTo } from 'rxjs/operators';
import { AutoSubscription } from 'auto-subscriptions';
import { selectGeoFilterActive } from '../../../../../status-bar/reducers/status-bar.reducer';
import {
selectAnnotationMode,
selectAnnotationProperties,
selectSubMenu,
} from '../../../../../status-bar/components/tools/reducers/tools.reducer';
import { featureCollection, FeatureCollection } from '@turf/turf';
import {
AnnotationMode,
AnnotationsVisualizer,
IDrawEndEvent,
IEditAnnotationMode,
ILabelTranslateMode,
IOLPluginsConfig,
OL_PLUGINS_CONFIG,
OpenLayersMap,
OpenLayersProjectionService
} from '@ansyn/ol';
import { ILayer, LayerType } from '../../../../../menu-items/layers-manager/models/layers.model';
import {
selectActiveAnnotationLayer,
selectLayers,
selectLayersEntities,
selectSelectedLayersIds
} from '../../../../../menu-items/layers-manager/reducers/layers.reducer';
import {
AnnotationRemoveFeature,
AnnotationUpdateFeature,
SetAnnotationMode,
ToolsActionsTypes, UpdateMeasureDataOptionsAction
} from '../../../../../status-bar/components/tools/actions/tools.actions';
import { LogAddFeatureToLayer, UpdateLayer } from '../../../../../menu-items/layers-manager/actions/layers.actions';
import { IOverlaysTranslationData } from '../../../../../menu-items/cases/models/case.model';
import { IOverlay } from '../../../../../overlays/models/overlay.model';
import { selectTranslationData } from '../../../../../overlays/overlay-status/reducers/overlay-status.reducer';
import { SetOverlayTranslationDataAction } from '../../../../../overlays/overlay-status/actions/overlay-status.actions';
import { Actions, ofType } from '@ngrx/effects';
import { GeometryObject } from 'geojson';
import { SubMenuEnum } from '../../../../../status-bar/components/tools/models/tools.model';
// @dynamic
@ImageryPlugin({
supported: [OpenLayersMap],
deps: [Store, Actions, OpenLayersProjectionService, OL_PLUGINS_CONFIG, VisualizersConfig]
})
export class AnsynAnnotationsVisualizer extends BaseImageryPlugin {
protected isContinuousDrawingEnabled: boolean;
protected openLastDrawnAnnotationContextMenuEnabled: boolean;
/** Last selected annotation mode which was not null or undefined */
private lastAnnotationMode: AnnotationMode;
annotationsVisualizer: AnnotationsVisualizer;
overlay: IOverlay;
activeAnnotationLayer$: Observable<ILayer> = combineLatest([
this.store$.pipe(select(selectActiveAnnotationLayer)),
this.store$.pipe(select(selectLayersEntities))
]).pipe(
map(([activeAnnotationLayerId, entities]) => {
return entities[activeAnnotationLayerId];
})
);
getAllAnotationLayers$: Observable<any> = this.store$.select(selectLayers).pipe(
map((layers: ILayer[]) => layers.filter(layer => layer.type === LayerType.annotation))
);
annotationFlag$ = this.store$.select(selectSubMenu).pipe(
map((subMenu: SubMenuEnum) => subMenu === SubMenuEnum.annotations),
distinctUntilChanged());
isActiveMap$ = this.store$.select(selectActiveMapId).pipe(
map((activeMapId: string): boolean => activeMapId === this.mapId),
distinctUntilChanged()
);
@AutoSubscription
activeChange$ = this.store$.pipe(
select(selectActiveMapId),
tap((activeMapId) => {
if (activeMapId !== this.mapId) {
this.annotationsVisualizer.events.onSelect.next([]);
this.annotationsVisualizer.events.onHover.next(null);
}
})
);
@AutoSubscription
geoFilterSearchMode$ = this.store$.pipe(
select(selectGeoFilterActive),
tap((active: boolean) => {
this.annotationsVisualizer.mapSearchIsActive = active;
})
);
@AutoSubscription
annoatationModeChange$: any = this.actions$
.pipe(
ofType(ToolsActionsTypes.STORE.SET_ANNOTATION_MODE),
tap((action: SetAnnotationMode) => {
const annotationMode = Boolean(action.payload) ? action.payload.annotationMode : null;
const useMapId = action.payload && Boolean(action.payload.mapId);
if (!useMapId || (useMapId && action.payload.mapId === this.mapId)) {
this.annotationsVisualizer.setMode(annotationMode, !useMapId);
}
}),
map(action => action.payload ? action.payload.annotationMode : null),
filter(annotationMode => !!annotationMode),
tap(annotationMode => this.lastAnnotationMode = annotationMode)
);
@AutoSubscription
annotationPropertiesChange$: Observable<any> = this.store$.pipe(
select(selectAnnotationProperties),
tap((changes: Partial<IVisualizerStyle>) => this.annotationsVisualizer.updateStyle({ initial: { ...changes } }))
);
@AutoSubscription
onAnnotationsChange$ = combineLatest([
this.store$.pipe(select(selectLayersEntities)),
this.annotationFlag$,
this.store$.select(selectSelectedLayersIds),
this.isActiveMap$,
this.store$.select(selectActiveAnnotationLayer)
]).pipe(
mergeMap(this.onAnnotationsChange.bind(this))
);
constructor(public store$: Store<any>,
protected actions$: Actions,
protected projectionService: OpenLayersProjectionService,
@Inject(OL_PLUGINS_CONFIG) protected olPluginsConfig: IOLPluginsConfig,
@Inject(VisualizersConfig) config: IVisualizersConfig) {
super();
// TODO - refactor with optional chaining when typescript version updated to >= 3.7
this.isContinuousDrawingEnabled = (config && config.AnnotationsVisualizer && config.AnnotationsVisualizer.extra && config.AnnotationsVisualizer.extra.continuousDrawing) ? config.AnnotationsVisualizer.extra.continuousDrawing : false;
this.openLastDrawnAnnotationContextMenuEnabled = (config && config.AnnotationsVisualizer && config.AnnotationsVisualizer.extra && config.AnnotationsVisualizer.extra.openContextMenuOnDrawEnd) ? config.AnnotationsVisualizer.extra.openContextMenuOnDrawEnd : false;
}
get offset() {
return this.annotationsVisualizer.offset;
}
set offset(offset: [number, number]) {
this.annotationsVisualizer.offset = offset;
}
@AutoSubscription
currentOverlay$ = () => this.store$.pipe(
select(selectOverlayByMapId(this.mapId)),
tap(overlay => this.overlay = overlay)
);
@AutoSubscription
onChangeMode$ = () => this.annotationsVisualizer.events.onChangeMode.pipe(
tap((arg: { mode: AnnotationMode, forceBroadcast: boolean }) => {
const newMode = !Boolean(arg.mode) ? undefined : arg.mode; // prevent infinite loop
this.store$.dispatch(new SetAnnotationMode({
annotationMode: newMode,
mapId: arg.forceBroadcast ? null : this.mapId
}));
this.annotationsVisualizer.events.onSelect.next([]);
})
);
@AutoSubscription
onDrawEnd$ = () => this.annotationsVisualizer.events.onDrawEnd.pipe(
withLatestFrom(this.activeAnnotationLayer$),
map(([{ GeoJSON, feature }, activeAnnotationLayer]: [IDrawEndEvent, ILayer]) => {
this.store$.dispatch(new LogAddFeatureToLayer({ layerName: activeAnnotationLayer.name }));
const data = <FeatureCollection<any>>{
...activeAnnotationLayer.data,
features: activeAnnotationLayer.data.features.concat(GeoJSON.features)
};
if (this.overlay) {
GeoJSON.features[0].properties = {
...GeoJSON.features[0].properties,
...this.projectionService.getProjectionProperties(this.communicator, data, feature, this.overlay)
};
}
GeoJSON.features[0].properties = { ...GeoJSON.features[0].properties };
this.store$.dispatch(new UpdateLayer({ id: activeAnnotationLayer.id, data }));
const featureId = this.getFeatureIdFromGeoJson(GeoJSON);
return featureId;
}),
filter(featureId => this.isContinuousDrawingEnabled || (this.openLastDrawnAnnotationContextMenuEnabled && !!featureId)),
tap(this.openLastDrawnAnnotationContextMenuEnabled ? this.openContextMenuByFeatureId : () => {}),
switchMapTo(this.closeContextMenuesAndKeepDrawing$)
);
@AutoSubscription
onAnnotationEditEnd$ = () => this.annotationsVisualizer.events.onAnnotationEditEnd.pipe(
withLatestFrom(this.getAllAnotationLayers$),
tap(([{ GeoJSON, feature }, AnnotationLayers]: [IDrawEndEvent, ILayer[]]) => {
const [geoJsonFeature] = GeoJSON.features;
const layerToUpdate = AnnotationLayers.find((layer: ILayer) => layer.data.features.some(({ id }) => id === geoJsonFeature.id));
if (layerToUpdate) {
const annotationToChangeIndex = layerToUpdate.data.features.findIndex((feature) => feature.id === geoJsonFeature.id);
const data = <FeatureCollection<any>>{ ...layerToUpdate.data,
features: layerToUpdate.data.features.map((existingFeature, index) =>
index === annotationToChangeIndex ? geoJsonFeature : existingFeature)
};
let label = geoJsonFeature.properties.label;
if (geoJsonFeature.properties.label.geometry) {
label = { ...geoJsonFeature.properties.label, geometry: GeoJSON.features[1].geometry };
}
feature.set('label', label);
if (this.overlay) {
geoJsonFeature.properties = {
...geoJsonFeature.properties,
...this.projectionService.getProjectionProperties(this.communicator, data, feature, this.overlay)
};
}
geoJsonFeature.properties = { ...geoJsonFeature.properties, label };
this.store$.dispatch(new UpdateLayer({ id: layerToUpdate.id, data }));
}
})
);
@AutoSubscription
getOffsetFromCase$ = () => combineLatest([this.store$.select(selectTranslationData), this.store$.select(selectOverlayByMapId(this.mapId))]).pipe(
tap(([translationData, overlay]: [IOverlaysTranslationData, IOverlay]) => {
if (overlay && translationData[overlay.id] && translationData[overlay.id].offset) {
this.offset = [...translationData[overlay.id].offset] as [number, number];
} else {
this.offset = [0, 0];
}
this.annotationsVisualizer.onResetView().subscribe();
})
);
@AutoSubscription
removeEntity$ = () => this.annotationsVisualizer.events.removeEntity.pipe(
tap((featureId) => {
this.store$.dispatch(new AnnotationRemoveFeature(featureId));
})
);
@AutoSubscription
updateEntity$ = (): Observable<IVisualizerEntity> => this.annotationsVisualizer.events.updateEntity.pipe(
tap((feature) => {
this.store$.dispatch(new AnnotationUpdateFeature({
featureId: feature.id,
properties: { ...feature }
}));
})
);
@AutoSubscription
onDraggEnd$ = () => this.annotationsVisualizer.events.offsetEntity.pipe(
tap((offset: any) => {
if (this.overlay) {
this.store$.dispatch(new SetOverlayTranslationDataAction({
overlayId: this.overlay.id, offset
}));
}
})
);
onAnnotationsChange([entities, annotationFlag, selectedLayersIds, isActiveMap, activeAnnotationLayer]: [{ [key: string]: ILayer }, boolean, string[], boolean, string]): Observable<any> {
const displayedIds = uniq(
isActiveMap && annotationFlag ? [...selectedLayersIds, activeAnnotationLayer] : [...selectedLayersIds]
)
.filter((id: string) => entities[id] && entities[id].type === LayerType.annotation);
const features = displayedIds.reduce((array, layerId) => [...array, ...entities[layerId].data.features], []);
return this.showAnnotation(featureCollection(features));
}
showAnnotation(annotationsLayer): Observable<any> {
const annotationsLayerEntities = this.annotationsVisualizer.annotationsLayerToEntities(annotationsLayer);
this.annotationsVisualizer.getEntities()
.filter(({ id }) => !annotationsLayerEntities.some((entity) => id === entity.id))
.forEach(({ id }) => this.annotationsVisualizer.removeEntity(id, true));
const entitiesToAdd = annotationsLayerEntities
.filter((entity) => {
const oldEntity = this.annotationsVisualizer.idToEntity.get(entity.id);
if (oldEntity) {
const isShowMeasuresDiff = oldEntity.originalEntity.showMeasures !== entity.showMeasures;
const isShowAreaDiff = oldEntity.originalEntity.showArea !== entity.showArea;
const isLabelDiff = oldEntity.originalEntity.label !== entity.label;
const isFillDiff = oldEntity.originalEntity.style.initial.fill !== entity.style.initial.fill;
const isStrokeWidthDiff = oldEntity.originalEntity.style.initial['stroke-width'] !== entity.style.initial['stroke-width'];
const isStrokeDiff = oldEntity.originalEntity.style.initial['stroke'] !== entity.style.initial['stroke'];
const isOpacityDiff = ['fill-opacity', 'stroke-opacity'].filter((o) => oldEntity.originalEntity.style.initial[o] !== entity.style.initial[o]);
return isShowMeasuresDiff || isLabelDiff || isFillDiff || isStrokeWidthDiff || isStrokeDiff || isOpacityDiff || isShowAreaDiff;
}
return true;
});
return this.annotationsVisualizer.addOrUpdateEntities(entitiesToAdd);
}
onInit() {
super.onInit();
this.annotationsVisualizer = this.communicator.getPlugin(AnnotationsVisualizer);
this.store$.select(selectAnnotationMode)
.pipe(take(1))
.subscribe((annotationMode) => {
this.annotationsVisualizer.setMode(annotationMode, false);
});
}
private openContextMenuByFeatureId = (featureId: string) => this.annotationsVisualizer.events.onSelect.next([featureId]);
private get closeContextMenuesAndKeepDrawing$() {
// TODO - can be replaced with this.communicator.ActiveMap.mouseSingleClick.pipe(...) when most recent changes merged
return this.annotationsVisualizer.events.onClick.pipe(
skip(this.isContinuousDrawingEnabled && !this.openLastDrawnAnnotationContextMenuEnabled ? 0 : 1),
take(1),
tap(_ => {
if (this.openLastDrawnAnnotationContextMenuEnabled) {
this.annotationsVisualizer.events.onSelect.next([]);
}
if (this.isContinuousDrawingEnabled) {
this.annotationsVisualizer.setMode(this.lastAnnotationMode, true);
}
})
);
}
private getFeatureIdFromGeoJson(geoJson: FeatureCollection<GeometryObject, {[name: string]: any}>, index = 0): string {
return (geoJson.features && geoJson.features[index] && geoJson.features[index].id) ?
geoJson.features[index].id.toString() :
null;
}
} | the_stack |
import {
isObject,
merge
} from './mquery-utils';
import {
newRxTypeError,
newRxError
} from '../../../rx-error';
import type {
MangoQuery,
MangoQuerySelector,
MangoQuerySortPart,
MangoQuerySortDirection
} from '../../../types';
declare type MQueryOptions = {
limit?: number;
skip?: number;
sort?: any;
};
export class NoSqlQueryBuilderClass<DocType> {
public options: MQueryOptions = {};
public _conditions: MangoQuerySelector<DocType> = {};
public _fields: any = {};
public _path?: any;
private _distinct: any;
/**
* MQuery constructor used for building queries.
*
* ####Example:
* var query = new MQuery({ name: 'mquery' });
* query.where('age').gte(21).exec(callback);
*
*/
constructor(
mangoQuery?: MangoQuery<DocType>
) {
if (mangoQuery) {
const queryBuilder: NoSqlQueryBuilder<DocType> = this as any;
if (mangoQuery.selector) {
queryBuilder.find(mangoQuery.selector);
}
if (mangoQuery.limit) {
queryBuilder.limit(mangoQuery.limit);
}
if (mangoQuery.skip) {
queryBuilder.skip(mangoQuery.skip);
}
if (mangoQuery.sort) {
mangoQuery.sort.forEach(s => queryBuilder.sort(s));
}
}
}
/**
* Specifies a `path` for use with chaining.
*/
where(_path: string, _val?: MangoQuerySelector<DocType>): NoSqlQueryBuilder<DocType> {
if (!arguments.length) return this as any;
const type = typeof arguments[0];
if ('string' === type) {
this._path = arguments[0];
if (2 === arguments.length) {
this._conditions[this._path] = arguments[1];
}
return this as any;
}
if ('object' === type && !Array.isArray(arguments[0])) {
return this.merge(arguments[0]);
}
throw newRxTypeError('MQ1', {
path: arguments[0]
});
}
/**
* Specifies the complementary comparison value for paths specified with `where()`
* ####Example
* User.where('age').equals(49);
*/
equals(val: any): NoSqlQueryBuilder<DocType> {
this._ensurePath('equals');
const path = this._path;
this._conditions[path] = val;
return this as any;
}
/**
* Specifies the complementary comparison value for paths specified with `where()`
* This is alias of `equals`
*/
eq(val: any): NoSqlQueryBuilder<DocType> {
this._ensurePath('eq');
const path = this._path;
this._conditions[path] = val;
return this as any;
}
/**
* Specifies arguments for an `$or` condition.
* ####Example
* query.or([{ color: 'red' }, { status: 'emergency' }])
*/
or(array: any[]): NoSqlQueryBuilder<DocType> {
const or = this._conditions.$or || (this._conditions.$or = []);
if (!Array.isArray(array)) array = [array];
or.push.apply(or, array);
return this as any;
}
/**
* Specifies arguments for a `$nor` condition.
* ####Example
* query.nor([{ color: 'green' }, { status: 'ok' }])
*/
nor(array: any[]): NoSqlQueryBuilder<DocType> {
const nor = this._conditions.$nor || (this._conditions.$nor = []);
if (!Array.isArray(array)) array = [array];
nor.push.apply(nor, array);
return this as any;
}
/**
* Specifies arguments for a `$and` condition.
* ####Example
* query.and([{ color: 'green' }, { status: 'ok' }])
* @see $and http://docs.mongodb.org/manual/reference/operator/and/
*/
and(array: any[]): NoSqlQueryBuilder<DocType> {
const and = this._conditions.$and || (this._conditions.$and = []);
if (!Array.isArray(array)) array = [array];
and.push.apply(and, array);
return this as any;
}
/**
* Specifies a `$mod` condition
*/
mod(_path: string, _val: number): NoSqlQueryBuilder<DocType> {
let val;
let path;
if (1 === arguments.length) {
this._ensurePath('mod');
val = arguments[0];
path = this._path;
} else if (2 === arguments.length && !Array.isArray(arguments[1])) {
this._ensurePath('mod');
val = (arguments as any).slice();
path = this._path;
} else if (3 === arguments.length) {
val = (arguments as any).slice(1);
path = arguments[0];
} else {
val = arguments[1];
path = arguments[0];
}
const conds = this._conditions[path] || (this._conditions[path] = {});
conds.$mod = val;
return this as any;
}
/**
* Specifies an `$exists` condition
* ####Example
* // { name: { $exists: true }}
* Thing.where('name').exists()
* Thing.where('name').exists(true)
* Thing.find().exists('name')
*/
exists(_path: string, _val: number): NoSqlQueryBuilder<DocType> {
let path;
let val;
if (0 === arguments.length) {
this._ensurePath('exists');
path = this._path;
val = true;
} else if (1 === arguments.length) {
if ('boolean' === typeof arguments[0]) {
this._ensurePath('exists');
path = this._path;
val = arguments[0];
} else {
path = arguments[0];
val = true;
}
} else if (2 === arguments.length) {
path = arguments[0];
val = arguments[1];
}
const conds = this._conditions[path] || (this._conditions[path] = {});
conds.$exists = val;
return this as any;
}
/**
* Specifies an `$elemMatch` condition
* ####Example
* query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})
* query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})
* query.elemMatch('comment', function (elem) {
* elem.where('author').equals('autobot');
* elem.where('votes').gte(5);
* })
* query.where('comment').elemMatch(function (elem) {
* elem.where({ author: 'autobot' });
* elem.where('votes').gte(5);
* })
*/
elemMatch(_path: string, _criteria: any): NoSqlQueryBuilder<DocType> {
if (null === arguments[0])
throw newRxTypeError('MQ2');
let fn;
let path;
let criteria;
if ('function' === typeof arguments[0]) {
this._ensurePath('elemMatch');
path = this._path;
fn = arguments[0];
} else if (isObject(arguments[0])) {
this._ensurePath('elemMatch');
path = this._path;
criteria = arguments[0];
} else if ('function' === typeof arguments[1]) {
path = arguments[0];
fn = arguments[1];
} else if (arguments[1] && isObject(arguments[1])) {
path = arguments[0];
criteria = arguments[1];
} else
throw newRxTypeError('MQ2');
if (fn) {
criteria = new NoSqlQueryBuilderClass;
fn(criteria);
criteria = criteria._conditions;
}
const conds = this._conditions[path] || (this._conditions[path] = {});
conds.$elemMatch = criteria;
return this as any;
}
/**
* Sets the sort order
* If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1.
* If a string is passed, it must be a space delimited list of path names.
* The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.
* ####Example
* query.sort({ field: 'asc', test: -1 });
* query.sort('field -test');
* query.sort([['field', 1], ['test', -1]]);
*/
sort(arg: any): NoSqlQueryBuilder<DocType> {
if (!arg) return this as any;
let len;
const type = typeof arg;
// .sort([['field', 1], ['test', -1]])
if (Array.isArray(arg)) {
len = arg.length;
for (let i = 0; i < arg.length; ++i) {
_pushArr(this.options, arg[i][0], arg[i][1]);
}
return this as any;
}
// .sort('field -test')
if (1 === arguments.length && 'string' === type) {
arg = arg.split(/\s+/);
len = arg.length;
for (let i = 0; i < len; ++i) {
let field = arg[i];
if (!field) continue;
const ascend = '-' === field[0] ? -1 : 1;
if (ascend === -1) field = field.substring(1);
push(this.options, field, ascend);
}
return this as any;
}
// .sort({ field: 1, test: -1 })
if (isObject(arg)) {
const keys = Object.keys(arg);
keys.forEach(field => push(this.options, field, arg[field]));
return this as any;
}
throw newRxTypeError('MQ3', {
args: arguments
});
}
/**
* Merges another MQuery or conditions object into this one.
*
* When a MQuery is passed, conditions, field selection and options are merged.
*
*/
merge(source: any): NoSqlQueryBuilder<DocType> {
if (!source) {
return this as any;
}
if (!canMerge(source)) {
throw newRxTypeError('MQ4', {
source
});
}
if (source instanceof NoSqlQueryBuilderClass) {
// if source has a feature, apply it to ourselves
if (source._conditions)
merge(this._conditions, source._conditions);
if (source._fields) {
if (!this._fields) this._fields = {};
merge(this._fields, source._fields);
}
if (source.options) {
if (!this.options) this.options = {};
merge(this.options, source.options);
}
if (source._distinct)
this._distinct = source._distinct;
return this as any;
}
// plain object
merge(this._conditions, source);
return this as any;
}
/**
* Finds documents.
* ####Example
* query.find()
* query.find({ name: 'Burning Lights' })
*/
find(criteria: any): NoSqlQueryBuilder<DocType> {
if (canMerge(criteria)) {
this.merge(criteria);
}
return this as any;
}
/**
* Make sure _path is set.
*
* @parmam {String} method
*/
_ensurePath(method: any) {
if (!this._path) {
throw newRxError('MQ5', {
method
});
}
}
toJSON(): {
query: MangoQuery<DocType>,
path?: string
} {
const query: MangoQuery<DocType> = {
selector: this._conditions,
};
if (this.options.skip) {
query.skip = this.options.skip;
}
if (this.options.limit) {
query.limit = this.options.limit;
}
if (this.options.sort) {
query.sort = mQuerySortToRxDBSort(this.options.sort);
}
return {
query,
path: this._path
};
}
}
export function mQuerySortToRxDBSort<DocType>(
sort: { [k: string]: 1 | -1 }
): MangoQuerySortPart<DocType>[] {
return Object.entries(sort).map(([k, v]) => {
const direction: MangoQuerySortDirection = v === 1 ? 'asc' : 'desc';
const part: MangoQuerySortPart<DocType> = { [k]: direction } as any;
return part;
});
}
/**
* Because some prototype-methods are generated,
* we have to define the type of NoSqlQueryBuilder here
*/
export interface NoSqlQueryBuilder<DocType = any> extends NoSqlQueryBuilderClass<DocType> {
maxScan: ReturnSelfNumberFunction<DocType>;
batchSize: ReturnSelfNumberFunction<DocType>;
limit: ReturnSelfNumberFunction<DocType>;
skip: ReturnSelfNumberFunction<DocType>;
comment: ReturnSelfFunction<DocType>;
gt: ReturnSelfFunction<DocType>;
gte: ReturnSelfFunction<DocType>;
lt: ReturnSelfFunction<DocType>;
lte: ReturnSelfFunction<DocType>;
ne: ReturnSelfFunction<DocType>;
in: ReturnSelfFunction<DocType>;
nin: ReturnSelfFunction<DocType>;
all: ReturnSelfFunction<DocType>;
regex: ReturnSelfFunction<DocType>;
size: ReturnSelfFunction<DocType>;
}
declare type ReturnSelfFunction<DocType> = (v: any) => NoSqlQueryBuilder<DocType>;
declare type ReturnSelfNumberFunction<DocType> = (v: number | null) => NoSqlQueryBuilder<DocType>;
/**
* limit, skip, maxScan, batchSize, comment
*
* Sets these associated options.
*
* query.comment('feed query');
*/
export const OTHER_MANGO_ATTRIBUTES = ['limit', 'skip', 'maxScan', 'batchSize', 'comment'];
OTHER_MANGO_ATTRIBUTES.forEach(function (method) {
(NoSqlQueryBuilderClass.prototype as any)[method] = function (v: any) {
this.options[method] = v;
return this;
};
});
/**
* gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance
*
* Thing.where('type').nin(array)
*/
export const OTHER_MANGO_OPERATORS = [
'gt', 'gte', 'lt', 'lte', 'ne',
'in', 'nin', 'all', 'regex', 'size'
];
OTHER_MANGO_OPERATORS.forEach(function ($conditional) {
(NoSqlQueryBuilderClass.prototype as any)[$conditional] = function () {
let path;
let val;
if (1 === arguments.length) {
this._ensurePath($conditional);
val = arguments[0];
path = this._path;
} else {
val = arguments[1];
path = arguments[0];
}
const conds = this._conditions[path] === null || typeof this._conditions[path] === 'object' ?
this._conditions[path] :
(this._conditions[path] = {});
conds['$' + $conditional] = val;
return this;
};
});
function push(opts: any, field: string, value: any) {
if (Array.isArray(opts.sort)) {
throw newRxTypeError('MQ6', {
opts,
field,
value
});
}
if (value && value.$meta) {
const sort = opts.sort || (opts.sort = {});
sort[field] = {
$meta: value.$meta
};
return;
}
const val = String(value || 1).toLowerCase();
if (!/^(?:ascending|asc|descending|desc|1|-1)$/.test(val)) {
if (Array.isArray(value)) value = '[' + value + ']';
throw newRxTypeError('MQ7', {
field,
value
});
}
// store `sort` in a sane format
const s = opts.sort || (opts.sort = {});
const valueStr = value.toString()
.replace('asc', '1')
.replace('ascending', '1')
.replace('desc', '-1')
.replace('descending', '-1');
s[field] = parseInt(valueStr, 10);
}
function _pushArr(opts: any, field: string, value: any) {
opts.sort = opts.sort || [];
if (!Array.isArray(opts.sort)) {
throw newRxTypeError('MQ8', {
opts,
field,
value
});
}
/* const valueStr = value.toString()
.replace('asc', '1')
.replace('ascending', '1')
.replace('desc', '-1')
.replace('descending', '-1');*/
opts.sort.push([field, value]);
}
/**
* Determines if `conds` can be merged using `mquery().merge()`
*/
export function canMerge(conds: any): boolean {
return conds instanceof NoSqlQueryBuilderClass || isObject(conds);
}
export function createQueryBuilder<DocType>(query?: MangoQuery<DocType>): NoSqlQueryBuilder<DocType> {
return new NoSqlQueryBuilderClass(query) as NoSqlQueryBuilder<DocType>;
} | the_stack |
// load thingpedia to initialize the polyfill
import 'thingpedia';
process.on('unhandledRejection', (up) => { throw up; });
import '../src/util/config_init';
import assert from 'assert';
import * as path from 'path';
import * as util from 'util';
import * as fs from 'fs';
import * as yaml from 'js-yaml';
import * as db from '../src/util/db';
import * as userModel from '../src/model/user';
import * as organization from '../src/model/organization';
import * as entityModel from '../src/model/entity';
import * as exampleModel from '../src/model/example';
import * as snapshotModel from '../src/model/snapshot';
import * as alexaModelsModel from '../src/model/alexa_model';
import * as user from '../src/util/user';
import * as Importer from '../src/util/import_device';
import * as Validation from '../src/util/validation';
import { makeRandom } from '../src/util/random';
import * as I18n from '../src/util/i18n';
import * as Config from '../src/config';
assert.strictEqual(Config.WITH_THINGPEDIA, 'embedded');
I18n.init(Config.SUPPORTED_LANGUAGES);
const req = {
_ : (x : string ) : string => { return x; },
} as Validation.RequestLike;
async function loadManifest(primaryKind : string) {
const filename = path.resolve(path.dirname(module.filename), './data/' + primaryKind + '.yaml');
return yaml.load((await util.promisify(fs.readFile)(filename)).toString(), { filename }) as any;
}
async function loadAllDevices(dbClient : db.Client, bob : userModel.RowWithOrg, root : userModel.RowWithOrg) {
// "login" as bob
req.user = bob;
// create a snapshot without the new stuff
await snapshotModel.create(dbClient, {
description: 'Test snapshot'
} as snapshotModel.Row);
const invisible = await loadManifest('org.thingpedia.builtin.test.invisible');
await Importer.importDevice(dbClient, req, 'org.thingpedia.builtin.test.invisible', invisible, {
owner: req.user.developer_org || undefined,
iconPath: path.resolve(path.dirname(module.filename), '../data/icon.png'),
approve: false
});
const bing = await loadManifest('com.bing');
await Importer.importDevice(dbClient, req, 'com.bing', bing, {
owner: req.user.developer_org || undefined,
zipFilePath: path.resolve(path.dirname(module.filename), './data/com.bing.zip'),
iconPath: path.resolve(path.dirname(module.filename), './data/com.bing.png'),
approve: true
});
// now "login" as root
req.user = root;
const adminonly = await loadManifest('org.thingpedia.builtin.test.adminonly');
await Importer.importDevice(dbClient, req, 'org.thingpedia.builtin.test.adminonly', adminonly, {
owner: req.user.developer_org || undefined,
iconPath: path.resolve(path.dirname(module.filename), '../data/icon.png'),
approve: false
});
await db.query(dbClient, `insert into device_class_tag(device_id,tag) select id,'featured' from device_class where primary_kind in ('com.bing', 'org.thingpedia.builtin.thingengine.phone')`);
}
async function loadEntityValues(dbClient : db.Client) {
await entityModel.createMany(dbClient, [{
id: 'tt:stock_id',
name: 'Company Stock ID',
language: 'en',
is_well_known: false,
has_ner_support: true,
}]);
await entityModel.createMany(dbClient, [{
id: 'com.spotify:playable',
name: 'Playable item in Spotify',
language: 'en',
is_well_known: false,
has_ner_support: true,
}]);
await entityModel.createMany(dbClient, [{
id: 'com.spotify:song',
name: 'Song in Spotify',
language: 'en',
is_well_known: false,
has_ner_support: true,
subtype_of: 'com.spotify:playable',
}]);
await db.insertOne(dbClient,
`insert ignore into entity_lexicon(language,entity_id,entity_value,
entity_canonical,entity_name) values ?`,
[[
['en', 'org.freedesktop:app_id', 'edu.stanford.Almond', 'almond', 'Almond'],
['en', 'org.freedesktop:app_id', 'org.gnome.Builder', 'gnome builder', 'GNOME Builder'],
['en', 'org.freedesktop:app_id', 'org.gnome.Weather.Application', 'gnome weather', 'GNOME Weather'],
['en', 'tt:stock_id', 'goog', 'alphabet inc.', 'Alphabet Inc.'],
['en', 'tt:stock_id', 'msft', 'microsoft corp.', 'Microsoft Corp.'],
]]);
}
const STRING_VALUES = [
'tt:search_query',
'tt:long_free_text',
'tt:short_free_text',
'tt:person_first_name',
'tt:path_name',
'tt:location',
];
async function loadStringValues(dbClient : db.Client) {
for (const type of STRING_VALUES) {
const filename = path.resolve(path.dirname(module.filename), './data/' + type + '.txt');
const data = (await util.promisify(fs.readFile)(filename)).toString().trim().split('\n');
const {id:typeId} = await db.selectOne(dbClient,
`select id from string_types where language='en' and type_name=?`, [type]);
const mappedData = data.map((line) => {
const parts = line.split('\t');
if (parts.length === 1)
return [typeId, parts[0], parts[0], 1];
if (parts.length === 3)
return [typeId, parts[0], parts[1], parseFloat(parts[2])];
const weight = parseFloat(parts[1]);
if (Number.isNaN(weight))
return [typeId, parts[0], parts[1], 1];
else
return [typeId, parts[0], parts[0], weight];
});
await db.insertOne(dbClient,
`insert into string_values(type_id,value,preprocessed,weight) values ?`, [mappedData]);
}
}
async function loadExamples(dbClient : db.Client, bob : userModel.RowWithOrg) {
const { id: schemaId } = await db.selectOne(dbClient, `select id from device_schema where kind = 'org.thingpedia.builtin.test'`);
const examples = [
// commandpedia
{
id: 999,
schema_id: null,
is_base: false,
language: 'en',
utterance: 'every day at 9:00 AM set my laptop background to pizza images',
preprocessed: 'every day at TIME_0 set my laptop background to pizza images',
target_json: '',
target_code: '( attimer time = TIME_0 ) join ( @com.bing.image_search param:query:String = " pizza " ) => @org.thingpedia.builtin.thingengine.gnome.set_background on param:picture_url:Entity(tt:picture) = param:picture_url:Entity(tt:picture)',
type: 'commandpedia',
owner: bob.id,
click_count: 8,
flags: 'exact',
},
// thingpedia
{
id: 1000,
schema_id: schemaId,
is_base: true,
language: 'en',
utterance: 'eat some data',
preprocessed: 'eat some data',
target_json: '',
target_code: 'action := @org.thingpedia.builtin.test.eat_data();',
type: 'thingpedia',
click_count: 0,
flags: 'template',
name: 'EatData',
},
{
id: 1001,
schema_id: schemaId,
is_base: true,
language: 'en',
utterance: 'get ${p_size} of data',
preprocessed: 'get ${p_size} of data',
target_json: '',
target_code: 'query (p_size : Measure(byte)) := @org.thingpedia.builtin.test.get_data(size=p_size);',
type: 'thingpedia',
click_count: 7,
flags: 'template',
name: 'GenDataWithSize',
},
{
id: 1002,
schema_id: schemaId,
is_base: true,
language: 'en',
utterance: 'keep eating data!',
preprocessed: 'keep eating data !',
target_json: '',
target_code: 'program := monitor @org.thingpedia.builtin.test.get_data() => @org.thingpedia.builtin.test.eat_data();',
type: 'thingpedia',
click_count: 0,
flags: 'template',
name: 'GenDataThenEatData',
},
{
id: 1003,
schema_id: schemaId,
is_base: true,
language: 'en',
utterance: 'keep eating data! (v2)',
preprocessed: 'keep eating data ! -lrb- v2 -rrb-',
target_json: '',
target_code: 'program = monitor(@org.thingpedia.builtin.test.get_data()) => @org.thingpedia.builtin.test.eat_data();',
type: 'thingpedia',
click_count: 0,
flags: 'template',
name: null,
},
{
id: 1004,
schema_id: schemaId,
is_base: true,
language: 'en',
utterance: 'more data eating...',
preprocessed: 'more data eating ...',
target_json: '',
target_code: 'action := @org.thingpedia.builtin.test.eat_data();',
type: 'thingpedia',
click_count: 0,
flags: 'template',
name: null,
},
{
id: 1005,
schema_id: schemaId,
is_base: true,
language: 'en',
utterance: 'more data genning...',
preprocessed: 'more data genning ...',
target_json: '',
target_code: 'query = @org.thingpedia.builtin.test.get_data();',
type: 'thingpedia',
click_count: 0,
flags: 'template',
name: 'GenData'
},
// online
{
id: 1010,
schema_id: null,
is_base: false,
language: 'en',
utterance: 'dial USERNAME_0',
preprocessed: 'dial USERNAME_0',
target_json: '',
target_code: 'now => @org.thingpedia.builtin.thingengine.phone.call param:number:Entity(tt:phone_number) = USERNAME_0',
type: 'online',
click_count: 0,
flags: 'training,exact',
},
{
id: 1011,
schema_id: null,
is_base: false,
language: 'en',
utterance: 'make a call to USERNAME_0',
preprocessed: 'make a call to USERNAME_0',
target_json: '',
target_code: 'now => @org.thingpedia.builtin.thingengine.phone.call param:number:Entity(tt:phone_number) = USERNAME_0',
type: 'online',
click_count: 0,
flags: 'training,exact'
},
{
id: 1012,
schema_id: null,
is_base: false,
language: 'en',
utterance: 'place a call to USERNAME_0',
preprocessed: 'place a call to USERNAME_0',
target_json: '',
target_code: 'now => @org.thingpedia.builtin.thingengine.phone.call param:number:Entity(tt:phone_number) = USERNAME_0',
type: 'online',
click_count: 0,
flags: 'training,exact'
},
{
id: 1013,
schema_id: null,
is_base: false,
language: 'en',
utterance: 'search "pizza" on bing',
preprocessed: 'search QUOTED_STRING_0 on bing',
target_json: '',
target_code: 'now => @com.bing.web_search param:query:String = QUOTED_STRING_0 => notify',
type: 'online',
click_count: 0,
flags: 'training,exact'
},
{
id: 1014,
schema_id: null,
is_base: false,
language: 'en',
utterance: 'search "pizza" on bing images',
preprocessed: 'search QUOTED_STRING_0 on bing images',
target_json: '',
target_code: 'now => @com.bing.image_search param:query:String = QUOTED_STRING_0 => notify',
type: 'online',
click_count: 0,
flags: 'training,exact'
},
{
id: 1015,
schema_id: null,
is_base: false,
language: 'en',
utterance: 'take a screenshot',
preprocessed: 'take a screenshot',
target_json: '',
target_code: 'now => @org.thingpedia.builtin.thingengine.gnome.get_screenshot => notify',
type: 'online',
click_count: 0,
flags: 'training,exact'
},
{
id: 1016,
schema_id: null,
is_base: false,
language: 'en',
utterance: 'what time is it?',
preprocessed: 'what time is it ?',
target_json: '',
target_code: 'now => @org.thingpedia.builtin.thingengine.builtin.get_time => notify',
type: 'online',
click_count: 0,
flags: 'training,exact'
},
{
id: 1017,
schema_id: null,
is_base: false,
language: 'en',
utterance: 'what day is today?',
preprocessed: 'what day is today ?',
target_json: '',
target_code: 'now => @org.thingpedia.builtin.thingengine.builtin.get_date => notify',
type: 'online',
click_count: 0,
flags: 'training,exact'
},
{
id: 1018,
schema_id: null,
is_base: false,
language: 'en',
utterance: 'what\'s today date?',
preprocessed: 'what \'s today date ?',
target_json: '',
target_code: 'now => @org.thingpedia.builtin.thingengine.builtin.get_date => notify',
type: 'online',
click_count: 0,
flags: 'training,exact'
},
{
id: 1019,
schema_id: null,
is_base: false,
language: 'en',
utterance: 'get my sms',
preprocessed: 'get my sms',
target_json: '',
target_code: 'now => @org.thingpedia.builtin.thingengine.phone.sms => notify',
type: 'online',
click_count: 0,
flags: 'training,exact'
}];
await exampleModel.createMany(dbClient, examples, false);
await exampleModel.like(dbClient, bob.id, 999);
}
async function loadAlexaModel(dbClient : db.Client, bob : userModel.RowWithOrg, alexaUser : userModel.RowWithOrg) {
await alexaModelsModel.create(dbClient, {
language: 'en',
tag: 'org.thingpedia.alexa.test',
owner: bob.developer_org || 0,
call_phrase: 'Bob Assistant',
access_token: null,
anonymous_user: alexaUser.id
}, ['com.bing', 'org.thingpedia.builtin.test']);
}
async function main() {
await db.withTransaction(async (dbClient : db.Client) => {
const newOrg = await organization.create(dbClient, {
name: 'Test Org',
comment: '',
id_hash: makeRandom(8),
developer_key: makeRandom(),
is_admin: false
});
const bob = await user.register(dbClient, req, {
username: 'bob',
human_name: 'Bob Builder',
password: '12345678',
email: 'bob@localhost',
email_verified: true,
locale: 'en-US',
timezone: 'America/Los_Angeles',
developer_org: newOrg.id,
profile_flags: user.ProfileFlags.VISIBLE_ORGANIZATION_PROFILE|user.ProfileFlags.SHOW_HUMAN_NAME|user.ProfileFlags.SHOW_PROFILE_PICTURE,
// must be a TRUSTED_DEVELOPER to self-approve the new device
// w/o hacks
developer_status: user.DeveloperStatus.ORG_ADMIN,
roles: user.Role.TRUSTED_DEVELOPER
});
await user.register(dbClient, req, {
username: 'david',
password: '12345678',
email: 'david@localhost',
email_verified: true,
locale: 'en-US',
timezone: 'America/Los_Angeles',
});
const alexaUser = await user.register(dbClient, req, {
username: 'alexa_user',
password: '12345678',
email: 'alexa_user@localhost',
email_verified: true,
locale: 'en-US',
timezone: 'America/Los_Angeles',
});
const [root] = await userModel.getByName(dbClient, 'root');
await loadAllDevices(dbClient, bob, root);
await loadEntityValues(dbClient);
await loadStringValues(dbClient);
await loadExamples(dbClient, bob);
await loadAlexaModel(dbClient, bob, alexaUser);
console.log(`export DEVELOPER_KEY="${newOrg.developer_key}" ROOT_DEVELOPER_KEY="${root.developer_key}"`);
});
await db.tearDown();
}
main(); | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { IotSecuritySolution } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { SecurityCenter } from "../securityCenter";
import {
IoTSecuritySolutionModel,
IotSecuritySolutionListBySubscriptionNextOptionalParams,
IotSecuritySolutionListBySubscriptionOptionalParams,
IotSecuritySolutionListByResourceGroupNextOptionalParams,
IotSecuritySolutionListByResourceGroupOptionalParams,
IotSecuritySolutionListBySubscriptionResponse,
IotSecuritySolutionListByResourceGroupResponse,
IotSecuritySolutionGetOptionalParams,
IotSecuritySolutionGetResponse,
IotSecuritySolutionCreateOrUpdateOptionalParams,
IotSecuritySolutionCreateOrUpdateResponse,
UpdateIotSecuritySolutionData,
IotSecuritySolutionUpdateOptionalParams,
IotSecuritySolutionUpdateResponse,
IotSecuritySolutionDeleteOptionalParams,
IotSecuritySolutionListBySubscriptionNextResponse,
IotSecuritySolutionListByResourceGroupNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing IotSecuritySolution operations. */
export class IotSecuritySolutionImpl implements IotSecuritySolution {
private readonly client: SecurityCenter;
/**
* Initialize a new instance of the class IotSecuritySolution class.
* @param client Reference to the service client
*/
constructor(client: SecurityCenter) {
this.client = client;
}
/**
* Use this method to get the list of IoT Security solutions by subscription.
* @param options The options parameters.
*/
public listBySubscription(
options?: IotSecuritySolutionListBySubscriptionOptionalParams
): PagedAsyncIterableIterator<IoTSecuritySolutionModel> {
const iter = this.listBySubscriptionPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listBySubscriptionPagingPage(options);
}
};
}
private async *listBySubscriptionPagingPage(
options?: IotSecuritySolutionListBySubscriptionOptionalParams
): AsyncIterableIterator<IoTSecuritySolutionModel[]> {
let result = await this._listBySubscription(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listBySubscriptionNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listBySubscriptionPagingAll(
options?: IotSecuritySolutionListBySubscriptionOptionalParams
): AsyncIterableIterator<IoTSecuritySolutionModel> {
for await (const page of this.listBySubscriptionPagingPage(options)) {
yield* page;
}
}
/**
* Use this method to get the list IoT Security solutions organized by resource group.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param options The options parameters.
*/
public listByResourceGroup(
resourceGroupName: string,
options?: IotSecuritySolutionListByResourceGroupOptionalParams
): PagedAsyncIterableIterator<IoTSecuritySolutionModel> {
const iter = this.listByResourceGroupPagingAll(resourceGroupName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByResourceGroupPagingPage(resourceGroupName, options);
}
};
}
private async *listByResourceGroupPagingPage(
resourceGroupName: string,
options?: IotSecuritySolutionListByResourceGroupOptionalParams
): AsyncIterableIterator<IoTSecuritySolutionModel[]> {
let result = await this._listByResourceGroup(resourceGroupName, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByResourceGroupNext(
resourceGroupName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByResourceGroupPagingAll(
resourceGroupName: string,
options?: IotSecuritySolutionListByResourceGroupOptionalParams
): AsyncIterableIterator<IoTSecuritySolutionModel> {
for await (const page of this.listByResourceGroupPagingPage(
resourceGroupName,
options
)) {
yield* page;
}
}
/**
* Use this method to get the list of IoT Security solutions by subscription.
* @param options The options parameters.
*/
private _listBySubscription(
options?: IotSecuritySolutionListBySubscriptionOptionalParams
): Promise<IotSecuritySolutionListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{ options },
listBySubscriptionOperationSpec
);
}
/**
* Use this method to get the list IoT Security solutions organized by resource group.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param options The options parameters.
*/
private _listByResourceGroup(
resourceGroupName: string,
options?: IotSecuritySolutionListByResourceGroupOptionalParams
): Promise<IotSecuritySolutionListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
listByResourceGroupOperationSpec
);
}
/**
* User this method to get details of a specific IoT Security solution based on solution name
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param solutionName The name of the IoT Security solution.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
solutionName: string,
options?: IotSecuritySolutionGetOptionalParams
): Promise<IotSecuritySolutionGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, solutionName, options },
getOperationSpec
);
}
/**
* Use this method to create or update yours IoT Security solution
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param solutionName The name of the IoT Security solution.
* @param iotSecuritySolutionData The security solution data
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
solutionName: string,
iotSecuritySolutionData: IoTSecuritySolutionModel,
options?: IotSecuritySolutionCreateOrUpdateOptionalParams
): Promise<IotSecuritySolutionCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, solutionName, iotSecuritySolutionData, options },
createOrUpdateOperationSpec
);
}
/**
* Use this method to update existing IoT Security solution tags or user defined resources. To update
* other fields use the CreateOrUpdate method.
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param solutionName The name of the IoT Security solution.
* @param updateIotSecuritySolutionData The security solution data
* @param options The options parameters.
*/
update(
resourceGroupName: string,
solutionName: string,
updateIotSecuritySolutionData: UpdateIotSecuritySolutionData,
options?: IotSecuritySolutionUpdateOptionalParams
): Promise<IotSecuritySolutionUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
solutionName,
updateIotSecuritySolutionData,
options
},
updateOperationSpec
);
}
/**
* Use this method to delete yours IoT Security solution
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param solutionName The name of the IoT Security solution.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
solutionName: string,
options?: IotSecuritySolutionDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, solutionName, options },
deleteOperationSpec
);
}
/**
* ListBySubscriptionNext
* @param nextLink The nextLink from the previous successful call to the ListBySubscription method.
* @param options The options parameters.
*/
private _listBySubscriptionNext(
nextLink: string,
options?: IotSecuritySolutionListBySubscriptionNextOptionalParams
): Promise<IotSecuritySolutionListBySubscriptionNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listBySubscriptionNextOperationSpec
);
}
/**
* ListByResourceGroupNext
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method.
* @param options The options parameters.
*/
private _listByResourceGroupNext(
resourceGroupName: string,
nextLink: string,
options?: IotSecuritySolutionListByResourceGroupNextOptionalParams
): Promise<IotSecuritySolutionListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, nextLink, options },
listByResourceGroupNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listBySubscriptionOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Security/iotSecuritySolutions",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.IoTSecuritySolutionsList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion5, Parameters.filter],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/iotSecuritySolutions",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.IoTSecuritySolutionsList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion5, Parameters.filter],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/iotSecuritySolutions/{solutionName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.IoTSecuritySolutionModel
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion5],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.solutionName
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/iotSecuritySolutions/{solutionName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.IoTSecuritySolutionModel
},
201: {
bodyMapper: Mappers.IoTSecuritySolutionModel
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.iotSecuritySolutionData,
queryParameters: [Parameters.apiVersion5],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.solutionName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/iotSecuritySolutions/{solutionName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.IoTSecuritySolutionModel
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.updateIotSecuritySolutionData,
queryParameters: [Parameters.apiVersion5],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.solutionName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/iotSecuritySolutions/{solutionName}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion5],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.solutionName
],
headerParameters: [Parameters.accept],
serializer
};
const listBySubscriptionNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.IoTSecuritySolutionsList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion5, Parameters.filter],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.IoTSecuritySolutionsList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion5, Parameters.filter],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import { UnitRecord } from '../DayFunctions';
import { Locale, Locales } from '../Locale';
// tslint:disable: no-magic-numbers
const unitToWordSingular: UnitRecord<string> = {
millis: 'milliseconde',
second: 'seconde',
minute: 'minuut',
hour: 'uur',
day: 'dag',
week: 'week',
month: 'maand',
quarter: 'kwartaal',
year: 'jaar'
};
const unitToWordPlural: UnitRecord<string> = {
millis: 'milliseconden',
second: 'seconden',
minute: 'minuten',
hour: 'uur',
day: 'dagen',
week: 'weken',
month: 'maanden',
quarter: 'vertrekken',
year: 'jaar'
};
const lc: Locale =
{
weekStartsOn: 1,
firstWeekContainsDate: 4,
am: '',
pm: '',
formatLT: 'HH:mm',
formatLTS: 'HH:mm:ss',
formatL: 'DD-MM-Y',
formatl: 'D-M-Y',
formatLL: 'D MMMM Y',
formatll: 'D MMM Y',
formatLLL: 'D MMMM Y HH:mm',
formatlll: 'D MMM Y HH:mm',
formatLLLL: 'dddd D MMMM Y HH:mm',
formatllll: 'ddd D MMM Y HH:mm',
suffix: (value: number) => {
return value + 'e';
},
identifierTime: (short) => short ? 'lll' : 'LLL',
identifierDay: (short) => short ? 'll' : 'LL',
identifierWeek: (short) => 'wo [week van] Y',
identifierMonth: (short) => short ? 'MMM Y' : 'MMMM Y',
identifierQuarter: (short) => 'Qo [kwartaal] Y',
identifierYear: (short) => 'Y',
patternNone: () => `Geen herhaling`,
patternDaily: () => `Dagelijks`,
patternWeekly: (day) => `Wekelijks op ${lc.weekdays[0][day.day]}`,
patternMonthlyWeek: (day) => `Maandelijks op de ${lc.suffix(day.weekspanOfMonth + 1)} ${lc.weekdays[0][day.day]}`,
patternAnnually: (day) => `Jaarlijks op ${day.dayOfMonth} ${lc.months[0][day.month]}`,
patternAnnuallyMonthWeek: (day) => `Jaarlijks op de ${lc.suffix(day.weekspanOfMonth + 1)} ${lc.weekdays[0][day.day]} van ${lc.months[0][day.month]}`,
patternWeekday: () => 'Iedere werkdag (maandag tot vrijdag)',
patternMonthly: (day) => `Maandelijks op de ${lc.suffix(day.dayOfMonth)}`,
patternLastDay: () => `Laatste dag van de maand`,
patternLastDayOfMonth: (day) => `Laatste dag van ${lc.months[0][day.month]}`,
patternLastWeekday: (day) => `Laatste ${lc.weekdays[0][day.day]} van ${lc.months[0][day.month]}`,
patternCustom: () => `Aangepast...`,
scheduleStartingOn: (start) => `Vanaf ${start.dayOfMonth} ${lc.months[0][start.month]} ${start.year}`,
scheduleEndingOn: (end) => `tot en met ${end.dayOfMonth} ${lc.months[0][end.month]} ${end.year}`,
scheduleEndsOn: (end) => `Tot en met ${end.dayOfMonth} ${lc.months[0][end.month]} ${end.year}`,
scheduleThing: (thing, start) => start
? 'Zal het ' + thing + ' plaatsvinden'
: ' zal het ' + thing + ' plaatsvinden',
scheduleAtTimes: ' om ',
scheduleDuration: (duration, unit) => ' gedurende ' + duration + ' ' + (unit ? (duration !== 1 ? unitToWordPlural[unit] : unitToWordSingular[unit]) + ' ' : ''),
scheduleExcludes: ' met uitzondering van ',
scheduleIncludes: ' inclusief ',
scheduleCancels: ' met annuleringen op ',
ruleDayOfWeek: {
// every 2nd day of the week
every: (every) => `iedere ${lc.suffix(every)} dag van de week`,
// starting on the 5th day of the week
offset: (offset) => `vanaf de ${lc.suffix(offset)} dag van de week`,
// on the 1st, 2nd, and 4th day of the week
oneOf: (values) => `op de ${lc.list(values.map(lc.suffix))} dag van de week`
},
ruleLastDayOfMonth: {
// every 3rd last day of the month
every: (every) => `iedere ${lc.suffix(every)} laatste dag van de maand`,
// starting on the 2nd last day of the month
offset: (offset) => `vanaf de ${lc.suffix(offset)} laatste dag van de maand`,
// on the 1st, 2nd, and 3rd last day of the month
oneOf: (values) => `op de ${lc.list(values.map(lc.suffix))} laatste dag van de maand`
},
ruleDayOfMonth: {
// every 3rd day of the month
every: (every) => `iedere ${lc.suffix(every)} dag van de maand`,
// starting on the 2nd day of the month
offset: (offset) => `vanaf de ${lc.suffix(offset)} dag van de maand`,
// on the 1st, 2nd, and 3rd day of the month
oneOf: (values) => `op de ${lc.list(values.map(lc.suffix))} dag van de maand`
},
ruleDayOfYear: {
// every 3rd day of the year
every: (every) => `iedere ${lc.suffix(every)} dag van het jaar`,
// starting on the 2nd day of the year
offset: (offset) => `vanaf de ${lc.suffix(offset + 1)} dag van het jaar`,
// on the 1st, 2nd, and 3rd day of the year
oneOf: (values) => `op de ${lc.list(values.map(lc.suffix))} dag van het jaar`
},
ruleYear: {
// every 3rd year
every: (every) => `iedere ${lc.suffix(every)} jaar`,
// starting in 2018
offset: (offset) => `vanaf ${offset}`,
// in 2019, 2020, and 2021
oneOf: (values) => `in ${lc.list(values.map(x => x.toString()))}`
},
ruleMonth: {
// every 3rd month
every: (every) => `iedere ${lc.suffix(every)} maand`,
// starting in February
offset: (offset) => `vanaf ${lc.months[0][offset]}`,
// in February, May, and June
oneOf: (values) => `in ${lc.list(values.map(x => lc.months[0][x]))}`
},
ruleDay: {
// every 2nd day of the week
every: (every) => `iedere ${lc.suffix(every)} dag van de week`,
// starting on Tuesday
offset: (offset) => `vanaf ${lc.weekdays[0][offset]}`,
// on Monday, Wednesday, and Friday
oneOf: (values) => `on ${lc.list(values.map(v => lc.weekdays[0][v]))}`
},
ruleWeek: {
// every 3rd week of the year
every: (every) => `iedere ${lc.suffix(every)} week van het jaar`,
// starting on the 2nd week of the year
offset: (offset) => `vanaf de ${lc.suffix(offset)} week van het jaar`,
// on the 1st, 2nd, and 3rd week of the year
oneOf: (values) => `op de ${lc.list(values.map(lc.suffix))} week van het jaar`
},
ruleWeekOfYear: {
// every 3rd week of the year
every: (every) => `iedere ${lc.suffix(every)} week van het jaar`,
// starting on the 2nd week of the year
offset: (offset) => `vanaf de ${lc.suffix(offset)} week van het jaar`,
// on the 1st, 2nd, and 3rd week of the year
oneOf: (values) => `op de ${lc.list(values.map(lc.suffix))} week van het jaar`
},
ruleWeekspanOfYear: {
// every 3rd weekspan of the year
every: (every) => `iedere ${lc.suffix(every + 1)} weekspanne van het jaar`,
// starting on the 2nd weekspan of the year
offset: (offset) => `vanaf de ${lc.suffix(offset + 1)} weekspanne van het jaar`,
// on the 1st, 2nd, and 3rd weekspan of the year
oneOf: (values) => `op de ${lc.list(values.map(x => lc.suffix(x + 1)))} weekspanne van het jaar`
},
ruleFullWeekOfYear: {
// every 3rd full week of the year
every: (every) => `iedere ${lc.suffix(every)} hele week van het jaar`,
// starting on the 2nd full week of the year
offset: (offset) => `vanaf de ${lc.suffix(offset)} hele week van het jaar`,
// on the 1st, 2nd, and 3rd full week of the year
oneOf: (values) => `op de ${lc.list(values.map(lc.suffix))} hele week van het jaar`
},
ruleLastWeekspanOfYear: {
// every 3rd last weekspan of the year
every: (every) => `iedere ${lc.suffix(every + 1)} laatste weekspanne van het jaar`,
// starting on the 2nd last weekspan of the year
offset: (offset) => `vanaf de ${lc.suffix(offset + 1)} laatste weekspanne van het jaar`,
// on the 1st, 2nd, and 3rd last weekspan of the year
oneOf: (values) => `op de ${lc.list(values.map(x => lc.suffix(x + 1)))} last weekspan van het jaar`
},
ruleLastFullWeekOfYear: {
// every 3rd last full week of the year
every: (every) => `iedere ${lc.suffix(every)} laatste hele week van het jaar`,
// starting on the 2nd last full week of the year
offset: (offset) => `vanaf de ${lc.suffix(offset)} laatste hele week van het jaar`,
// on the 1st, 2nd, and 3rd last full week of the year
oneOf: (values) => `op de ${lc.list(values.map(lc.suffix))} laatste hele week van het jaar`
},
ruleWeekOfMonth: {
// every 3rd week of the month
every: (every) => `iedere ${lc.suffix(every)} week van de maand`,
// starting on the 2nd week of the month
offset: (offset) => `vanaf de ${lc.suffix(offset)} week van de maand`,
// on the 1st, 2nd, and 3rd week of the month
oneOf: (values) => `op de ${lc.list(values.map(lc.suffix))} week van de maand`
},
ruleFullWeekOfMonth: {
// every 3rd full week of the month
every: (every) => `iedere ${lc.suffix(every)} hele week van de maand`,
// starting on the 2nd full week of the month
offset: (offset) => `vanaf de ${lc.suffix(offset)} hele week van de maand`,
// on the 1st, 2nd, and 3rd full week of the month
oneOf: (values) => `op de ${lc.list(values.map(lc.suffix))} hele week van de maand`
},
ruleWeekspanOfMonth: {
// every 3rd weekspan of the month
every: (every) => `iedere ${lc.suffix(every + 1)} weekspanne van de maand`,
// starting on the 2nd weekspan of the month
offset: (offset) => `vanaf de ${lc.suffix(offset + 1)} weekspanne van de maand`,
// on the 1st, 2nd, and 3rd weekspan of the month
oneOf: (values) => `op de ${lc.list(values.map(x => lc.suffix(x + 1)))} weekspanne van de maand`
},
ruleLastFullWeekOfMonth: {
// every 3rd last full week of the month
every: (every) => `iedere ${lc.suffix(every)} laatste hele week van de maand`,
// starting on the 2nd last full week of the month
offset: (offset) => `vanaf de ${lc.suffix(offset)} laatste hele week van de maand`,
// on the 1st, 2nd, and 3rd full week of the month
oneOf: (values) => `op de ${lc.list(values.map(lc.suffix))} laatste hele week van de maand`
},
ruleLastWeekspanOfMonth: {
// every 3rd last weekspan of the month
every: (every) => `iedere ${lc.suffix(every + 1)} laatste weekspanne van de maand`,
// starting on the 2nd last weekspan of the month
offset: (offset) => `vanaf de ${lc.suffix(offset + 1)} laatste weekspanne van de maand`,
// on the 1st, 2nd, and 3rd last weekspan of the month
oneOf: (values) => `op de ${lc.list(values.map(x => lc.suffix(x + 1)))} last weekspanne van de maand`
},
summaryDay: (short, dayOfWeek, year) => (dayOfWeek ? (short ? 'ddd ' : 'dddd ') : '') + 'D ' + (short ? 'MMM ' : 'MMMM ') + (year ? 'Y' : ''),
summaryWeek: (short, dayOfWeek, year) => (dayOfWeek ? (short ? 'ddd ' : 'dddd ') : '') + 'D ' + (short ? 'MMM ' : 'MMMM ') + (year ? 'Y' : ''),
summaryMonth: (short, dayOfWeek, year) => (short ? 'MMM' : 'MMMM') + (year ? ' YYYY' : ''),
summaryYear: (short, dayOfWeek, year) => (year ? 'YYYY' : ''),
list: (items) => {
const last: number = items.length - 1;
let out: string = items[0];
for (let i = 1; i < last; i++) {
out += ', ' + items[i];
}
if (last > 0) {
out += ' en ' + items[last];
}
return out;
},
months: [
['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december'],
['jan', 'feb', 'mrt', 'apr', 'mei', 'jun', 'jul', 'aug', 'sept', 'okt', 'nov', 'dec'],
['jan', 'feb', 'mrt', 'apr', 'mei', 'jun', 'jul', 'aug', 'sept', 'okt', 'nov', 'dec'],
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D']
],
weekdays: [
['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'],
['zon', 'maan', 'din', 'woen', 'don', 'vrij', 'zat'],
['zon', 'maa', 'din', 'woe', 'don', 'vrij', 'zat'],
['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],
],
};
export default lc;
Locales.add(['nl', 'nl-be'], lc); | the_stack |
export type SemVer = string;
// tslint:disable:no-reserved-keywords
export interface Option {
title?: string;
type: "string" | "boolean" | "integer" | "array";
description: string;
/**
* Available since version
*/
since: SemVer;
/**
* Deprecated since version
*/
deprecated?: SemVer;
default?: any;
enum?: any[];
maximum?: number;
minimum?: number;
multipleOf?: number;
items?: {
type: string;
};
}
// tslint:enable:no-reserved-keywords
export interface OptionsRegistry {
[key: string]: Option;
}
export const Options: OptionsRegistry = {
align_assignments: {
default: false,
description:
"If lists of assignments or properties should be vertically aligned for faster " +
"and easier reading.",
since: "0.7.0",
type: "boolean",
},
arrow_parens: {
default: "always",
description: "Require parenthesis in arrow function arguments",
enum: ["always", "as-needed"],
since: "0.7.0",
type: "string",
},
brace_style: {
default: "collapse",
description: "Brace style",
enum: [
"collapse",
"collapse-preserve-inline",
"expand",
"end-expand",
"none",
],
since: "0.7.0",
type: "string",
},
break_chained_methods: {
default: false,
description: "Break chained method calls across subsequent lines",
since: "0.7.0",
type: "boolean",
},
comma_first: {
default: false,
description: "Put commas at the beginning of new line instead of end",
since: "0.7.0",
type: "boolean",
},
end_of_line: {
default: "System Default",
description: "End-Of-Line (EOL) separator",
enum: ["CRLF", "LF", "System Default"],
since: "0.7.0",
type: "string",
},
end_with_comma: {
default: false,
description:
"If a terminating comma should be inserted into arrays, object literals, and de" +
"structured objects.",
since: "0.7.0",
type: "boolean",
},
end_with_newline: {
default: false,
description: "End output with newline",
since: "0.7.0",
type: "boolean",
},
end_with_semicolon: {
default: false,
description: "Insert a semicolon at the end of statements",
since: "0.7.0",
type: "boolean",
},
force_indentation: {
default: false,
description:
"if indentation should be forcefully applied to markup even if it disruptively " +
"adds unintended whitespace to the documents rendered output",
since: "0.7.0",
type: "boolean",
},
identifier_case: {
default: "lowercase",
description: "Case type for identifiers",
enum: ["lowercase", "uppercase", "capitalize"],
since: "0.17.0",
type: "string",
},
indent_chained_methods: {
default: true,
description: "Indent chained method calls",
since: "0.10.0",
type: "boolean",
},
indent_char: {
default: " ",
deprecated: "0.8.0",
description: "Indentation character",
enum: [" ", "\t"],
since: "0.7.0",
type: "string",
},
indent_comments: {
default: true,
description: "Determines whether comments should be indented.",
since: "0.7.0",
type: "boolean",
},
indent_inner_html: {
default: false,
description: "Indent <head> and <body> sections.",
since: "0.7.0",
type: "boolean",
},
indent_level: {
default: 0,
description: "Initial indentation level",
minimum: 0,
multipleOf: 1,
since: "0.7.0",
type: "integer",
},
indent_scripts: {
default: "normal",
description: "Indent scripts",
enum: ["keep", "separate", "normal"],
since: "0.7.0",
type: "string",
},
indent_size: {
default: 2,
description: "Indentation size/length",
minimum: 0,
multipleOf: 1,
since: "0.7.0",
type: "integer",
},
indent_style: {
default: "space",
description: "Indentation style",
enum: ["space", "tab"],
since: "0.8.0",
type: "string",
},
indent_with_tabs: {
default: true,
deprecated: "0.8.0",
description:
"Indentation uses tabs, overrides `Indent Size` and `Indent Char`",
since: "0.7.0",
type: "boolean",
},
jslint_happy: {
default: false,
description: "Enable jslint-stricter mode",
since: "0.7.0",
title: "JSLint Happy",
type: "boolean",
},
jsx_brackets: {
default: false,
description:
"Put the `>` of a multi-line JSX element at the end of the last line",
since: "0.7.0",
title: "JSX Brackets",
type: "boolean",
},
keep_array_indentation: {
default: false,
description: "Preserve array indentation",
since: "0.7.0",
type: "boolean",
},
keyword_case: {
default: "lowercase",
description: "Case type for keywords",
enum: ["lowercase", "uppercase", "capitalize"],
since: "0.17.0",
type: "string",
},
max_preserve_newlines: {
default: 10,
description: "Number of line-breaks to be preserved in one chunk",
multipleOf: 1,
since: "0.7.0",
type: "integer",
},
multiline_ternary: {
default: "always",
description:
"Enforces new lines between the operands of a ternary expression",
enum: ["always", "always-multiline", "never"],
since: "0.7.0",
type: "string",
},
newline_before_tags: {
default: ["head", "body", "/html"],
description: "List of tags which should have an extra newline before them.",
items: {
type: "string",
},
since: "0.7.0",
type: "array",
},
newline_between_rules: {
default: true,
description: "Add a newline between CSS rules",
since: "0.7.0",
type: "boolean",
},
no_leading_zero: {
default: false,
description:
"If in CSS values leading 0s immediately preceeding a decimal should be removed" +
" or prevented.",
since: "0.7.0",
type: "boolean",
},
object_curly_spacing: {
default: true,
description:
"Inserts a space before/after brackets for object literals, destructuring assig" +
"nments, and import/export specifiers",
since: "0.7.0",
type: "boolean",
},
pragma_insert: {
default: false,
description:
"Insert a marker at the top of a file specifying the file has been beautified",
since: "0.7.0",
type: "boolean",
},
pragma_require: {
default: false,
description:
"Restrict beautifying files to only those with a pragma at the top",
since: "0.7.0",
type: "boolean",
},
preserve_newlines: {
default: true,
description: "Preserve line-breaks",
since: "0.7.0",
type: "boolean",
},
quotes: {
default: "none",
description:
"Convert the quote characters delimiting strings from either double or single q" +
"uotes to the other.",
enum: ["none", "double", "single"],
since: "0.7.0",
type: "string",
},
remove_trailing_whitespace: {
default: false,
description: "Remove trailing whitespace",
since: "0.7.0",
type: "boolean",
},
selector_separator_newline: {
default: false,
description: "Add a newline between multiple selectors",
since: "0.7.0",
type: "boolean",
},
space_after_anon_function: {
default: false,
description:
"Add a space before an anonymous function's parentheses. ie. `function ()`",
since: "0.7.0",
type: "boolean",
},
space_before_conditional: {
default: true,
description: "Add a space before conditional, `if(true)` vs `if (true)`",
since: "0.7.0",
type: "boolean",
},
space_in_empty_paren: {
default: false,
description: "Add padding spaces within empty parentheses, ie. `f( )`",
since: "0.7.0",
type: "boolean",
},
space_in_paren: {
default: false,
description: "Add padding spaces within parentheses, ie. `f( a, b )`",
since: "0.7.0",
type: "boolean",
},
typesafe_equality_operators: {
default: false,
description:
"Use typesafe equality operators (`===` and `!==` instead of `==` and `!=`)",
since: "0.10.0",
type: "boolean",
},
unescape_strings: {
default: false,
description: "Decode printable characters encoded in xNN notation",
since: "0.7.0",
type: "boolean",
},
unformatted: {
default: [
"a",
"abbr",
"area",
"audio",
"b",
"bdi",
"bdo",
"br",
"button",
"canvas",
"cite",
"code",
"data",
"datalist",
"del",
"dfn",
"em",
"embed",
"i",
"iframe",
"img",
"input",
"ins",
"kbd",
"keygen",
"label",
"map",
"mark",
"math",
"meter",
"noscript",
"object",
"output",
"progress",
"q",
"ruby",
"s",
"samp",
"select",
"small",
"span",
"strong",
"sub",
"sup",
"svg",
"template",
"textarea",
"time",
"u",
"var",
"video",
"wbr",
"text",
"acronym",
"address",
"big",
"dt",
"strike",
"tt",
"pre",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
],
description:
"List of tags (defaults to inline) that should not be reformatted",
items: {
type: "string",
},
since: "0.7.0",
type: "array",
},
unindent_chained_methods: {
default: false,
deprecated: "0.10.0",
description: "Do not indent chained method calls",
since: "0.7.0",
type: "boolean",
},
wrap_attributes: {
default: "auto",
description: "Wrap attributes to new lines",
enum: ["auto", "force", "force-aligned"],
since: "0.7.0",
type: "string",
},
wrap_attributes_indent_size: {
default: 4,
description: "Indent wrapped attributes to after N characters",
minimum: 0,
multipleOf: 1,
since: "0.7.0",
type: "integer",
},
wrap_line_length: {
default: 80,
description: "Wrap lines at next opportunity after N characters",
minimum: 0,
multipleOf: 1,
since: "0.7.0",
type: "integer",
},
wrap_prose: {
default: "preserve",
description: "Wrap markdown text to new lines",
enum: ["always", "never", "preserve"],
since: "0.7.0",
type: "string",
},
}; | the_stack |
'use strict';
import {shallowEquals} from './objects';
import {BaseEvent, Postable} from './base-event';
import {SyncEvent, VoidSyncEvent} from './sync-event';
import {AsyncEvent, AsyncEventOpts} from './async-event';
import {QueuedEvent, QueuedEventOpts} from './queued-event';
export enum EventType {
Sync,
Async,
Queued
}
export interface AnyEventOpts {
/**
* Create evtFirstAttached and evtLastDetached so you can monitor when someone is subscribed
*/
monitorAttach?: boolean;
}
/**
* An event that behaves like a Sync/Async/Queued event depending on how
* you subscribe.
*/
export class AnyEvent<T> implements Postable<T> {
/**
* Sent when someone attaches or detaches
*/
public get evtListenersChanged(): VoidSyncEvent {
if (!this._listenersChanged) {
// need to delay-load to avoid stack overflow in constructor
this._listenersChanged = new VoidSyncEvent();
}
return this._listenersChanged;
}
/**
* Event for listening to listener count
*/
private _listenersChanged?: VoidSyncEvent;
/**
* Triggered whenever someone attaches and nobody was attached.
* Note: you must call the constructor with monitorAttach set to true to create this event!
*/
public evtFirstAttached: VoidAnyEvent;
/**
* Triggered whenever someone detaches and nobody is attached anymore
* Note: you must call the constructor with monitorAttach set to true to create this event!
*/
public evtLastDetached: VoidAnyEvent;
/**
* Underlying event implementations; one for every attach type + opts combination
*/
private _events: BaseEvent<T>[] = [];
constructor(opts?: AnyEventOpts) {
if (opts && opts.monitorAttach) {
this.evtFirstAttached = new VoidAnyEvent();
this.evtLastDetached = new VoidAnyEvent();
}
}
/**
* Legacy method
* same as attachSync/attachAsync/attachQueued; based on the given enum
* @param mode determines whether to attach sync/async/queued
*/
public attach(handler: (data: T) => void, opts?: AsyncEventOpts | QueuedEventOpts): () => void;
public attach(boundTo: Object, handler: (data: T) => void, opts?: AsyncEventOpts | QueuedEventOpts): () => void;
public attach(event: Postable<T>, opts?: AsyncEventOpts | QueuedEventOpts): () => void;
public attach(mode: EventType, handler: (data: T) => void, opts?: AsyncEventOpts | QueuedEventOpts): () => void;
public attach(mode: EventType, boundTo: Object, handler: (data: T) => void, opts?: AsyncEventOpts | QueuedEventOpts): () => void;
public attach(mode: EventType, event: Postable<T>, opts?: AsyncEventOpts | QueuedEventOpts): () => void;
public attach(...args: any[]): () => void {
let mode = EventType.Sync;
if (args.length > 0 && typeof args[0] === 'number') {
mode = args.shift() as EventType;
}
let boundTo: Object = this; // add ourselves as default 'boundTo' argument
let handler: ((data: T) => void) | undefined;
let opts: AsyncEventOpts | QueuedEventOpts;
let postable: Postable<T> | undefined;
if (typeof args[0] === 'function' || (args[0] && typeof args[0] === 'object' && typeof args[0].post === 'function')) {
if (typeof args[0] === 'function') {
handler = args[0];
} else {
postable = args[0];
}
opts = args[1];
} else {
boundTo = args[0];
handler = args[1];
opts = args[2];
}
return this._attach(mode, boundTo, handler, postable, opts, false);
}
/**
* Legacy method
* same as onceSync/onceAsync/onceQueued; based on the given enum
* @param mode determines whether to once sync/async/queued
*/
public once(handler: (data: T) => void, opts?: AsyncEventOpts | QueuedEventOpts): () => void;
public once(boundTo: Object, handler: (data: T) => void, opts?: AsyncEventOpts | QueuedEventOpts): () => void;
public once(event: Postable<T>, opts?: AsyncEventOpts | QueuedEventOpts): () => void;
public once(mode: EventType, handler: (data: T) => void, opts?: AsyncEventOpts | QueuedEventOpts): () => void;
public once(mode: EventType, boundTo: Object, handler: (data: T) => void, opts?: AsyncEventOpts | QueuedEventOpts): () => void;
public once(mode: EventType, event: Postable<T>, opts?: AsyncEventOpts | QueuedEventOpts): () => void;
public once(...args: any[]): () => void {
let mode = EventType.Sync;
if (args.length > 0 && typeof args[0] === 'number') {
mode = args.shift() as EventType;
}
let boundTo: object = this; // add ourselves as default 'boundTo' argument
let handler: ((data: T) => void) | undefined;
let opts: AsyncEventOpts | QueuedEventOpts;
let postable: Postable<T> | undefined;
if (typeof args[0] === 'function' || (args[0] && typeof args[0] === 'object' && typeof args[0].post === 'function')) {
if (typeof args[0] === 'function') {
handler = args[0];
} else {
postable = args[0];
}
opts = args[1];
} else {
boundTo = args[0];
handler = args[1];
opts = args[2];
}
return this._attach(mode, boundTo, handler, postable, opts, true);
}
private _attach(
mode: EventType,
boundTo: Object | undefined,
handler: ((data: T) => void) | undefined,
postable: Postable<T> | undefined,
opts: AsyncEventOpts | QueuedEventOpts | undefined,
once: boolean
): () => void {
const prevCount = (!!this.evtFirstAttached ? this.listenerCount() : 0);
let event: BaseEvent<T> | undefined;
switch (mode) {
case EventType.Sync: {
for (const evt of this._events) {
if (evt instanceof SyncEvent) {
event = evt;
}
}
if (!event) {
event = new SyncEvent<T>();
this._events.push(event);
}
} break;
case EventType.Async: {
for (const evt of this._events) {
if (evt instanceof AsyncEvent && shallowEquals((<AsyncEvent<T>>evt).options, opts)) {
event = evt;
}
}
if (!event) {
event = new AsyncEvent<T>(opts);
this._events.push(event);
}
} break;
case EventType.Queued: {
for (const evt of this._events) {
if (evt instanceof QueuedEvent && shallowEquals((<QueuedEvent<T>>evt).options, opts)) {
event = evt;
}
}
if (!event) {
event = new QueuedEvent<T>(opts);
this._events.push(event);
}
} break;
default:
throw new Error('unknown EventType');
}
let detacher: () => void;
if (once) {
if (postable) {
detacher = event.once(postable);
} else {
detacher = event.once(boundTo!, handler!);
}
} else {
if (postable) {
detacher = event.attach(postable);
} else {
detacher = event.attach(boundTo!, handler!);
}
}
if (this.evtFirstAttached && prevCount === 0) {
this.evtFirstAttached.post();
}
if (this.evtListenersChanged && prevCount !== this.listenerCount()) {
this.evtListenersChanged.post();
}
return (): void => {
const prevCount = (!!this.evtLastDetached ? this.listenerCount() : 0);
detacher();
if (!!this.evtLastDetached && prevCount > 0 && this.listenerCount() === 0) {
this.evtLastDetached.post();
}
if (this.evtListenersChanged && prevCount !== this.listenerCount()) {
this.evtListenersChanged.post();
}
};
}
public attachSync(handler: (data: T) => void): () => void;
public attachSync(boundTo: Object, handler: (data: T) => void): () => void;
public attachSync(event: Postable<T>): () => void;
public attachSync(...args: any[]): () => void {
args.unshift(EventType.Sync);
return this.attach.apply(this, args);
}
public onceSync(handler: (data: T) => void): () => void;
public onceSync(boundTo: Object, handler: (data: T) => void): () => void;
public onceSync(event: Postable<T>): () => void;
public onceSync(...args: any[]): () => void {
args.unshift(EventType.Sync);
return this.once.apply(this, args);
}
public attachAsync(handler: (data: T) => void, opts?: AsyncEventOpts): () => void;
public attachAsync(boundTo: Object, handler: (data: T) => void, opts?: AsyncEventOpts): () => void;
public attachAsync(event: Postable<T>, opts?: AsyncEventOpts): () => void;
public attachAsync(...args: any[]): () => void {
args.unshift(EventType.Async);
return this.attach.apply(this, args);
}
public onceAsync(handler: (data: T) => void, opts?: AsyncEventOpts): () => void;
public onceAsync(boundTo: Object, handler: (data: T) => void, opts?: AsyncEventOpts): () => void;
public onceAsync(event: Postable<T>, opts?: AsyncEventOpts): () => void;
public onceAsync(...args: any[]): () => void {
args.unshift(EventType.Async);
return this.once.apply(this, args);
}
public attachQueued(handler: (data: T) => void, opts?: QueuedEventOpts): () => void;
public attachQueued(boundTo: Object, handler: (data: T) => void, opts?: QueuedEventOpts): () => void;
public attachQueued(event: Postable<T>, opts?: QueuedEventOpts): () => void;
public attachQueued(...args: any[]): () => void {
args.unshift(EventType.Queued);
return this.attach.apply(this, args);
}
public onceQueued(handler: (data: T) => void, opts?: QueuedEventOpts): () => void;
public onceQueued(boundTo: Object, handler: (data: T) => void, opts?: QueuedEventOpts): () => void;
public onceQueued(event: Postable<T>, opts?: QueuedEventOpts): () => void;
public onceQueued(...args: any[]): () => void {
args.unshift(EventType.Queued);
return this.once.apply(this, args);
}
public detach(handler: (data: T) => void): void;
public detach(boundTo: Object, handler: (data: T) => void): void;
public detach(boundTo: Object): void;
public detach(event: Postable<T>): void;
public detach(): void;
/**
* Detach event handlers regardless of type
*/
public detach(...args: any[]): void {
const prevCount = this.listenerCount();
for (let i = 0; i < this._events.length; ++i) {
this._events[i].detach.apply(this._events[i], args);
}
if (this.evtListenersChanged && prevCount !== this.listenerCount()) {
this.evtListenersChanged.post();
}
if (!!this.evtLastDetached && prevCount > 0 && this.listenerCount() === 0) {
this.evtLastDetached.post();
}
}
/**
* Post an event to all current listeners
*/
public post(data: T): void {
// make a copy of the array first to cover the case where event handlers
// are attached during the post
const events: BaseEvent<T>[] = [];
for (let i = 0; i < this._events.length; ++i) {
events.push(this._events[i]);
}
for (let i = 0; i < events.length; ++i) {
events[i].post(data);
}
}
/**
* The number of attached listeners
*/
public listenerCount(): number {
let result = 0;
for (let i = 0; i < this._events.length; ++i) {
result += this._events[i].listenerCount();
}
return result;
}
}
/**
* Convenience class for AnyEvents without data
*/
export class VoidAnyEvent extends AnyEvent<void> {
/**
* Send the AsyncEvent.
*/
public post(): void {
super.post(undefined);
}
}
/**
* Similar to 'error' event on EventEmitter: throws when a post() occurs while no handlers set.
*/
export class ErrorAnyEvent extends AnyEvent<Error> {
public post(data: Error): void {
if (this.listenerCount() === 0) {
throw new Error(`error event posted while no listeners attached. Error: ${data.message}`);
}
super.post(data);
}
} | the_stack |
/// <reference path="../../scripts/typings/libs/html.ts" />
class QueryView
{
//these will be replaced by some event dispatcher,
//keep it simple for now
public RetrieveInstanceEvent: (mediaType:string) => any = null;
private _parent: HTMLElement;
private _model: QueryModel;
private _retrieveService : RetrieveService;
private _$studyItemTemplate: JQuery;
private _$seriesItemTemplate: JQuery;
private _$instanceItemTemplate: JQuery;
private _$selectedStudyView: JQuery;
private _$studiesView: JQuery;
private _$seriesView: JQuery;
private _$instanceView: JQuery;
//EVENTS
private _onPreviewStudy = new LiteEvent<StudyEventArgs>();
private _onQidoStudy = new LiteEvent<QidoRsEventArgs>();
private _onQidoSeries = new LiteEvent<QidoRsEventArgs>();
private _onQidoInstance = new LiteEvent<QidoRsEventArgs>();
private _onInstanceMetadata = new LiteEvent<RsInstanceEventArgs>();
private _onInstance = new LiteEvent<RsInstanceEventArgs>();
private _onFrames = new LiteEvent<RsFramesEventArgs>();
private _onWadoUri = new LiteEvent<WadoUriEventArgs>();
private _onDeleteStudy = new LiteEvent<StudyEventArgs>();
private _onShowStudyViewer = new LiteEvent<StudyEventArgs>();
private _onQuerySeries = new LiteEvent<void>();
private _onQueryInstances = new LiteEvent<void>();
private _onViewInstance = new LiteEvent<WadoUriEventArgs>();
private _ViewClassName = {
$SeriesQuery: ".series-query", $StudyQuery: ".studies-query", $InstanceQuery: ".instance-query",
SeriesQuery: "series-query", StudyQuery: "studies-query", InstanceQuery: "instance-query" };
constructor(parentElement: HTMLElement, model: QueryModel, retrieveService: RetrieveService) {
this._parent = parentElement;
this._model = model;
this._retrieveService = retrieveService;
this._$studiesView = $(this._ViewClassName.$StudyQuery);
this._$seriesView = $(this._ViewClassName.$SeriesQuery);
this._$instanceView = $(this._ViewClassName.$InstanceQuery);
this.buildQueryControl();
this.createViewTemplates();
$(".instance-details").hide();
this.registerEvents();
}
public get qidoStudy() { return this._onQidoStudy; }
public get qidoSeries() { return this._onQidoSeries; }
public get qidoInstance() { return this._onQidoInstance; }
public get instanceMetaDataRequest() { return this._onInstanceMetadata; }
public get instanceRequest() { return this._onInstance; }
public get framesRequest() { return this._onFrames; }
public get wadoUriRequest() { return this._onWadoUri; }
public get deleteStudyRequest() { return this._onDeleteStudy; }
public get showStudyViewer() { return this._onShowStudyViewer; }
public get previewStudy() { return this._onPreviewStudy; }
public get instanceViewRequest() { return this._onViewInstance; }
public get querySeries() { return this._onQuerySeries; }
public get queryInstances() { return this._onQueryInstances; }
public clearInstanceMetadata()
{
new CodeRenderer().renderValue($(".pacs-metadata-viewer")[0], "");
}
public showInstanceMetadata(data: any, args: RsInstanceEventArgs)
{
if (args.MediaType == MimeTypes.Json) { this.renderJson($(".pacs-metadata-viewer"), data); }
if (args.MediaType == MimeTypes.xmlDicom) { this.renderXml($(".pacs-metadata-viewer"), data); }
}
private bin2String(array: any) {
return String.fromCharCode.apply(String, array);
}
private registerEvents()
{
this._model.StudiesChangedEvent = () => {
this.renderStudies();
};
this._model.SeriesChangedEvent = () => {
this.renderSeries();
};
this._model.InstancesChangedEvent = () => {
this.renderInstances();
};
this._model.SelectedStudyChangedEvent.on(() => {
var index = this._model.SelectedStudyIndex;
this._$studiesView.find(".thumbnail").removeClass("selected");
if (index != -1) {
this._$studiesView.find(".thumbnail").eq(index).addClass("selected");
$(".study-overview").text("| (Patient: " + this._model.Studies[index].PatientName.Alphabetic + ")");
}
else
{
$(".study-overview").text("");
}
});
this._model.SelectedSeriesChangedEvent.on(() => {
var index = this._model.SelectedSeriesIndex;
this._$seriesView.find(".thumbnail").removeClass("selected");
if (index != -1) {
this._$seriesView.find(".thumbnail").eq(index).addClass("selected");
}
});
this._model.SelectedInstanceChangedEvent.on(() => {
var index = this._model.SelectedInstanceIndex;
this._$instanceView.find(".thumbnail").removeClass("selected");
this.clearInstanceMetadata();
if (index == -1) {
$(".instance-details").hide();
}
else {
this._$instanceView.find(".thumbnail").eq(index).addClass("selected");
$(".instance-details").show();
}
});
$("*[data-rs-frames]").on("click", (ev: JQueryEventObject) => {
var instance = this._model.selectedInstance();
if (instance) {
var frameList = this.geFramsList();
var args = new RsFramesEventArgs(instance, $(ev.target).attr("data-pacs-args"), frameList);
this._onFrames.trigger(args);
}
ev.preventDefault();
return false;
});
$("*[data-uri-instance]").on("click", (ev: JQueryEventObject) => {
var instance = this._model.selectedInstance();
if (instance) {
var frame = this.geUriFrame();
var args = new WadoUriEventArgs(instance, $(ev.target).attr("data-pacs-args"), frame);
this._onWadoUri.trigger(args);
}
ev.preventDefault();
return false;
});
}
private StudiesChangedHandler(){
this.renderStudies();
}
public SeriesChangedHandler() {
this.renderSeries();
}
public render() {
this.renderStudies();
this.renderSeries();
this.renderInstances();
}
private renderStudies()
{
$(this._ViewClassName.$StudyQuery).html("");
this._model.Studies.forEach((value: StudyParams, index: number, array: StudyParams[]) => {
var $studyItem :JQuery = this.createStudyItem(value,index);
$studyItem.appendTo($(this._ViewClassName.$StudyQuery));
});
if (!$("#studyCollapse").hasClass("in")) {
$("#studyCollapse").collapse("show");
}
var pageText = "";
if (this._model.StudyPaginationModel.totalCount > this._model.StudyPaginationModel.pageLimit) {
pageText = (this._model.StudyPaginationModel.currentOffset + 1) + "-" + (this._model.StudyPaginationModel.currentOffset + this._model.Studies.length) + " of " + this._model.StudyPaginationModel.totalCount;
}
else
{
pageText = this._model.Studies.length + "";
}
$("*[data-pacs-study-count]").text(pageText);
}
private renderSeries() {
this._$seriesView.html("");
this._model.Series.forEach((value: SeriesParams, index: number, array: SeriesParams[]) => {
var $seriesItem: JQuery = this.createSeriesItem(value, index);
$seriesItem.appendTo(this._$seriesView);
});
$("#seriesCollapse").collapse("show");
$("*[data-pacs-series-count]").text(this._model.Series.length);
}
private renderInstances() {
this._$instanceView.html("");
this.renderJson($(".pacs-metadata-viewer"), "");
this._model.Instances.forEach((value: InstanceParams, index: number, array: InstanceParams[]) => {
var $instanceItem: JQuery = this.createInstanceItem(value, index);
$instanceItem.appendTo(this._$instanceView);
});
$("#instanceCollapse").collapse("show");
$("*[data-pacs-instance-count]").text(this._model.Instances.length);
}
private buildQueryControl()
{
$("#searchButton").click((args: JQueryEventObject) => {
var queryModel :StudyParams = this._model.StudyQueryParams;
queryModel.PatientId = $("#patientIdInput").val();
queryModel.PatientName = $("#patientNameInput").val();
queryModel.StudyDate = $("#studyDateInput").val();
queryModel.StudyID = $("#studyIdInput").val();
this._model.StudyQueryParams = queryModel;
return false;
});
}
//TODO: zaid-move this to the app
private createViewTemplates()
{
this.createStudyTemplate();
this.createSeriesTemplate();
this.createInstanceTemplate();
}
private getTemplateRelativePath(templatePath: string): string
{
//take the relative path name and remove / if exists
return window.location.pathname.replace(/\/$/, "") + templatePath;
}
private createStudyTemplate()
{
var ajaxSettings: JQueryAjaxSettings = {};
ajaxSettings.url = this.getTemplateRelativePath("/_StudyItem/");
ajaxSettings.success = (data: any, textStatus: string, jqXHR: JQueryXHR) => {
this._$studyItemTemplate = $(data);
};
ajaxSettings.error = (jsXHR: JQueryXHR, testStatus: string, errorThrown: string) => {
new ModalDialog().showError("Error", "error getting study item");
};
$.ajax(ajaxSettings);
}
private createSeriesTemplate()
{
$.get(this.getTemplateRelativePath("/_SeriesItem/"), (data: any, textStatus: string, jqXHR: JQueryXHR) => {
this._$seriesItemTemplate = $(data);
}, "html");
}
private createInstanceTemplate() {
$.get(this.getTemplateRelativePath("/_InstanceItem/"), (data: any, textStatus: string, jqXHR: JQueryXHR) => {
this._$instanceItemTemplate = $(data);
}, "html");
}
private getContentView ( $parentView :JQuery, viewId:string ):JQuery
{
var targetItemId = $parentView.find("*[data-target]").attr("data-target");
if (targetItemId) {
var $seriesView: JQuery;
$parentView.find("*[data-target]").attr("data-target", "#" + viewId );
$seriesView = $parentView.find(targetItemId);
$seriesView.attr("id", viewId);
return $seriesView;
}
return null;
}
private createStudyItem(study: StudyParams, index: number): JQuery
{
var $item = this._$studyItemTemplate.clone();
var patientName = "";
if (study.PatientName)
{
patientName = study.PatientName.Alphabetic;
}
$item.find("*[data-pacs-patientName]").text(patientName);
$item.find("*[data-pacs-patientId]").text(study.PatientId);
$item.find("*[data-pacs-accessionNumber]").text(study.AccessionNumber);
$item.find("*[data-pacs-studyDate]").text(study.StudyDate);
$item.find("*[data-pacs-studyID]").text(study.StudyID);
$item.find("*[data-pacs-studyDesc]").text(study.StudyDescription);
this.registerStudyEvents(study, $item, index);
return $item;
}
private createSeriesItem(series: SeriesParams, index: number): JQuery {
var $item = this._$seriesItemTemplate.clone();
this.updateSeriesItem(series, $item);
this.registerSeriesEvents(series, $item, index);
return $item;
}
private createInstanceItem(instance: InstanceParams, index: number): JQuery{
var $item = this._$instanceItemTemplate.clone();
$item.find("*[data-pacs-InstanceNum]").text(instance.InstanceNumber);
//$item.find("*[data-pacs-SopInstanceUid]").text(instance.SopInstanceUid);
this.registerInstanceEvents(instance, $item, index);
return $item;
}
private updateSeriesItem(series: SeriesParams, $item: JQuery)
{
$item.find("*[data-pacs-seriesNum]").text(series.SeriesNumber);
$item.find("*[data-pacs-modality]").text(series.Modality);
$item.find("*[data-pacs-seriesDesc]").text(series.SeriesDescription);
$item.find("*[data-pacs-seriesDate]").text(series.SeriesDate);
}
private registerStudyEvents(study: StudyParams, $item: JQuery, index: number)
{
$item.find(".thumbnail").on("click", (ev: JQueryEventObject) => {
var args = new StudyEventArgs(study);
this._onPreviewStudy.trigger(args);
this._model.SelectedStudyIndex = index;
ev.preventDefault();
return false;
});
$item.find("*[data-pacs-study-json]").on("click", (ev: JQueryEventObject) => {
this._retrieveService.getStudyAsJson(study, (studyInstances: any) => {
this.ViewJsonDlg(studyInstances, "(" + studyInstances.length + ") Study Instances Response");
});
ev.preventDefault();
return false;
});
$item.find("*[data-pacs-study-xml]").on("click", (ev: JQueryEventObject) => {
this._retrieveService.getStudyAsXml(study, (studyInstances: any) => {
this.ViewXmlDlg(studyInstances, "Multipart DICOM+XML Study Instances Response");
});
ev.preventDefault();
return false;
});
$item.find('*[data-pacs-viewQidoStudy="json"]').on("click", (ev: JQueryEventObject) => {
var args = new QidoRsEventArgs(MimeTypes.Json, study.StudyInstanceUid);
this._onQidoStudy.trigger(args);
ev.preventDefault();
return false;
});
$item.find('*[data-pacs-viewQidoStudy="xml"]').on("click", (ev: JQueryEventObject) => {
var args = new QidoRsEventArgs(MimeTypes.xmlDicom, study.StudyInstanceUid);
this._onQidoStudy.trigger(args);
ev.preventDefault();
return false;
});
$item.find('*[data-pacs-deletestudy="true"]').on("click", (ev: JQueryEventObject) => {
var args = new StudyEventArgs(study);
this._onDeleteStudy.trigger(args);
ev.preventDefault();
return false;
});
$item.find('*[data-pacs-ohifviewer]').on("click", (ev: JQueryEventObject) => {
var args = new StudyEventArgs(study);
this._onShowStudyViewer.trigger(args);
ev.preventDefault();
return false;
});
$item.find('*[data-pacs-querySeries]').on("click", (ev: JQueryEventObject) => {
$("#studyCollapse").collapse("hide");
this._model.SelectedStudyIndex = index;
this._onQuerySeries.trigger();
ev.preventDefault();
return false;
});
}
private registerSeriesEvents(series: SeriesParams, $item: JQuery, index:number) {
$item.find(".panel-body").on("click", (ev: Event) => {
this._model.SelectedSeriesIndex = index;
this._onQueryInstances.trigger();
$("#seriesCollapse").collapse("hide");
ev.preventDefault();
return false;
});
$item.find("*[data-pacs-series-json]").on("click", (ev: JQueryEventObject) => {
this._retrieveService.getSeries(series, (seriesInstances: any) => {
this.ViewJsonDlg(seriesInstances, "(" + seriesInstances.length + ") Series Instances Response");
}, MimeTypes.Json);
ev.preventDefault();
return false;
});
$item.find("*[data-pacs-series-xml]").on("click", (ev: JQueryEventObject) => {
this._retrieveService.getSeries(series, (seriesInstances: any) => {
this.ViewXmlDlg(seriesInstances, "Multipart DICOM+XML Study Instances Response");
}, MimeTypes.xmlDicom);
ev.preventDefault();
return false;
});
$item.find('*[data-pacs-viewQidoSeries="json"]').on("click", (ev: JQueryEventObject) => {
var args = new QidoRsEventArgs(MimeTypes.Json, series.StudyInstanceUid, series.SeriesInstanceUID);
this._onQidoSeries.trigger(args);
ev.preventDefault();
return false;
});
$item.find('*[data-pacs-viewQidoSeries="xml"]').on("click", (ev: JQueryEventObject) => {
var args = new QidoRsEventArgs(MimeTypes.xmlDicom, series.StudyInstanceUid, series.SeriesInstanceUID);
this._onQidoSeries.trigger(args);
ev.preventDefault();
return false;
});
}
private registerInstanceEvents(instance: InstanceParams, $item: JQuery, index: number) {
$item.find(".panel-body").on("click", (ev: JQueryEventObject) => {
this._model.SelectedInstanceIndex = index;
ev.preventDefault();
return false;
});
$item.find('*[data-pacs-viewQidoInstance="json"]').on("click", (ev: JQueryEventObject) => {
var args = new QidoRsEventArgs(MimeTypes.Json, instance.StudyInstanceUid, instance.SeriesInstanceUID, instance.SopInstanceUid);
this._onQidoInstance.trigger(args);
ev.preventDefault();
return false;
});
$item.find('*[data-pacs-viewQidoInstance="xml"]').on("click", (ev: JQueryEventObject) => {
var args = new QidoRsEventArgs(MimeTypes.xmlDicom, instance.StudyInstanceUid, instance.SeriesInstanceUID, instance.SopInstanceUid);
this._onQidoInstance.trigger(args);
ev.preventDefault();
return false;
});
$item.find("*[data-pacs-instance-json]").on("click", (ev: JQueryEventObject) => {
this._retrieveService.getObjectInstanceMetadata(instance, (instanceJson: any) => {
this.ViewJsonDlg(instanceJson, "Instance Response");
}, MimeTypes.Json );
ev.preventDefault();
return false;
});
$item.find("*[data-pacs-instance-xml]").on("click", (ev: JQueryEventObject) => {
this._retrieveService.getObjectInstanceMetadata(instance, (instanceXml: any) => {
this.ViewXmlDlg(instanceXml, "Multipart DICOM+XML Instance Response");
}, MimeTypes.xmlDicom);
ev.preventDefault();
return false;
});
$item.find("*[data-pacs-viewInstanceViewer]").on("click", (ev: JQueryEventObject) => {
this._onViewInstance.trigger(new WadoUriEventArgs(instance, MimeTypes.DICOM, ""));
ev.preventDefault();
return false;
});
$item.find("*[data-rs-instance]").on("click", (ev: JQueryEventObject) => {
var args = new RsInstanceEventArgs(instance, $(ev.target).attr("data-pacs-args"));
this._onInstance.trigger(args);
ev.preventDefault();
return false;
});
}
private geFramsList() : string
{
var frameNumber: string;
frameNumber = $("*[data-rs-frames-input]").val();
if (frameNumber)
{
return frameNumber ;
}
return "1";
}
private geUriFrame(): string
{
return $("*[data-uri-frame-input]").val();
}
public ViewJsonDlg(data: any, caption: string) {
var dlg = new ModalDialog("#modal-alert");
dlg.showJson(caption, data);
}
public ViewXmlDlg(data: any, caption: string)
{
var dlg = new ModalDialog("#modal-alert");
dlg.showXml(caption, data);
}
private renderJson($contentElement: JQuery, data: any) {
new CodeRenderer().renderJson($contentElement[0], data);
}
private renderXml($contentElement: JQuery, data: any) {
new CodeRenderer().renderXml($contentElement[0], data);
}
} | the_stack |
import ComponentRepository from '../core/ComponentRepository';
import Component from '../core/Component';
import MeshComponent from './MeshComponent';
import WebGLStrategy from '../../webgl/WebGLStrategy';
import {ProcessApproachEnum} from '../definitions/ProcessApproach';
import {ProcessStage, ProcessStageEnum} from '../definitions/ProcessStage';
import EntityRepository from '../core/EntityRepository';
import SceneGraphComponent from './SceneGraphComponent';
import WebGLResourceRepository from '../../webgl/WebGLResourceRepository';
import {WellKnownComponentTIDs} from './WellKnownComponentTIDs';
import CameraComponent from './CameraComponent';
import Matrix44 from '../math/Matrix44';
import Accessor from '../memory/Accessor';
import CGAPIResourceRepository from '../renderer/CGAPIResourceRepository';
import MemoryManager from '../core/MemoryManager';
import Config from '../core/Config';
import {BufferUse} from '../definitions/BufferUse';
import {CompositionType} from '../definitions/CompositionType';
import {ComponentType} from '../definitions/ComponentType';
import ModuleManager from '../system/ModuleManager';
import CubeTexture from '../textures/CubeTexture';
import Entity from '../core/Entity';
import RenderPass from '../renderer/RenderPass';
import {Visibility} from '../definitions/visibility';
import RnObject from '../core/RnObject';
import {
ComponentSID,
CGAPIResourceHandle,
Count,
Index,
ObjectUID,
ComponentTID,
EntityUID,
} from '../../types/CommonTypes';
import AbstractMaterialNode from '../materials/core/AbstractMaterialNode';
import {IMatrix44} from '../math/IMatrix';
export default class MeshRendererComponent extends Component {
private __meshComponent?: MeshComponent;
static __shaderProgramHandleOfPrimitiveObjectUids: Map<
ObjectUID,
CGAPIResourceHandle
> = new Map();
private __sceneGraphComponent?: SceneGraphComponent;
public diffuseCubeMap?: CubeTexture;
public specularCubeMap?: CubeTexture;
public diffuseCubeMapContribution = 1.0;
public specularCubeMapContribution = 1.0;
public rotationOfCubeMap = 0;
private static __webglResourceRepository?: WebGLResourceRepository;
private static __componentRepository: ComponentRepository = ComponentRepository.getInstance();
private static __instanceIDBufferUid: CGAPIResourceHandle =
CGAPIResourceRepository.InvalidCGAPIResourceUid;
private static __webglRenderingStrategy?: WebGLStrategy;
private static __instanceIdAccessor?: Accessor;
private static __tmp_identityMatrix: IMatrix44 = Matrix44.identity();
private static __cameraComponent?: CameraComponent;
private static __firstTransparentIndex = -1;
private static __lastTransparentIndex = -1;
private static __manualTransparentSids?: ComponentSID[];
public _readyForRendering = false;
public static isViewFrustumCullingEnabled = true;
public static isDepthMaskTrueForTransparencies = false;
constructor(
entityUid: EntityUID,
componentSid: ComponentSID,
entityRepository: EntityRepository
) {
super(entityUid, componentSid, entityRepository);
this.__sceneGraphComponent = this.__entityRepository.getComponentOfEntity(
this.__entityUid,
SceneGraphComponent
) as SceneGraphComponent;
const componentRepository = ComponentRepository.getInstance();
const cameraComponents = componentRepository.getComponentsWithType(
CameraComponent
) as CameraComponent[];
if (cameraComponents) {
MeshRendererComponent.__cameraComponent = cameraComponents[0];
}
}
static get componentTID(): ComponentTID {
return WellKnownComponentTIDs.MeshRendererComponentTID;
}
static get firstTransparentIndex() {
return MeshRendererComponent.__firstTransparentIndex;
}
static get lastTransparentIndex() {
return MeshRendererComponent.__lastTransparentIndex;
}
private static __isReady() {
if (
MeshRendererComponent.__instanceIDBufferUid !==
CGAPIResourceRepository.InvalidCGAPIResourceUid
) {
return true;
} else {
return false;
}
}
private static __setupInstanceIDBuffer() {
if (MeshRendererComponent.__instanceIdAccessor == null) {
const buffer = MemoryManager.getInstance().createOrGetBuffer(
BufferUse.CPUGeneric
);
const count = Config.maxEntityNumber;
const bufferView = buffer.takeBufferView({
byteLengthToNeed: 4 /*byte*/ * count,
byteStride: 0,
});
MeshRendererComponent.__instanceIdAccessor = bufferView.takeAccessor({
compositionType: CompositionType.Scalar,
componentType: ComponentType.Float,
count: count,
});
}
const meshComponents = MeshRendererComponent.__componentRepository.getComponentsWithType(
MeshComponent
);
if (meshComponents == null) {
return CGAPIResourceRepository.InvalidCGAPIResourceUid;
}
for (let i = 0; i < meshComponents.length; i++) {
MeshRendererComponent.__instanceIdAccessor!.setScalar(
i,
meshComponents[i].entityUID,
{}
);
}
return MeshRendererComponent.__webglResourceRepository!.createVertexBuffer(
MeshRendererComponent.__instanceIdAccessor!
);
}
static set manualTransparentSids(sids: ComponentSID[]) {
MeshRendererComponent.__manualTransparentSids = sids;
}
static set manualTransparentEntityNames(names: string[]) {
MeshRendererComponent.__manualTransparentSids = [];
for (const name of names) {
const entity = RnObject.getRnObjectByName(name) as Entity;
if (entity) {
const meshComponent = entity.getMesh();
if (meshComponent) {
const mesh = meshComponent.mesh;
if (mesh) {
if (!mesh.isOpaque()) {
MeshRendererComponent.__manualTransparentSids.push(
meshComponent.componentSID
);
}
}
}
}
}
}
$create() {
this.__meshComponent = this.__entityRepository.getComponentOfEntity(
this.__entityUid,
MeshComponent
) as MeshComponent;
this.moveStageTo(ProcessStage.Load);
}
static common_$load({
processApproach,
}: {
processApproach: ProcessApproachEnum;
}) {
const moduleManager = ModuleManager.getInstance();
const moduleName = 'webgl';
const webglModule = moduleManager.getModule(moduleName)! as any;
// Strategy
MeshRendererComponent.__webglRenderingStrategy = webglModule.getRenderingStrategy(
processApproach
);
// ResourceRepository
MeshRendererComponent.__webglResourceRepository = webglModule.WebGLResourceRepository.getInstance();
AbstractMaterialNode.initDefaultTextures();
}
$load() {
MeshRendererComponent.__webglRenderingStrategy!.$load(
this.__meshComponent!
);
if (this.diffuseCubeMap && !this.diffuseCubeMap.startedToLoad) {
this.diffuseCubeMap.loadTextureImagesAsync();
}
if (this.specularCubeMap && !this.specularCubeMap.startedToLoad) {
this.specularCubeMap.loadTextureImagesAsync();
}
this.moveStageTo(ProcessStage.PreRender);
}
static common_$prerender(): CGAPIResourceHandle {
const gl = MeshRendererComponent.__webglResourceRepository!
.currentWebGLContextWrapper;
if (gl == null) {
throw new Error('No WebGLRenderingContext!');
}
MeshRendererComponent.__webglRenderingStrategy!.common_$prerender();
if (MeshRendererComponent.__isReady()) {
return 0;
}
MeshRendererComponent.__instanceIDBufferUid = MeshRendererComponent.__setupInstanceIDBuffer();
return MeshRendererComponent.__instanceIDBufferUid;
}
$prerender() {
MeshRendererComponent.__webglRenderingStrategy!.$prerender(
this.__meshComponent!,
this,
MeshRendererComponent.__instanceIDBufferUid
);
this.moveStageTo(ProcessStage.Render);
}
static sort_$render(renderPass: RenderPass): ComponentSID[] {
if (MeshRendererComponent.__manualTransparentSids == null) {
const sortedMeshComponentSids = MeshRendererComponent.sort_$render_inner(
void 0,
renderPass
);
// const sortedMeshComponentSids = MeshRendererComponent.sort_$render_inner();
return sortedMeshComponentSids;
} else {
const sortedMeshComponentSids = MeshRendererComponent.sort_$render_inner(
MeshRendererComponent.__manualTransparentSids,
renderPass
);
// const sortedMeshComponentSids = MeshRendererComponent.sort_$render_inner(MeshRendererComponent.__manualTransparentSids);
return sortedMeshComponentSids;
}
}
private static sort_$render_inner(
transparentMeshComponentSids_: ComponentSID[] = [],
renderPass: RenderPass
) {
const sceneGraphComponents = renderPass.sceneTopLevelGraphComponents!;
let meshComponents: MeshComponent[] = [];
const componentRepository = ComponentRepository.getInstance();
let cameraComponent = renderPass.cameraComponent;
if (cameraComponent == null) {
cameraComponent = componentRepository.getComponent(
CameraComponent,
CameraComponent.main
) as CameraComponent;
}
if (cameraComponent && MeshRendererComponent.isViewFrustumCullingEnabled) {
cameraComponent.updateFrustum();
const whetherContainsSkeletal = (sg: SceneGraphComponent): boolean => {
const skeletalComponent = sg.entity.getSkeletal();
if (skeletalComponent != null) {
return true;
} else {
const children = sg.children;
for (const child of children) {
return whetherContainsSkeletal(child);
}
return false;
}
};
const frustum = cameraComponent.frustum;
const doAsVisible = (
sg: SceneGraphComponent,
meshComponents: MeshComponent[]
) => {
const sgs = SceneGraphComponent.flattenHierarchy(sg, false);
for (const sg of sgs) {
const mesh = sg.entity.getMesh();
if (mesh) {
meshComponents!.push(mesh);
}
}
};
const frustumCullingRecursively = (
sg: SceneGraphComponent,
meshComponents: MeshComponent[]
) => {
const result = frustum.culling(sg);
if (result === Visibility.Visible) {
doAsVisible(sg, meshComponents);
} else if (
result === Visibility.Neutral ||
whetherContainsSkeletal(sg)
) {
const children = sg.children;
const mesh = sg.entity.getMesh();
if (mesh) {
meshComponents!.push(mesh);
}
for (const child of children) {
frustumCullingRecursively(child, meshComponents);
}
}
};
for (const tlsg of sceneGraphComponents) {
frustumCullingRecursively(tlsg, meshComponents);
}
} else {
meshComponents = renderPass!.meshComponents!;
}
meshComponents = Array.from(new Set(meshComponents));
const opaqueAndTransparentPartiallyMeshComponentSids: ComponentSID[] = [];
const transparentPartiallyMeshComponents: MeshComponent[] = [];
const transparentCompletelyMeshComponents: MeshComponent[] = [];
for (let i = 0; i < meshComponents.length; i++) {
if (!meshComponents[i].entity.getSceneGraph().isVisible) {
continue;
}
const meshRendererComponent = meshComponents[i].entity.getMeshRenderer();
if (meshRendererComponent.currentProcessStage === ProcessStage.Render) {
const meshComponent = meshComponents[i];
if (meshComponent.mesh) {
if (
transparentMeshComponentSids_.length === 0 &&
meshComponent.mesh.isBlendPartially()
) {
transparentPartiallyMeshComponents.push(meshComponent);
opaqueAndTransparentPartiallyMeshComponentSids.push(
meshComponent.componentSID
);
} else if (
transparentMeshComponentSids_.length === 0 &&
meshComponent.mesh.isAllBlend()
) {
transparentCompletelyMeshComponents.push(meshComponent);
}
if (meshComponent.mesh.isOpaque()) {
opaqueAndTransparentPartiallyMeshComponentSids.push(
meshComponent.componentSID
);
} else {
if (cameraComponent) {
meshComponent.calcViewDepth(cameraComponent);
}
}
} else {
MeshComponent.alertNoMeshSet(meshComponent);
}
}
}
// Sort transparent meshes
const transparentPartiallyOrAllMeshComponents = transparentPartiallyMeshComponents.concat(
transparentCompletelyMeshComponents
);
transparentPartiallyOrAllMeshComponents.sort((a, b) => {
return a.viewDepth - b.viewDepth;
});
let transparentMeshComponentSids;
if (transparentMeshComponentSids_.length === 0) {
transparentMeshComponentSids = transparentPartiallyOrAllMeshComponents.map(
meshComponent => {
return meshComponent.componentSID;
}
);
} else {
transparentMeshComponentSids = transparentMeshComponentSids_;
}
MeshRendererComponent.__firstTransparentIndex =
opaqueAndTransparentPartiallyMeshComponentSids.length;
// Concat opaque and transparent meshes
const sortedMeshComponentSids = opaqueAndTransparentPartiallyMeshComponentSids.concat(
transparentMeshComponentSids
);
MeshRendererComponent.__lastTransparentIndex =
sortedMeshComponentSids.length - 1;
// Add terminator
sortedMeshComponentSids.push(Component.invalidComponentSID);
return sortedMeshComponentSids;
}
static common_$render({
renderPass,
processStage,
renderPassTickCount,
}: {
renderPass: RenderPass;
processStage: ProcessStageEnum;
renderPassTickCount: Count;
}) {
MeshRendererComponent.__cameraComponent = renderPass.cameraComponent;
if (MeshRendererComponent.__cameraComponent == null) {
MeshRendererComponent.__cameraComponent = MeshRendererComponent.__componentRepository.getComponent(
CameraComponent,
CameraComponent.main
) as CameraComponent;
}
let viewMatrix = MeshRendererComponent.__tmp_identityMatrix;
let projectionMatrix = MeshRendererComponent.__tmp_identityMatrix;
if (MeshRendererComponent.__cameraComponent) {
viewMatrix = MeshRendererComponent.__cameraComponent.viewMatrix;
projectionMatrix =
MeshRendererComponent.__cameraComponent.projectionMatrix;
}
const meshComponentSids = Component.__componentsOfProcessStages.get(
processStage
)!;
const meshComponents = MeshRendererComponent.__componentRepository._getComponents(
MeshComponent
) as MeshComponent[];
MeshRendererComponent.__webglRenderingStrategy!.common_$render(
meshComponentSids,
meshComponents,
viewMatrix,
projectionMatrix,
renderPass,
renderPassTickCount
);
}
$render({
i,
renderPass,
renderPassTickCount,
}: {
i: Index;
renderPass: RenderPass;
renderPassTickCount: Count;
}) {
if (MeshRendererComponent.__webglRenderingStrategy!.$render == null) {
return;
}
const entity = this.__entityRepository.getEntity(this.__entityUid);
MeshRendererComponent.__webglRenderingStrategy!.$render!(
i,
this.__meshComponent!,
this.__sceneGraphComponent!.worldMatrixInner,
this.__sceneGraphComponent!.normalMatrixInner,
entity,
renderPass,
renderPassTickCount,
this.diffuseCubeMap,
this.specularCubeMap
);
if (this.__meshComponent!.mesh) {
if (this.__meshComponent!.mesh.weights.length > 0) {
this.moveStageTo(ProcessStage.PreRender);
}
} else {
MeshComponent.alertNoMeshSet(this.__meshComponent!);
}
}
}
ComponentRepository.registerComponentClass(MeshRendererComponent); | the_stack |
import {
BlockDeviceMappingProperty,
BlockDeviceProperty,
PluginSettings,
SpotFleetInstanceProfile,
SpotFleetRequestConfiguration,
LaunchSpecification,
SpotFleetRequestProps,
SpotFleetSecurityGroupId,
SpotFleetTagSpecification,
} from './types';
/**
* Convert the configuration we received from ConfigureSpotEventPlugin construct to the fromat expected by the Spot Event Plugin.
* boolean and number properties get converted into strings when passed to the Lambda,
* so we need to restore the original types.
*/
export function convertSpotFleetRequestConfiguration(spotFleetRequestConfigs: SpotFleetRequestConfiguration): SpotFleetRequestConfiguration {
const convertedSpotFleetRequestConfigs: SpotFleetRequestConfiguration = {};
for (const [group_name, sfrConfigs] of Object.entries(spotFleetRequestConfigs)) {
const convertedSpotFleetRequestProps: SpotFleetRequestProps = {
AllocationStrategy: validateString(sfrConfigs.AllocationStrategy, `${group_name}.AllocationStrategy`),
IamFleetRole: validateString(sfrConfigs.IamFleetRole, `${group_name}.IamFleetRole`),
LaunchSpecifications: convertLaunchSpecifications(sfrConfigs.LaunchSpecifications, `${group_name}.LaunchSpecifications`),
ReplaceUnhealthyInstances: convertToBoolean(sfrConfigs.ReplaceUnhealthyInstances, `${group_name}.ReplaceUnhealthyInstances`),
TargetCapacity: convertToInt(sfrConfigs.TargetCapacity, `${group_name}.TargetCapacity`),
TerminateInstancesWithExpiration: convertToBoolean(sfrConfigs.TerminateInstancesWithExpiration, `${group_name}.TerminateInstancesWithExpiration`),
Type: validateString(sfrConfigs.Type, `${group_name}.Type`),
ValidUntil: validateStringOptional(sfrConfigs.ValidUntil, `${group_name}.ValidUntil`),
TagSpecifications: convertTagSpecifications(sfrConfigs.TagSpecifications, `${group_name}.TagSpecifications`),
};
convertedSpotFleetRequestConfigs[group_name] = convertedSpotFleetRequestProps;
}
return convertedSpotFleetRequestConfigs;
}
/**
* Convert the configuration we received from ConfigureSpotEventPlugin construct to the fromat expected by the Spot Event Plugin.
* boolean and number properties get converted into strings when passed to the Lambda,
* so we need to restore the original types.
*/
export function convertSpotEventPluginSettings(pluginOptions: PluginSettings): PluginSettings {
return {
AWSInstanceStatus: validateString(pluginOptions.AWSInstanceStatus, 'AWSInstanceStatus'),
DeleteInterruptedSlaves: convertToBoolean(pluginOptions.DeleteInterruptedSlaves, 'DeleteInterruptedSlaves'),
DeleteTerminatedSlaves: convertToBoolean(pluginOptions.DeleteTerminatedSlaves, 'DeleteTerminatedSlaves'),
IdleShutdown: convertToInt(pluginOptions.IdleShutdown, 'IdleShutdown'),
Logging: validateString(pluginOptions.Logging, 'Logging'),
PreJobTaskMode: validateString(pluginOptions.PreJobTaskMode, 'PreJobTaskMode'),
Region: validateString(pluginOptions.Region, 'Region'),
ResourceTracker: convertToBoolean(pluginOptions.ResourceTracker, 'ResourceTracker'),
StaggerInstances: convertToInt(pluginOptions.StaggerInstances, 'StaggerInstances'),
State: validateString(pluginOptions.State, 'State'),
StrictHardCap: convertToBoolean(pluginOptions.StrictHardCap, 'StrictHardCap'),
};
}
export function validateArray(input: any, propertyName: string): void {
if (!input || !Array.isArray(input) || input.length === 0) {
throw new Error(`${propertyName} should be an array with at least one element.`);
}
}
export function validateProperty(isValid: (input: any) => boolean, property: any, propertyName: string): void {
if (!isValid(property)) {
throw new Error(`${propertyName} type is not valid.`);
}
}
export function isValidSecurityGroup(securityGroup: SpotFleetSecurityGroupId): boolean {
if (!securityGroup || typeof(securityGroup) !== 'object' || Array.isArray(securityGroup)) { return false; }
// We also verify groupId with validateString later
if (!securityGroup.GroupId || typeof(securityGroup.GroupId) !== 'string') { return false; }
return true;
}
export function convertSecurityGroups(securityGroups: SpotFleetSecurityGroupId[], propertyName: string): SpotFleetSecurityGroupId[] {
validateArray(securityGroups, propertyName);
const convertedSecurityGroups: SpotFleetSecurityGroupId[] = securityGroups.map(securityGroup => {
validateProperty(isValidSecurityGroup, securityGroup, propertyName);
const convertedSecurityGroup: SpotFleetSecurityGroupId = {
GroupId: validateString(securityGroup.GroupId, `${propertyName}.GroupId`),
};
return convertedSecurityGroup;
});
return convertedSecurityGroups;
}
export function isValidTagSpecification(tagSpecification: SpotFleetTagSpecification): boolean {
if (!tagSpecification || typeof(tagSpecification) !== 'object' || Array.isArray(tagSpecification)) { return false; }
// We also verify resourceType with validateString later
if (!tagSpecification.ResourceType || typeof(tagSpecification.ResourceType) !== 'string') { return false; }
if (!tagSpecification.Tags || !Array.isArray(tagSpecification.Tags)) { return false; }
for (let element of tagSpecification.Tags) {
if (!element || typeof(element) !== 'object') { return false; };
if (!element.Key || typeof(element.Key) !== 'string') { return false; }
if (!element.Value || typeof(element.Value) !== 'string') { return false; }
}
return true;
}
export function convertTagSpecifications(tagSpecifications: SpotFleetTagSpecification[], propertyName: string): SpotFleetTagSpecification[] {
validateArray(tagSpecifications, propertyName);
const convertedTagSpecifications: SpotFleetTagSpecification[] = tagSpecifications.map(tagSpecification => {
validateProperty(isValidTagSpecification, tagSpecification, propertyName);
const convertedTagSpecification: SpotFleetTagSpecification = {
ResourceType: validateString(tagSpecification.ResourceType, `${propertyName}.ResourceType`),
Tags: tagSpecification.Tags,
};
return convertedTagSpecification;
});
return convertedTagSpecifications;
}
export function isValidDeviceMapping(deviceMapping: BlockDeviceMappingProperty): boolean {
if (!deviceMapping || typeof(deviceMapping) !== 'object' || Array.isArray(deviceMapping)) { return false; }
// We validate the rest properties when convert them.
return true;
}
export function convertEbs(ebs: BlockDeviceProperty, propertyName: string): BlockDeviceProperty {
const convertedEbs: BlockDeviceProperty = {
DeleteOnTermination: convertToBooleanOptional(ebs.DeleteOnTermination, `${propertyName}.DeleteOnTermination`),
Encrypted: convertToBooleanOptional(ebs.Encrypted, `${propertyName}.Encrypted`),
Iops: convertToIntOptional(ebs.Iops, `${propertyName}.Iops`),
SnapshotId: validateStringOptional(ebs.SnapshotId, `${propertyName}.SnapshotId`),
VolumeSize: convertToIntOptional(ebs.VolumeSize, `${propertyName}.VolumeSize`),
VolumeType: validateStringOptional(ebs.VolumeType, `${propertyName}.VolumeType`),
};
return convertedEbs;
}
export function convertBlockDeviceMapping(blockDeviceMappings: BlockDeviceMappingProperty[], propertyName: string): BlockDeviceMappingProperty[] {
validateArray(blockDeviceMappings, propertyName);
const convertedBlockDeviceMappings: BlockDeviceMappingProperty[] = blockDeviceMappings.map(deviceMapping => {
validateProperty(isValidDeviceMapping, deviceMapping, propertyName);
const convertedDeviceMapping: BlockDeviceMappingProperty = {
DeviceName: validateString(deviceMapping.DeviceName, `${propertyName}.DeviceName`),
Ebs: deviceMapping.Ebs ? convertEbs(deviceMapping.Ebs, `${propertyName}.Ebs`) : undefined,
NoDevice: validateStringOptional(deviceMapping.NoDevice, `${propertyName}.NoDevice`),
VirtualName: validateStringOptional(deviceMapping.VirtualName, `${propertyName}.VirtualName`),
};
return convertedDeviceMapping;
});
return convertedBlockDeviceMappings;
}
export function isValidInstanceProfile(instanceProfile: SpotFleetInstanceProfile): boolean {
if (!instanceProfile || typeof(instanceProfile) !== 'object' || Array.isArray(instanceProfile)) { return false; }
// We also verify arn with validateString later
if (!instanceProfile.Arn || typeof(instanceProfile.Arn) !== 'string') { return false; }
return true;
}
export function convertInstanceProfile(instanceProfile: SpotFleetInstanceProfile, propertyName: string): SpotFleetInstanceProfile {
validateProperty(isValidInstanceProfile, instanceProfile, propertyName);
const convertedInstanceProfile: SpotFleetInstanceProfile = {
Arn: validateString(instanceProfile.Arn, `${propertyName}.Arn`),
};
return convertedInstanceProfile;
}
export function convertLaunchSpecifications(launchSpecifications: LaunchSpecification[], propertyName: string): LaunchSpecification[] {
validateArray(launchSpecifications, propertyName);
const convertedLaunchSpecifications: LaunchSpecification[] = [];
launchSpecifications.map(launchSpecification => {
const SecurityGroups = convertSecurityGroups(launchSpecification.SecurityGroups, `${propertyName}.SecurityGroups`);
const TagSpecifications = convertTagSpecifications(launchSpecification.TagSpecifications, `${propertyName}.TagSpecifications`);
const BlockDeviceMappings = launchSpecification.BlockDeviceMappings ?
convertBlockDeviceMapping(launchSpecification.BlockDeviceMappings, `${propertyName}.BlockDeviceMappings`) : undefined;
const convertedLaunchSpecification: LaunchSpecification = {
BlockDeviceMappings,
IamInstanceProfile: convertInstanceProfile(launchSpecification.IamInstanceProfile, `${propertyName}.IamInstanceProfile`),
ImageId: validateString(launchSpecification.ImageId, `${propertyName}.ImageId`),
KeyName: validateStringOptional(launchSpecification.KeyName, `${propertyName}.KeyName`),
SecurityGroups,
SubnetId: validateStringOptional(launchSpecification.SubnetId, `${propertyName}.SubnetId`),
TagSpecifications,
UserData: validateString(launchSpecification.UserData, `${propertyName}.UserData`),
InstanceType: validateString(launchSpecification.InstanceType, `${propertyName}.InstanceType`),
};
convertedLaunchSpecifications.push(convertedLaunchSpecification);
});
return convertedLaunchSpecifications;
}
export function convertToInt(value: any, propertyName: string): number {
if (typeof(value) === 'number') {
if (Number.isInteger(value)) {
return value;
}
}
if (typeof(value) === 'string') {
const result = Number.parseFloat(value);
if (Number.isInteger(result)) {
return result;
}
}
throw new Error(`The value of ${propertyName} should be an integer. Received: ${value} of type ${typeof(value)}`);
}
export function convertToIntOptional(value: any, propertyName: string): number | undefined {
if (value === undefined) {
return undefined;
}
return convertToInt(value, propertyName);
}
export function convertToBoolean(value: any, propertyName: string): boolean {
if (typeof(value) === 'boolean') {
return value;
}
if (typeof(value) === 'string') {
if (value === 'true') { return true; }
if (value === 'false') { return false; }
}
throw new Error(`The value of ${propertyName} should be a boolean. Received: ${value} of type ${typeof(value)}`);
}
export function convertToBooleanOptional(value: any, propertyName: string): boolean | undefined {
if (value === undefined) {
return undefined;
}
return convertToBoolean(value, propertyName);
}
export function validateString(value: any, propertyName: string): string {
if (typeof(value) === 'string') {
return value;
}
throw new Error(`The value of ${propertyName} should be a string. Received: ${value} of type ${typeof(value)}`);
}
export function validateStringOptional(value: any, propertyName: string): string | undefined {
if (value === undefined) {
return undefined;
}
return validateString(value, propertyName);
} | the_stack |
import { CfnResource, IConstruct } from '@aws-cdk/core';
import { NagMessageLevel, NagPack, NagPackProps } from '../nag-pack';
import {
APIGWAssociatedWithWAF,
APIGWCacheEnabledAndEncrypted,
APIGWExecutionLoggingEnabled,
APIGWSSLEnabled,
} from '../rules/apigw';
import {
AutoScalingGroupELBHealthCheckRequired,
AutoScalingLaunchConfigPublicIpDisabled,
} from '../rules/autoscaling';
import {
CloudTrailCloudWatchLogsEnabled,
CloudTrailEncryptionEnabled,
CloudTrailLogFileValidationEnabled,
} from '../rules/cloudtrail';
import {
CloudWatchLogGroupEncrypted,
CloudWatchLogGroupRetentionPeriod,
} from '../rules/cloudwatch';
import {
CodeBuildProjectEnvVarAwsCred,
CodeBuildProjectSourceRepoUrl,
} from '../rules/codebuild';
import { DMSReplicationNotPublic } from '../rules/dms';
import {
EC2InstanceNoPublicIp,
EC2InstanceProfileAttached,
EC2InstancesInVPC,
EC2RestrictedCommonPorts,
EC2RestrictedSSH,
} from '../rules/ec2';
import { ECSTaskDefinitionUserForHostMode } from '../rules/ecs';
import { EFSEncrypted } from '../rules/efs';
import {
ALBHttpDropInvalidHeaderEnabled,
ALBHttpToHttpsRedirection,
ALBWAFEnabled,
ELBACMCertificateRequired,
ELBLoggingEnabled,
ELBTlsHttpsListenersOnly,
ELBv2ACMCertificateRequired,
} from '../rules/elb';
import { EMRKerberosEnabled } from '../rules/emr';
import {
IAMGroupHasUsers,
IAMNoInlinePolicy,
IAMPolicyNoStatementsWithAdminAccess,
IAMPolicyNoStatementsWithFullAccess,
IAMUserGroupMembership,
IAMUserNoPolicies,
} from '../rules/iam';
import { KMSBackingKeyRotationEnabled } from '../rules/kms';
import { LambdaInsideVPC } from '../rules/lambda';
import {
OpenSearchEncryptedAtRest,
OpenSearchErrorLogsToCloudWatch,
OpenSearchInVPCOnly,
OpenSearchNodeToNodeEncryption,
} from '../rules/opensearch';
import {
RDSAutomaticMinorVersionUpgradeEnabled,
RDSInstancePublicAccess,
RDSLoggingEnabled,
RDSStorageEncrypted,
} from '../rules/rds';
import {
RedshiftClusterConfiguration,
RedshiftClusterMaintenanceSettings,
RedshiftClusterPublicAccess,
RedshiftEnhancedVPCRoutingEnabled,
RedshiftRequireTlsSSL,
} from '../rules/redshift';
import {
S3BucketLevelPublicAccessProhibited,
S3BucketLoggingEnabled,
S3BucketPublicReadProhibited,
S3BucketPublicWriteProhibited,
S3BucketReplicationEnabled,
S3BucketServerSideEncryptionEnabled,
S3BucketSSLRequestsOnly,
S3BucketVersioningEnabled,
S3DefaultEncryptionKMS,
} from '../rules/s3';
import {
SageMakerEndpointConfigurationKMSKeyConfigured,
SageMakerNotebookInstanceKMSKeyConfigured,
SageMakerNotebookNoDirectInternetAccess,
} from '../rules/sagemaker';
import { SecretsManagerUsingKMSKey } from '../rules/secretsmanager';
import { SNSEncryptedKMS } from '../rules/sns';
import {
VPCDefaultSecurityGroupClosed,
VPCFlowLogsEnabled,
VPCNoUnrestrictedRouteToIGW,
VPCSubnetAutoAssignPublicIpDisabled,
} from '../rules/vpc';
import { WAFv2LoggingEnabled } from '../rules/waf';
/**
* Check for PCI DSS 3.2.1 compliance.
* Based on the PCI DSS 3.2.1 AWS operational best practices: https://docs.aws.amazon.com/config/latest/developerguide/operational-best-practices-for-pci-dss.html
*/
export class PCIDSS321Checks extends NagPack {
constructor(props?: NagPackProps) {
super(props);
this.packName = 'PCI.DSS.321';
}
public visit(node: IConstruct): void {
if (node instanceof CfnResource) {
this.checkAPIGW(node);
this.checkAutoScaling(node);
this.checkCloudTrail(node);
this.checkCloudWatch(node);
this.checkCodeBuild(node);
this.checkDMS(node);
this.checkEC2(node);
this.checkECS(node);
this.checkEFS(node);
this.checkELB(node);
this.checkEMR(node);
this.checkIAM(node);
this.checkKMS(node);
this.checkLambda(node);
this.checkOpenSearch(node);
this.checkRDS(node);
this.checkRedshift(node);
this.checkS3(node);
this.checkSageMaker(node);
this.checkSecretsManager(node);
this.checkSNS(node);
this.checkVPC(node);
this.checkWAF(node);
}
}
/**
* Check API Gateway Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkAPIGW(node: CfnResource): void {
this.applyRule({
info: 'The REST API stage is not associated with AWS WAFv2 web ACL - (Control ID: 6.6).',
explanation:
'AWS WAF enables you to configure a set of rules (called a web access control list (web ACL)) that allow, block, or count web requests based on customizable web security rules and conditions that you define. Ensure your Amazon API Gateway stage is associated with a WAF Web ACL to protect it from malicious attacks.',
level: NagMessageLevel.ERROR,
rule: APIGWAssociatedWithWAF,
node: node,
});
this.applyRule({
info: 'The API Gateway stage does not have caching enabled and encrypted for all methods - (Control ID: 3.4).',
explanation:
"To help protect data at rest, ensure encryption is enabled for your API Gateway stage's cache. Because sensitive data can be captured for the API method, enable encryption at rest to help protect that data.",
level: NagMessageLevel.ERROR,
rule: APIGWCacheEnabledAndEncrypted,
node: node,
});
this.applyRule({
info: 'The API Gateway stage does not have execution logging enabled for all methods - (Control IDs: 10.1, 10.3.1, 10.3.2, 10.3.3, 10.3.4, 10.3.5, 10.3.6, 10.5.4).',
explanation:
'API Gateway logging displays detailed views of users who accessed the API and the way they accessed the API. This insight enables visibility of user activities.',
level: NagMessageLevel.ERROR,
rule: APIGWExecutionLoggingEnabled,
node: node,
});
this.applyRule({
info: 'The API Gateway REST API stage is not configured with SSL certificates - (Control IDs: 2.3, 4.1, 8.2.1).',
explanation:
'Ensure Amazon API Gateway REST API stages are configured with SSL certificates to allow backend systems to authenticate that requests originate from API Gateway.',
level: NagMessageLevel.ERROR,
rule: APIGWSSLEnabled,
node: node,
});
}
/**
* Check Auto Scaling Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkAutoScaling(node: CfnResource): void {
this.applyRule({
info: 'The Auto Scaling group (which is associated with a load balancer) does not utilize ELB healthchecks - (Control ID: 2.2).',
explanation:
'The Elastic Load Balancer (ELB) health checks for Amazon Elastic Compute Cloud (Amazon EC2) Auto Scaling groups support maintenance of adequate capacity and availability. The load balancer periodically sends pings, attempts connections, or sends requests to test Amazon EC2 instances health in an auto-scaling group. If an instance is not reporting back, traffic is sent to a new Amazon EC2 instance.',
level: NagMessageLevel.ERROR,
rule: AutoScalingGroupELBHealthCheckRequired,
node: node,
});
this.applyRule({
info: 'The Auto Scaling launch configuration does not have public IP addresses disabled - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 1.3.4, 1.3.6, 2.2.2).',
explanation:
'If you configure your Network Interfaces with a public IP address, then the associated resources to those Network Interfaces are reachable from the internet. EC2 resources should not be publicly accessible, as this may allow unintended access to your applications or servers.',
level: NagMessageLevel.ERROR,
rule: AutoScalingLaunchConfigPublicIpDisabled,
node: node,
});
}
/**
* Check CloudTrail Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkCloudTrail(node: CfnResource): void {
this.applyRule({
info: 'The trail does not have CloudWatch logs enabled - (Control IDs: 2.2, 10.1, 10.2.1, 10.2.2, 10.2.3, 10.2.5, 10.3.1, 10.3.2, 10.3.3, 10.3.4, 10.3.5, 10.3.6, 10.5.3, 10.5.4).',
explanation:
'Use Amazon CloudWatch to centrally collect and manage log event activity. Inclusion of AWS CloudTrail data provides details of API call activity within your AWS account.',
level: NagMessageLevel.ERROR,
rule: CloudTrailCloudWatchLogsEnabled,
node: node,
});
this.applyRule({
info: 'The trail does not have encryption enabled - (Control IDs: 2.2, 3.4, 10.5).',
explanation:
'Because sensitive data may exist and to help protect data at rest, ensure encryption is enabled for your AWS CloudTrail trails.',
level: NagMessageLevel.ERROR,
rule: CloudTrailEncryptionEnabled,
node: node,
});
this.applyRule({
info: 'The trail does not have log file validation enabled - (Control IDs: 2.2, 10.5.2, 10.5, 10.5.5, 11.5).',
explanation:
'Utilize AWS CloudTrail log file validation to check the integrity of CloudTrail logs. Log file validation helps determine if a log file was modified or deleted or unchanged after CloudTrail delivered it. This feature is built using industry standard algorithms: SHA-256 for hashing and SHA-256 with RSA for digital signing. This makes it computationally infeasible to modify, delete or forge CloudTrail log files without detection.',
level: NagMessageLevel.ERROR,
rule: CloudTrailLogFileValidationEnabled,
node: node,
});
}
/**
* Check CloudWatch Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkCloudWatch(node: CfnResource): void {
this.applyRule({
info: 'The CloudWatch Log Group is not encrypted with an AWS KMS key - (Control ID: 3.4).',
explanation:
'To help protect sensitive data at rest, ensure encryption is enabled for your Amazon CloudWatch Log Groups.',
level: NagMessageLevel.ERROR,
rule: CloudWatchLogGroupEncrypted,
node: node,
});
this.applyRule({
info: 'The CloudWatch Log Group does not have an explicit retention period configured - (Control IDs: 3.1, 10.7).',
explanation:
'Ensure a minimum duration of event log data is retained for your log groups to help with troubleshooting and forensics investigations. The lack of available past event log data makes it difficult to reconstruct and identify potentially malicious events.',
level: NagMessageLevel.ERROR,
rule: CloudWatchLogGroupRetentionPeriod,
node: node,
});
}
/**
* Check CodeBuild Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkCodeBuild(node: CfnResource): void {
this.applyRule({
info: 'The CodeBuild environment stores sensitive credentials (such as AWS_ACCESS_KEY_ID and/or AWS_SECRET_ACCESS_KEY) as plaintext environment variables - (Control ID: 8.2.1).',
explanation:
'Do not store these variables in clear text. Storing these variables in clear text leads to unintended data exposure and unauthorized access.',
level: NagMessageLevel.ERROR,
rule: CodeBuildProjectEnvVarAwsCred,
node: node,
});
this.applyRule({
info: 'The CodeBuild project which utilizes either a GitHub or BitBucket source repository does not utilize OAUTH - (Control ID: 8.2.1).',
explanation:
'OAUTH is the most secure method of authenticating your CodeBuild application. Use OAuth instead of personal access tokens or a user name and password to grant authorization for accessing GitHub or Bitbucket repositories.',
level: NagMessageLevel.ERROR,
rule: CodeBuildProjectSourceRepoUrl,
node: node,
});
}
/**
* Check DMS Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkDMS(node: CfnResource) {
this.applyRule({
info: 'The DMS replication instance is public - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 1.3.4, 1.3.6, 2.2.2).',
explanation:
'DMS replication instances can contain sensitive information and access control is required for such accounts.',
level: NagMessageLevel.ERROR,
rule: DMSReplicationNotPublic,
node: node,
});
}
/**
* Check EC2 Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkEC2(node: CfnResource): void {
this.applyRule({
info: 'The EC2 instance is associated with a public IP address - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 1.3.4, 1.3.6, 2.2.2).',
explanation:
'Manage access to the AWS Cloud by ensuring Amazon Elastic Compute Cloud (Amazon EC2) instances cannot be publicly accessed. Amazon EC2 instances can contain sensitive information and access control is required for such accounts.',
level: NagMessageLevel.ERROR,
rule: EC2InstanceNoPublicIp,
node: node,
});
this.applyRule({
info: 'The EC2 instance does not have an instance profile attached - (Control IDs: 2.2, 7.1.1, 7.2.1).',
explanation:
'EC2 instance profiles pass an IAM role to an EC2 instance. Attaching an instance profile to your instances can assist with least privilege and permissions management.',
level: NagMessageLevel.ERROR,
rule: EC2InstanceProfileAttached,
node: node,
});
this.applyRule({
info: 'The EC2 instance is not within a VPC - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 1.3.4, 1.3.6, 2.2.2).',
explanation:
'Deploy Amazon Elastic Compute Cloud (Amazon EC2) instances within an Amazon Virtual Private Cloud (Amazon VPC) to enable secure communication between an instance and other services within the amazon VPC, without requiring an internet gateway, NAT device, or VPN connection. All traffic remains securely within the AWS Cloud. Because of their logical isolation, domains that reside within anAmazon VPC have an extra layer of security when compared to domains that use public endpoints. Assign Amazon EC2 instances to an Amazon VPC to properly manage access.',
level: NagMessageLevel.ERROR,
rule: EC2InstancesInVPC,
node: node,
});
this.applyRule({
info: 'The EC2 instance allows unrestricted inbound IPv4 TCP traffic on one or more common ports (by default these ports include 20, 21, 3389, 3309, 3306, 4333) - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 2.2, 2.2.2).',
explanation:
'Not restricting access to ports to trusted sources can lead to attacks against the availability, integrity and confidentiality of systems. By default, common ports which should be restricted include port numbers 20, 21, 3389, 3306, and 4333.',
level: NagMessageLevel.ERROR,
rule: EC2RestrictedCommonPorts,
node: node,
});
this.applyRule({
info: 'The Security Group allows unrestricted SSH access - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 2.2, 2.2.2).',
explanation:
'Not allowing ingress (or remote) traffic from 0.0.0.0/0 or ::/0 to port 22 on your resources helps to restrict remote access.',
level: NagMessageLevel.ERROR,
rule: EC2RestrictedSSH,
node: node,
});
}
/**
* Check ECS Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkECS(node: CfnResource): void {
this.applyRule({
info: "The ECS task definition is configured for host networking and has at least one container with definitions with 'privileged' set to false or empty or 'user' set to root or empty - (Control ID: 7.2.1).",
explanation:
'If a task definition has elevated privileges it is because you have specifically opted-in to those configurations. This rule checks for unexpected privilege escalation when a task definition has host networking enabled but the customer has not opted-in to elevated privileges.',
level: NagMessageLevel.ERROR,
rule: ECSTaskDefinitionUserForHostMode,
node: node,
});
}
/**
* Check EFS Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkEFS(node: CfnResource) {
this.applyRule({
info: 'The EFS does not have encryption at rest enabled - (Control IDs: 3.4, 8.2.1).',
explanation:
'Because sensitive data can exist and to help protect data at rest, ensure encryption is enabled for your Amazon Elastic File System (EFS).',
level: NagMessageLevel.ERROR,
rule: EFSEncrypted,
node: node,
});
}
/**
* Check Elastic Load Balancer Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkELB(node: CfnResource): void {
this.applyRule({
info: 'The ALB does not have invalid HTTP header dropping enabled - (Control IDs: 4.1, 8.2.1).',
explanation:
'Ensure that your Application Load Balancers (ALB) are configured to drop http headers. Because sensitive data can exist, enable encryption in transit to help protect that data.',
level: NagMessageLevel.ERROR,
rule: ALBHttpDropInvalidHeaderEnabled,
node: node,
});
this.applyRule({
info: "The ALB's HTTP listeners are not configured to redirect to HTTPS - (Control IDs: 2.3, 4.1, 8.2.1).",
explanation:
'To help protect data in transit, ensure that your Application Load Balancer automatically redirects unencrypted HTTP requests to HTTPS. Because sensitive data can exist, enable encryption in transit to help protect that data.',
level: NagMessageLevel.ERROR,
rule: ALBHttpToHttpsRedirection,
node: node,
});
this.applyRule({
info: 'The ALB is not associated with AWS WAFv2 web ACL - (Control ID: 6.6).',
explanation:
'A WAF helps to protect your web applications or APIs against common web exploits. These web exploits may affect availability, compromise security, or consume excessive resources within your environment.',
level: NagMessageLevel.ERROR,
rule: ALBWAFEnabled,
node: node,
});
this.applyRule({
info: 'The CLB does not utilize an SSL certificate provided by ACM (Amazon Certificate Manager) - (Control IDs: 4.1, 8.2.1).',
explanation:
'Because sensitive data can exist and to help protect data at transit, ensure encryption is enabled for your Elastic Load Balancing. Use AWS Certificate Manager to manage, provision and deploy public and private SSL/TLS certificates with AWS services and internal resources.',
level: NagMessageLevel.ERROR,
rule: ELBACMCertificateRequired,
node: node,
});
this.applyRule({
info: 'The ELB does not have logging enabled - (Control IDs: 10.1, 10.3.1, 10.3.2, 10.3.3, 10.3.4, 10.3.5, 10.3.6, 10.5.4).',
explanation:
"Elastic Load Balancing activity is a central point of communication within an environment. Ensure ELB logging is enabled. The collected data provides detailed information about requests sent to The ELB. Each log contains information such as the time the request was received, the client's IP address, latencies, request paths, and server responses.",
level: NagMessageLevel.ERROR,
rule: ELBLoggingEnabled,
node: node,
});
this.applyRule({
info: 'The CLB does not restrict its listeners to only the SSL and HTTPS protocols - (Control IDs: 2.3, 4.1, 8.2.1).',
explanation:
'Ensure that your Classic Load Balancers (CLBs) are configured with SSL or HTTPS listeners. Because sensitive data can exist, enable encryption in transit to help protect that data.',
level: NagMessageLevel.ERROR,
rule: ELBTlsHttpsListenersOnly,
node: node,
});
this.applyRule({
info: 'The ALB, NLB, or GLB listener does not utilize an SSL certificate provided by ACM (Amazon Certificate Manager) - (Control ID: 4.1).',
explanation:
'Because sensitive data can exist and to help protect data at transit, ensure encryption is enabled for your Elastic Load Balancing. Use AWS Certificate Manager to manage, provision and deploy public and private SSL/TLS certificates with AWS services and internal resources.',
level: NagMessageLevel.ERROR,
rule: ELBv2ACMCertificateRequired,
node: node,
});
}
/**
* Check EMR Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkEMR(node: CfnResource) {
this.applyRule({
info: 'The ALB, NLB, or GLB listener does not utilize an SSL certificate provided by ACM (Amazon Certificate Manager) - (Control ID: 7.2.1).',
explanation:
'Because sensitive data can exist and to help protect data at transit, ensure encryption is enabled for your Elastic Load Balancing. Use AWS Certificate Manager to manage, provision and deploy public and private SSL/TLS certificates with AWS services and internal resources.',
level: NagMessageLevel.ERROR,
rule: EMRKerberosEnabled,
node: node,
});
}
/**
* Check IAM Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkIAM(node: CfnResource): void {
this.applyRule({
info: 'The IAM Group does not have at least one IAM User - (Control IDs: 7.1.2, 7.1.3, 7.2.1, 7.2.2).',
explanation:
'AWS Identity and Access Management (IAM) can help you incorporate the principles of least privilege and separation of duties with access permissions and authorizations, by ensuring that IAM groups have at least one IAM user. Placing IAM users in groups based on their associated permissions or job function is one way to incorporate least privilege.',
level: NagMessageLevel.ERROR,
rule: IAMGroupHasUsers,
node: node,
});
this.applyRule({
info: 'The IAM Group, User, or Role contains an inline policy - (Control IDs: 2.2, 7.1.2, 7.1.3, 7.2.1, 7.2.2).',
explanation:
'AWS recommends to use managed policies instead of inline policies. The managed policies allow reusability, versioning and rolling back, and delegating permissions management.',
level: NagMessageLevel.ERROR,
rule: IAMNoInlinePolicy,
node: node,
});
this.applyRule({
info: 'The IAM policy grants admin access - (Control IDs: 2.2, 7.1.2, 7.1.3, 7.2.1, 7.2.2).',
explanation:
'AWS Identity and Access Management (IAM) can help you incorporate the principles of least privilege and separation of duties with access permissions and authorizations, by ensuring that IAM groups have at least one IAM user. Placing IAM users in groups based on their associated permissions or job function is one way to incorporate least privilege.',
level: NagMessageLevel.ERROR,
rule: IAMPolicyNoStatementsWithAdminAccess,
node: node,
});
this.applyRule({
info: 'The IAM policy grants full access - (Control IDs: 7.1.2, 7.1.3, 7.2.1, 7.2.2).',
explanation:
'Ensure IAM Actions are restricted to only those actions that are needed. Allowing users to have more privileges than needed to complete a task may violate the principle of least privilege and separation of duties.',
level: NagMessageLevel.ERROR,
rule: IAMPolicyNoStatementsWithFullAccess,
node: node,
});
this.applyRule({
info: 'The IAM user does not belong to any group(s) - (Control IDs: 2.2, 7.1.2, 7.1.3, 7.2.1, 7.2.2).',
explanation:
'AWS Identity and Access Management (IAM) can help you restrict access permissions and authorizations by ensuring IAM users are members of at least one group. Allowing users more privileges than needed to complete a task may violate the principle of least privilege and separation of duties.',
level: NagMessageLevel.ERROR,
rule: IAMUserGroupMembership,
node: node,
});
this.applyRule({
info: 'The IAM policy is attached at the user level - (Control IDs: 2.2, 7.1.2, 7.1.3, 7.2.1, 7.2.2).',
explanation:
'Assigning privileges at the group or the role level helps to reduce opportunity for an identity to receive or retain excessive privileges.',
level: NagMessageLevel.ERROR,
rule: IAMUserNoPolicies,
node: node,
});
}
/**
* Check KMS Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkKMS(node: CfnResource): void {
this.applyRule({
info: 'The KMS Symmetric key does not have automatic key rotation enabled - (Control IDs: 2.2, 3.5, 3.6, 3.6.4).',
explanation:
'Enable key rotation to ensure that keys are rotated once they have reached the end of their crypto period.',
level: NagMessageLevel.ERROR,
rule: KMSBackingKeyRotationEnabled,
node: node,
});
}
/**
* Check Lambda Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkLambda(node: CfnResource) {
this.applyRule({
info: 'The Lambda function is not VPC enabled - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 1.3.4, 2.2.2).',
explanation:
'Because of their logical isolation, domains that reside within an Amazon VPC have an extra layer of security when compared to domains that use public endpoints.',
level: NagMessageLevel.ERROR,
rule: LambdaInsideVPC,
node: node,
});
}
/**
* Check OpenSearch Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkOpenSearch(node: CfnResource) {
this.applyRule({
info: 'The OpenSearch Service domain does not have encryption at rest enabled - (Control IDs: 3.4, 8.2.1).',
explanation:
'Because sensitive data can exist and to help protect data at rest, ensure encryption is enabled for your Amazon OpenSearch Service (OpenSearch Service) domains.',
level: NagMessageLevel.ERROR,
rule: OpenSearchEncryptedAtRest,
node: node,
});
this.applyRule({
info: 'The OpenSearch Service domain is not running within a VPC - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 1.3.4, 1.3.6, 2.2.2).',
explanation:
'VPCs help secure your AWS resources and provide an extra layer of protection.',
level: NagMessageLevel.ERROR,
rule: OpenSearchInVPCOnly,
node: node,
});
this.applyRule({
info: 'The OpenSearch Service domain does not stream error logs (ES_APPLICATION_LOGS) to CloudWatch Logs - (Control IDs: 10.1, 10.2.1, 10.2.2, 10.2.3, 10.2.4, 10.2.5, 10.3.1, 10.3.2, 10.3.3, 10.3.4, 10.3.5, 10.3.6).',
explanation:
'Ensure Amazon OpenSearch Service domains have error logs enabled and streamed to Amazon CloudWatch Logs for retention and response. Domain error logs can assist with security and access audits, and can help to diagnose availability issues.',
level: NagMessageLevel.ERROR,
rule: OpenSearchErrorLogsToCloudWatch,
node: node,
});
this.applyRule({
info: 'The OpenSearch Service domain does not have node-to-node encryption enabled - (Control ID: 4.1).',
explanation:
'Because sensitive data can exist, enable encryption in transit to help protect that data within your Amazon OpenSearch Service (OpenSearch Service) domains.',
level: NagMessageLevel.ERROR,
rule: OpenSearchNodeToNodeEncryption,
node: node,
});
}
/**
* Check RDS Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkRDS(node: CfnResource): void {
this.applyRule({
info: "The route table may contain one or more unrestricted route(s) to an IGW ('0.0.0.0/0' or '::/0') - (Control ID: 6.2).",
explanation:
'Ensure Amazon EC2 route tables do not have unrestricted routes to an internet gateway. Removing or limiting the access to the internet for workloads within Amazon VPCs can reduce unintended access within your environment.',
level: NagMessageLevel.ERROR,
rule: RDSAutomaticMinorVersionUpgradeEnabled,
node: node,
});
this.applyRule({
info: 'The RDS DB Instance allows public access - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 1.3.4, 1.3.6, 2.2.2).',
explanation:
'Amazon RDS database instances can contain sensitive information, and principles and access control is required for such accounts.',
level: NagMessageLevel.ERROR,
rule: RDSInstancePublicAccess,
node: node,
});
this.applyRule({
info: 'The RDS DB Instance does not have all CloudWatch log types exported - (Control IDs: 10.1, 10.2.1, 10.2.2, 10.2.3, 10.2.4, 10.2.5, 10.3.1, 10.3.2, 10.3.3, 10.3.4, 10.3.5, 10.3.6).',
explanation:
'To help with logging and monitoring within your environment, ensure Amazon Relational Database Service (Amazon RDS) logging is enabled. With Amazon RDS logging, you can capture events such as connections, disconnections, queries, or tables queried.',
level: NagMessageLevel.ERROR,
rule: RDSLoggingEnabled,
node: node,
});
this.applyRule({
info: 'The RDS DB Instance or Aurora Cluster does not have storage encrypted - (Control IDs: 3.4, 8.2.1).',
explanation:
'Because sensitive data can exist at rest in Amazon RDS instances, enable encryption at rest to help protect that data.',
level: NagMessageLevel.ERROR,
rule: RDSStorageEncrypted,
node: node,
});
}
/**
* Check Redshift Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkRedshift(node: CfnResource): void {
this.applyRule({
info: 'The Redshift cluster does not have encryption or audit logging enabled - (Control IDs: 3.4, 8.2.1, 10.1, 10.2.1, 10.2.2, 10.2.3, 10.2.4, 10.2.5, 10.3.1, 10.3.2, 10.3.3, 10.3.4, 10.3.5, 10.3.6).',
explanation:
'To protect data at rest, ensure that encryption is enabled for your Amazon Redshift clusters. You must also ensure that required configurations are deployed on Amazon Redshift clusters. The audit logging should be enabled to provide information about connections and user activities in the database.',
level: NagMessageLevel.ERROR,
rule: RedshiftClusterConfiguration,
node: node,
});
this.applyRule({
info: 'The Redshift cluster does not have version upgrades enabled, automated snapshot retention periods enabled, and an explicit maintenance window configured - (Control ID: 6.2).',
explanation:
'Ensure that Amazon Redshift clusters have the preferred settings for your organization. Specifically, that they have preferred maintenance windows and automated snapshot retention periods for the database. ',
level: NagMessageLevel.ERROR,
rule: RedshiftClusterMaintenanceSettings,
node: node,
});
this.applyRule({
info: 'The Redshift cluster allows public access - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 1.3.4, 1.3.6, 2.2.2).',
explanation:
'Amazon Redshift clusters can contain sensitive information and principles and access control is required for such accounts.',
level: NagMessageLevel.ERROR,
rule: RedshiftClusterPublicAccess,
node: node,
});
this.applyRule({
info: 'The Redshift cluster does not have enhanced VPC routing enabled - (Control IDs: 1.2, 1.3, 1.3.1, 1.3.2).',
explanation:
'Enhanced VPC routing forces all COPY and UNLOAD traffic between the cluster and data repositories to go through your Amazon VPC. You can then use VPC features such as security groups and network access control lists to secure network traffic. You can also use VPC flow logs to monitor network traffic.',
level: NagMessageLevel.ERROR,
rule: RedshiftEnhancedVPCRoutingEnabled,
node: node,
});
this.applyRule({
info: 'The Redshift cluster does not require TLS/SSL encryption - (Control IDs: 2.3, 4.1).',
explanation:
'Ensure that your Amazon Redshift clusters require TLS/SSL encryption to connect to SQL clients. Because sensitive data can exist, enable encryption in transit to help protect that data.',
level: NagMessageLevel.ERROR,
rule: RedshiftRequireTlsSSL,
node: node,
});
}
/**
* Check Amazon S3 Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkS3(node: CfnResource): void {
this.applyRule({
info: 'The S3 bucket does not prohibit public access through bucket level settings - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 1.3.4, 1.3.6, 2.2.2).',
explanation:
'Keep sensitive data safe from unauthorized remote users by preventing public access at the bucket level.',
level: NagMessageLevel.ERROR,
rule: S3BucketLevelPublicAccessProhibited,
node: node,
});
this.applyRule({
info: 'The S3 Buckets does not have server access logs enabled - (Control IDs: 2.2, 10.1, 10.2.1, 10.2.2, 10.2.3, 10.2.4, 10.2.5, 10.2.7, 10.3.1, 10.3.2, 10.3.3, 10.3.4, 10.3.5, 10.3.6).',
explanation:
'Amazon Simple Storage Service (Amazon S3) server access logging provides a method to monitor the network for potential cybersecurity events. The events are monitored by capturing detailed records for the requests that are made to an Amazon S3 bucket. Each access log record provides details about a single access request. The details include the requester, bucket name, request time, request action, response status, and an error code, if relevant.',
level: NagMessageLevel.ERROR,
rule: S3BucketLoggingEnabled,
node: node,
});
this.applyRule({
info: 'The S3 Bucket does not prohibit public read access through its Block Public Access configurations and bucket ACLs - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 1.3.4, 1.3.6, 2.2, 2.2.2).',
explanation:
'The management of access should be consistent with the classification of the data.',
level: NagMessageLevel.ERROR,
rule: S3BucketPublicReadProhibited,
node: node,
});
this.applyRule({
info: 'The S3 Bucket does not prohibit public write access through its Block Public Access configurations and bucket ACLs - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 1.3.4, 1.3.6, 2.2, 2.2.2).',
explanation:
'The management of access should be consistent with the classification of the data.',
level: NagMessageLevel.ERROR,
rule: S3BucketPublicWriteProhibited,
node: node,
});
this.applyRule({
info: 'The S3 Bucket does not have replication enabled - (Control IDs: 2.2, 10.5.3).',
explanation:
'Amazon Simple Storage Service (Amazon S3) Cross-Region Replication (CRR) supports maintaining adequate capacity and availability. CRR enables automatic, asynchronous copying of objects across Amazon S3 buckets to help ensure that data availability is maintained.',
level: NagMessageLevel.ERROR,
rule: S3BucketReplicationEnabled,
node: node,
});
this.applyRule({
info: 'The S3 Bucket does not have default server-side encryption enabled - (Control IDs: 2.2, 3.4, 8.2.1, 10.5).',
explanation:
'Because sensitive data can exist at rest in Amazon S3 buckets, enable encryption to help protect that data.',
level: NagMessageLevel.ERROR,
rule: S3BucketServerSideEncryptionEnabled,
node: node,
});
this.applyRule({
info: 'The S3 Bucket does not require requests to use SSL - (Control IDs: 2.2, 4.1, 8.2.1).',
explanation:
'To help protect data in transit, ensure that your Amazon Simple Storage Service (Amazon S3) buckets require requests to use Secure Socket Layer (SSL). Because sensitive data can exist, enable encryption in transit to help protect that data.',
level: NagMessageLevel.ERROR,
rule: S3BucketSSLRequestsOnly,
node: node,
});
this.applyRule({
info: 'The S3 Bucket does not have versioning enabled - (Control ID: 10.5.3).',
explanation:
'Use versioning to preserve, retrieve, and restore every version of every object stored in your Amazon S3 bucket. Versioning helps you to easily recover from unintended user actions and application failures.',
level: NagMessageLevel.ERROR,
rule: S3BucketVersioningEnabled,
node: node,
});
this.applyRule({
info: 'The S3 Bucket is not encrypted with a KMS Key by default - (Control IDs: 3.4, 8.2.1, 10.5).',
explanation:
'Ensure that encryption is enabled for your Amazon Simple Storage Service (Amazon S3) buckets. Because sensitive data can exist at rest in an Amazon S3 bucket, enable encryption at rest to help protect that data.',
level: NagMessageLevel.ERROR,
rule: S3DefaultEncryptionKMS,
node: node,
});
}
/**
* Check SageMaker Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkSageMaker(node: CfnResource) {
this.applyRule({
info: 'The SageMaker resource endpoint is not encrypted with a KMS key - (Control IDs: 3.4, 8.2.1).',
explanation:
'Because sensitive data can exist at rest in SageMaker endpoint, enable encryption at rest to help protect that data.',
level: NagMessageLevel.ERROR,
rule: SageMakerEndpointConfigurationKMSKeyConfigured,
node: node,
});
this.applyRule({
info: 'The SageMaker notebook is not encrypted with a KMS key - (Control IDs: 3.4, 8.2.1).',
explanation:
'Because sensitive data can exist at rest in SageMaker notebook, enable encryption at rest to help protect that data.',
level: NagMessageLevel.ERROR,
rule: SageMakerNotebookInstanceKMSKeyConfigured,
node: node,
});
this.applyRule({
info: 'The SageMaker notebook does not disable direct internet access - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 1.3.4, 1.3.6, 2.2.2).',
explanation:
'By preventing direct internet access, you can keep sensitive data from being accessed by unauthorized users.',
level: NagMessageLevel.ERROR,
rule: SageMakerNotebookNoDirectInternetAccess,
node: node,
});
}
/**
* Check Secrets Manager Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkSecretsManager(node: CfnResource): void {
this.applyRule({
info: 'The secret is not encrypted with a KMS Customer managed key - (Control IDs: 3.4, 8.2.1).',
explanation:
'To help protect data at rest, ensure encryption with AWS Key Management Service (AWS KMS) is enabled for AWS Secrets Manager secrets. Because sensitive data can exist at rest in Secrets Manager secrets, enable encryption at rest to help protect that data.',
level: NagMessageLevel.ERROR,
rule: SecretsManagerUsingKMSKey,
node: node,
});
}
/**
* Check Amazon SNS Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkSNS(node: CfnResource): void {
this.applyRule({
info: 'The SNS topic does not have KMS encryption enabled - (Control ID: 8.2.1).',
explanation:
'To help protect data at rest, ensure that your Amazon Simple Notification Service (Amazon SNS) topics require encryption using AWS Key Management Service (AWS KMS) Because sensitive data can exist at rest in published messages, enable encryption at rest to help protect that data.',
level: NagMessageLevel.ERROR,
rule: SNSEncryptedKMS,
node: node,
});
}
/**
* Check VPC Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkVPC(node: CfnResource): void {
this.applyRule({
info: "The VPC's default security group allows inbound or outbound traffic - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 2.1, 2.2, 2.2.2).",
explanation:
'Amazon Elastic Compute Cloud (Amazon EC2) security groups can help in the management of network access by providing stateful filtering of ingress and egress network traffic to AWS resources. Restricting all the traffic on the default security group helps in restricting remote access to your AWS resources.',
level: NagMessageLevel.WARN,
rule: VPCDefaultSecurityGroupClosed,
node: node,
});
this.applyRule({
info: 'The VPC does not have an associated Flow Log - (Control IDs: 2.2, 10.1, 10.3.2, 10.3.3, 10.3.4, 10.3.5, 10.3.6).',
explanation:
'The VPC flow logs provide detailed records for information about the IP traffic going to and from network interfaces in your Amazon Virtual Private Cloud (Amazon VPC). By default, the flow log record includes values for the different components of the IP flow, including the source, destination, and protocol.',
level: NagMessageLevel.ERROR,
rule: VPCFlowLogsEnabled,
node: node,
});
this.applyRule({
info: "The route table may contain one or more unrestricted route(s) to an IGW ('0.0.0.0/0' or '::/0') - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 2.2.2).",
explanation:
'Ensure Amazon EC2 route tables do not have unrestricted routes to an internet gateway. Removing or limiting the access to the internet for workloads within Amazon VPCs can reduce unintended access within your environment.',
level: NagMessageLevel.ERROR,
rule: VPCNoUnrestrictedRouteToIGW,
node: node,
});
this.applyRule({
info: 'The subnet auto-assigns public IP addresses - (Control IDs: 1.2, 1.2.1, 1.3, 1.3.1, 1.3.2, 1.3.4, 1.3.6, 2.2.2).',
explanation:
'Manage access to the AWS Cloud by ensuring Amazon Virtual Private Cloud (VPC) subnets are not automatically assigned a public IP address. Amazon Elastic Compute Cloud (EC2) instances that are launched into subnets that have this attribute enabled have a public IP address assigned to their primary network interface.',
level: NagMessageLevel.ERROR,
rule: VPCSubnetAutoAssignPublicIpDisabled,
node: node,
});
}
/**
* Check WAF Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkWAF(node: CfnResource): void {
this.applyRule({
info: 'The WAFv2 web ACL does not have logging enabled - (Control IDs: 10.1, 10.3.1, 10.3.2, 10.3.3, 10.3.4, 10.3.5, 10.3.6, 10.5.4).',
explanation:
'AWS WAF logging provides detailed information about the traffic that is analyzed by your web ACL. The logs record the time that AWS WAF received the request from your AWS resource, information about the request, and an action for the rule that each request matched.',
level: NagMessageLevel.ERROR,
rule: WAFv2LoggingEnabled,
node: node,
});
}
} | the_stack |
import {
ProxyReadAttribute,
ProxyReadNotifyAttribute,
ProxyReadWriteAttribute,
ProxyReadWriteNotifyAttribute
} from "../../../../main/js/joynr/proxy/ProxyAttribute";
import MessagingQos from "../../../../main/js/joynr/messaging/MessagingQos";
import OnChangeWithKeepAliveSubscriptionQos from "../../../../main/js/joynr/proxy/OnChangeWithKeepAliveSubscriptionQos";
import * as Request from "../../../../main/js/joynr/dispatching/types/Request";
import TestEnum from "../../../generated/joynr/tests/testTypes/TestEnum";
import TypeRegistrySingleton from "../../../../main/js/joynr/types/TypeRegistrySingleton";
import DiscoveryEntryWithMetaInfo from "../../../../main/js/generated/joynr/types/DiscoveryEntryWithMetaInfo";
import Version from "../../../../main/js/generated/joynr/types/Version";
import ProviderQos from "../../../../main/js/generated/joynr/types/ProviderQos";
import ComplexTestType = require("../../../generated/joynr/tests/testTypes/ComplexTestType");
describe("libjoynr-js.joynr.proxy.ProxyAttribute", () => {
let isOn: ProxyReadWriteNotifyAttribute<boolean>;
let isOnNotifyReadOnly: ProxyReadNotifyAttribute<boolean>;
let isOnReadWrite: ProxyReadWriteAttribute<boolean>;
let isOnReadOnly: ProxyReadAttribute<boolean>;
let subscriptionQos: any;
let messagingQos: any;
let requestReplyManagerSpy: any;
let subscriptionId: any;
let subscriptionManagerSpy: any;
let proxyParticipantId: any;
let providerParticipantId: any;
let providerDiscoveryEntry: any;
let isOnType: string;
let settings: any;
let proxy: any;
function RadioStation(this: any, name: any, station: any, source: any) {
this.name = name;
this.station = station;
this.source = source;
this.checkMembers = jest.fn();
Object.defineProperty(this, "_typeName", {
configurable: false,
writable: false,
enumerable: true,
value: "test.RadioStation"
});
}
beforeEach(() => {
subscriptionQos = new OnChangeWithKeepAliveSubscriptionQos();
messagingQos = new MessagingQos();
requestReplyManagerSpy = {
sendRequest: jest.fn()
};
requestReplyManagerSpy.sendRequest.mockImplementation((_settings: any, callbackSettings: any) => {
const response = { result: { resultKey: "resultValue" } };
return Promise.resolve({
response,
settings: callbackSettings
});
});
subscriptionId = {
tokenId: "someId",
tokenUserData: "some additional data, do not touch!"
};
subscriptionManagerSpy = {
registerSubscription: jest.fn(),
unregisterSubscription: jest.fn()
};
subscriptionManagerSpy.registerSubscription.mockReturnValue(Promise.resolve(subscriptionId));
subscriptionManagerSpy.unregisterSubscription.mockReturnValue(Promise.resolve(subscriptionId));
proxyParticipantId = "proxyParticipantId";
providerParticipantId = "providerParticipantId";
providerDiscoveryEntry = new DiscoveryEntryWithMetaInfo({
providerVersion: new Version({ majorVersion: 0, minorVersion: 23 }),
domain: "testProviderDomain",
interfaceName: "interfaceName",
participantId: providerParticipantId,
qos: new (ProviderQos as any)(),
lastSeenDateMs: Date.now(),
expiryDateMs: Date.now() + 60000,
publicKeyId: "publicKeyId",
isLocal: true
});
settings = {
dependencies: {
requestReplyManager: requestReplyManagerSpy,
subscriptionManager: subscriptionManagerSpy
}
};
proxy = {
proxyParticipantId,
providerDiscoveryEntry,
settings
};
isOnType = "Boolean";
isOn = new ProxyReadWriteNotifyAttribute(proxy, "isOn", isOnType);
isOnNotifyReadOnly = new ProxyReadNotifyAttribute(proxy, "isOnNotifyReadOnly", "Boolean");
isOnReadOnly = new ProxyReadAttribute(proxy, "isOnReadOnly", "Boolean");
isOnReadWrite = new ProxyReadWriteAttribute(proxy, "isOnReadWrite", "Boolean");
TypeRegistrySingleton.getInstance().addType(TestEnum);
});
it("got initialized", done => {
expect(isOn).toBeDefined();
expect(isOn).not.toBeNull();
expect(typeof isOn === "object").toBeTruthy();
done();
});
it("has correct members (ProxyAttribute with NOTIFYREADWRITE)", done => {
expect(isOn.get).toBeDefined();
expect(isOn.set).toBeDefined();
expect(isOn.subscribe).toBeDefined();
expect(isOn.unsubscribe).toBeDefined();
done();
});
it("has correct members (ProxyAttribute with NOTIFYREADONLY)", done => {
expect(isOnNotifyReadOnly.get).toBeDefined();
expect((isOnNotifyReadOnly as any).set).toBeUndefined();
expect(isOnNotifyReadOnly.subscribe).toBeDefined();
expect(isOnNotifyReadOnly.unsubscribe).toBeDefined();
done();
});
it("has correct members (ProxyAttribute with READWRITE)", done => {
expect(isOnReadWrite.get).toBeDefined();
expect(isOnReadWrite.set).toBeDefined();
expect((isOnReadWrite as any).subscribe).toBeUndefined();
expect((isOnReadWrite as any).unsubscribe).toBeUndefined();
done();
});
it("has correct members (ProxyAttribute with READONLY)", done => {
expect(isOnReadOnly.get).toBeDefined();
expect((isOnReadOnly as any).set).toBeUndefined();
expect((isOnReadOnly as any).subscribe).toBeUndefined();
expect((isOnReadOnly as any).unsubscribe).toBeUndefined();
done();
});
it("get calls through to RequestReplyManager", async () => {
await isOn.get();
expect(requestReplyManagerSpy.sendRequest).toHaveBeenCalled();
const requestReplyId = requestReplyManagerSpy.sendRequest.mock.calls[0][0].request.requestReplyId;
expect(requestReplyManagerSpy.sendRequest).toHaveBeenCalledWith(
{
toDiscoveryEntry: providerDiscoveryEntry,
from: proxyParticipantId,
messagingQos,
request: Request.create({
methodName: "getIsOn",
requestReplyId
})
},
isOnType
);
});
it("get notifies", async () => {
expect(isOn.get).toBeDefined();
expect(typeof isOn.get === "function").toBeTruthy();
await isOn.get();
});
it("get returns correct joynr objects", done => {
const fixture = new ProxyReadWriteNotifyAttribute(
{
proxyParticipantId: "proxy",
providerDiscoveryEntry,
settings
},
"attributeOfTypeTestEnum",
TestEnum.ZERO._typeName
);
expect(fixture.get).toBeDefined();
expect(typeof fixture.get === "function").toBeTruthy();
requestReplyManagerSpy.sendRequest.mockImplementation((_settings: any, callbackSettings: any) => {
return Promise.resolve({
response: ["ZERO"],
settings: callbackSettings
});
});
fixture.get().then((data: any) => {
expect(data).toEqual(TestEnum.ZERO);
done();
});
});
it("expect correct error reporting after attribute set with invalid value", done => {
TypeRegistrySingleton.getInstance().addType(ComplexTestType);
const enumAttribute = new ProxyReadWriteNotifyAttribute(
{
proxyParticipantId: "proxy",
providerParticipantId: "provider",
settings
},
"enumAttribute",
"joynr.tests.testTypes.ComplexTestType"
);
return enumAttribute
.set({
value: {
_typeName: "joynr.tests.testTypes.ComplexTestType",
a: "notANumber"
}
})
.then(() => {
done.fail("unexpected resolve from setter with invalid value");
})
.catch((error: any) => {
expect(error.message).toEqual(
"error setting attribute: enumAttribute: Error: members.a is not of type Number. Actual type is String"
);
done();
});
});
it("set calls through to RequestReplyManager", async () => {
await isOn.set({
value: true
});
expect(requestReplyManagerSpy.sendRequest).toHaveBeenCalled();
const requestReplyId = requestReplyManagerSpy.sendRequest.mock.calls[0][0].request.requestReplyId;
expect(requestReplyManagerSpy.sendRequest).toHaveBeenCalledWith(
{
toDiscoveryEntry: providerDiscoveryEntry,
from: proxyParticipantId,
messagingQos,
request: Request.create({
methodName: "setIsOn",
requestReplyId,
paramDatatypes: ["Boolean"],
params: [true]
})
},
isOnType
);
});
it("subscribe calls through to SubscriptionManager", done => {
const spy = {
onReceive: jest.fn(),
onError: jest.fn(),
onSubscribed: jest.fn()
};
isOn.subscribe({
subscriptionQos,
onReceive: spy.onReceive,
onError: spy.onError,
onSubscribed: spy.onSubscribed
});
expect(subscriptionManagerSpy.registerSubscription).toHaveBeenCalled();
expect(subscriptionManagerSpy.registerSubscription).toHaveBeenCalledWith({
proxyId: proxyParticipantId,
providerDiscoveryEntry,
attributeName: "isOn",
attributeType: "Boolean",
qos: subscriptionQos,
subscriptionId: undefined,
onReceive: spy.onReceive,
onError: spy.onError,
onSubscribed: spy.onSubscribed
});
done();
});
it("subscribe notifies", async () => {
expect(isOn.subscribe).toBeDefined();
expect(typeof isOn.subscribe === "function").toBeTruthy();
await isOn.subscribe({
subscriptionQos,
onReceive() {},
onError() {}
});
});
it("subscribe provides a subscriptionId", done => {
isOn.subscribe({
subscriptionQos,
onReceive() {},
onError() {}
})
.then(id => {
expect(id).toEqual(subscriptionId);
done();
return null;
})
.catch(() => {
return null;
});
});
it("unsubscribe calls through to SubscriptionManager", done => {
isOn.unsubscribe({
subscriptionId
})
.then(() => {
expect(subscriptionManagerSpy.unregisterSubscription).toHaveBeenCalled();
expect(subscriptionManagerSpy.unregisterSubscription).toHaveBeenCalledWith({
messagingQos: new MessagingQos(),
subscriptionId
});
done();
return null;
})
.catch(() => {
return null;
});
});
it("unsubscribe notifies", async () => {
expect(isOn.unsubscribe).toBeDefined();
expect(typeof isOn.unsubscribe === "function").toBeTruthy();
const subscriptionId = await isOn.subscribe({
subscriptionQos,
onReceive() {},
onError() {}
});
await isOn.unsubscribe({
subscriptionId
});
});
it("rejects if caller sets a generic object without a declared _typeName attribute with the name of a registrered type", done => {
const radioStationProxyAttributeWrite = new ProxyReadWriteAttribute(
proxy,
"radioStationProxyAttributeWrite",
RadioStation
);
radioStationProxyAttributeWrite
.set({
value: {
name: "radiostationname",
station: "station"
}
})
.then(() => done.fail())
.catch(() => done());
});
}); | the_stack |
import * as fs from 'fs';
import * as path from 'path';
import * as config from '../config';
import * as fileUtils from '../utils/file.utils';
import {Logger, LogLevel} from '../logger';
import {IDataProvider} from '../data.manager';
import {window} from 'vscode';
/**
* Markdown tables data provider.
*/
export class MarkdownDataProvider implements IDataProvider {
// TODO: add mime types later for http data loading
public supportedDataFileTypes: Array<string> = ['.md'];
private logger: Logger = new Logger('markdown.data.provider:', config.logLevel);
// local table names cache with dataUrl/tableNames array key/values
private dataTableNamesMap = {};
/**
* Creates data provider for Excel data files.
*/
constructor() {
this.logger.debug('created for:', this.supportedDataFileTypes);
}
/**
* Gets local or remote markdown file table data.
* @param dataUrl Local data file path or remote data url.
* @param parseOptions Data parse options.
* @param loadData Load data callback.
*/
public async getData(dataUrl: string, parseOptions: any, loadData: Function): Promise<void> {
let content: string = '';
try {
// read markdown file content
content = String(await fileUtils.readDataFile(dataUrl, 'utf8'));
// convert it to to CSV for loading into data view
content = this.markdownToCsv(dataUrl, content, parseOptions.dataTable);
}
catch (error) {
this.logger.error(`getMarkdownData(): Error parsing '${dataUrl}'. \n\t Error: ${error.message}`);
window.showErrorMessage(`Unable to parse data file: '${dataUrl}'. \n\t Error: ${error.message}`);
}
loadData(content);
} // end of getData()
/**
* Gets data table names for data sources with multiple data sets.
* @param dataUrl Local data file path or remote data url.
*/
public getDataTableNames(dataUrl: string): Array<string> {
return this.dataTableNamesMap[dataUrl];
}
/**
* Gets data schema in json format for file types that provide it.
* @param dataUrl Local data file path or remote data url.
*/
public getDataSchema(dataUrl: string): any {
// TODO: return md table headers row later ???
return null; // none for .md data files
}
/**
* Saves CSV as markdown table data.
* @param filePath Local data file path.
* @param fileData Raw data to save.
* @param tableName Table name for data files with multiple tables support.
* @param showData Show saved data callback.
*/
public saveData(filePath: string, fileData: any, tableName: string, showData?: Function): void {
// convert CSV text to markdown table
fileData = this.csvToMarkdownTable(fileData);
if ( fileData.length > 0) {
// TODO: change this to async later
fs.writeFile(filePath, fileData, (error) => showData(error));
}
}
/**
* Converts markdown content to csv data for display in data view.
* @param dataUrl Local data file path or remote data url.
* @param markdownContent Markdown file content to convert to csv string.
* @param dataTable Markdown data table name to load.
*/
private markdownToCsv(dataUrl:string, markdownContent: string, dataTable: string): string {
// extract markdown sections and tables
const sections: Array<string> = markdownContent.split('\n#');
const sectionMarker: RegExp = new RegExp(/(#)/g);
const quotes: RegExp = new RegExp(/(")/g);
const tableHeaderSeparator: RegExp = new RegExp(/((\|)|(\:)|(\-)|(\s))+/g);
const tableRowMarkdown: RegExp = new RegExp(/((\|[^|\r\n]*)+\|(\r?\n|\r)?)/g);
const tablesMap: any = {};
let tableNames: Array<string> = [];
sections.forEach(section => {
// get section title
let sectionTitle: string = '';
const sectionLines: Array<string> = section.split('\n');
if (sectionLines.length > 0) {
sectionTitle = sectionLines[0].replace(sectionMarker, '').trim(); // strip out #'s and trim
}
// create section text blocks
const textBlocks: Array<string> = [];
let textBlock: string = '';
sectionLines.forEach(textLine => {
if (textLine.trim().length === 0) {
// create new text block
textBlocks.push(textBlock);
textBlock = '';
}
else {
// append to the current text block
textBlock += textLine + '\n';
}
});
// extract section table data from each section text block
const tables: Array<Array<string>> = []; // two-dimensional array of table rows
textBlocks.forEach(textBlock => {
// extract markdown table data rows from a text block
const tableRows: Array<string> = textBlock.match(tableRowMarkdown);
if (tableRows) {
// add matching markdown table rows to the tables array
tables.push(tableRows);
this.logger.debug('markdownToCsv(): section:', sectionTitle);
this.logger.debug('markdownToCsv(): extractred markdown table rows:', tableRows);
}
});
// process markdown tables
tables.forEach((table, tableIndex) => {
// process markdown table row strings
const tableRows: Array<string> = [];
table.forEach(row => {
// trim markdown table text row lines
row = row.trim();
// strip out leading | table row sign
if (row.startsWith('| ')) {
row = row.slice(2);
}
// strip out trailing | table row sign
if (row.endsWith(' |')) {
row = row.slice(0, row.length-2);
}
// check for a table header separator row
const isTableHeaderSeparator: boolean = (row.replace(tableHeaderSeparator, '').length === 0);
if (!isTableHeaderSeparator && row.length > 0) {
// add data table row
tableRows.push(row);
}
});
if (tableRows.length > 0 ) {
// create table title
let tableTitle: string = sectionTitle;
if (tables.length > 1) {
// append table index
tableTitle += '-table-' + (tableIndex + 1);
}
// update table list for data view display
tablesMap[tableTitle] = tableRows;
tableNames.push(tableTitle);
this.logger.debug(`markdownToCsv(): created data table: '${tableTitle}' rows: ${tableRows.length}`);
}
}); // end of tables.forEach(row)
}); // end of sections.forEach(textBlock/table)
// get requested table data
let table: Array<string> = tablesMap[tableNames[0]]; // default to 1st table in the loaded tables list
if (dataTable && dataTable.length > 0) {
table = tablesMap[dataTable];
this.logger.debug(`markdownToCsv(): requested data table: '${dataTable}'`);
}
if (tableNames.length === 1) {
// clear table names if only one markdown table is present
tableNames = [];
}
// update table names cache
this.dataTableNamesMap[dataUrl] = tableNames;
// convert requested markdown table to csv for data view display
let csvContent: string = '';
if (table) {
this.logger.debug('markdownToCsv(): markdown table rows:', table);
table.forEach(row => {
const cells: Array<string> = row.split(' | ');
const csvCells: Array<string> = [];
cells.forEach(cell => {
cell = cell.trim();
const cellHasQuotes: boolean = quotes.test(cell);
if (cellHasQuotes) {
// escape quotes for csv
cell = cell.replace(quotes, '""'); // double quote for csv quote escape
}
if (cellHasQuotes || cell.indexOf(',') >= 0) {
// quote cell string
cell = `"${cell}"`;
}
csvCells.push(cell);
});
const csvRow = csvCells.join(',');
csvContent += csvRow + '\n';
});
this.logger.debug('markdownToCsv(): final csv table content string for data.view load:\n', csvContent);
}
return csvContent;
} // end of markdownToCsv()
/**
* Converts CSV to markdown table.
* @param {string} csvContent Csv/tsv data content.
* @param {string} delimiter Csv/tsv delimiter.
* @param {boolean} hasTableHeaderRow Has table header row.
* @returns {string} Markdown table content.
*/
private csvToMarkdownTable(csvContent: string, delimiter: string = ',', hasTableHeaderRow: boolean = true) : string {
if (delimiter !== '\t') {
// replace all tabs with spaces
csvContent = csvContent.replace(/\t/g, ' ');
}
// extract table rows and data from csv content
const csvRows: Array<string> = csvContent.split('\n');
const tableData: string[][] = [];
const maxColumnLength: number[] = []; // for pretty markdown table cell spacing
const cellRegExp: RegExp = new RegExp(delimiter + '(?![^"]*"\\B)');
const doubleQuotes: RegExp = new RegExp(/("")/g);
this.logger.debug('csvToMarkdownTable(): csv rows:', csvRows);
csvRows.forEach((row, rowIndex) => {
if (typeof tableData[rowIndex] === 'undefined') {
// create new table row cells data array
tableData[rowIndex] = [];
}
// extract row cells data from csv text line
const cells: Array<string> = row.replace('\r', '').split(cellRegExp);
cells.forEach((cell, columnIndex) => {
if (typeof maxColumnLength[columnIndex] === 'undefined') {
// set initial column size to 0
maxColumnLength[columnIndex] = 0;
}
// strip out leading and trailing quotes
if (cell.startsWith('"')) {
cell = cell.substring(1);
}
if (cell.endsWith('"')) {
cell = cell.substring(0, cell.length - 1);
}
// replace escaped double quotes that come from csv text data format
cell = cell.replace(doubleQuotes, '"');
// update max column length for pretty markdwon table cells spacing
maxColumnLength[columnIndex] = Math.max(maxColumnLength[columnIndex], cell.length);
// save extracted cell data for table rows output
tableData[rowIndex][columnIndex] = cell;
});
});
// create markdown table header and separator text lines
let tableHeader: string = '';
let tableHeaderSeparator: string = '';
maxColumnLength.forEach((columnLength) => {
const columnHeader = Array(columnLength + 1 + 2);
tableHeader += '|' + columnHeader.join(' ');
tableHeaderSeparator += '|' + columnHeader.join('-');
});
// end table header and separator text lines
tableHeader += '| \n';
tableHeaderSeparator += '| \n';
if (hasTableHeaderRow) {
// reset: use table data instead
tableHeader = '';
}
// create markdown table data text lines
let tableRows = '';
tableData.forEach((row, rowIndex) => {
maxColumnLength.forEach((columnLength, columnIndex) => {
const cellData: string = typeof row[columnIndex] === 'undefined' ? '' : row[columnIndex];
const cellSpacing: string = Array((columnLength - cellData.length) + 1).join(' ');
const cellString: string = `| ${cellData}${cellSpacing} `;
if (hasTableHeaderRow && rowIndex === 0) {
tableHeader += cellString;
} else {
tableRows += cellString;
}
});
// end table header or data row text line
if (hasTableHeaderRow && rowIndex === 0) {
tableHeader += '| \n';
} else {
tableRows += '| \n';
}
});
return `${tableHeader}${tableHeaderSeparator}${tableRows}`;
} // end of csvToMarkdownTable()
} | the_stack |
import {checkTransform} from './worker-test-util.js';
import type {BuildOutput, SampleFile} from '../shared/worker-api.js';
import type {CdnData} from './fake-cdn-plugin.js';
suite('typescript builder', () => {
test('empty project', async () => {
const files: SampleFile[] = [];
const expected: BuildOutput[] = [];
await checkTransform(files, expected);
});
test('compiles ts file to js', async () => {
const files: SampleFile[] = [
{
name: 'index.ts',
content: 'export const foo: number = 3;',
},
];
const expected: BuildOutput[] = [
{
kind: 'file',
file: {
name: 'index.js',
content: 'export const foo = 3;\r\n',
contentType: 'text/javascript',
},
},
];
await checkTransform(files, expected);
});
test('ignores js file', async () => {
const files: SampleFile[] = [
{
name: 'index.js',
content: 'export const foo: number = 3;',
},
];
const expected: BuildOutput[] = [
{
kind: 'file',
file: {
name: 'index.js',
content: 'export const foo: number = 3;',
},
},
];
await checkTransform(files, expected);
});
test('emits syntax error', async () => {
const files: SampleFile[] = [
{
name: 'index.ts',
content: ':',
},
];
const expected: BuildOutput[] = [
{
diagnostic: {
code: 1128,
message: 'Declaration or statement expected.',
range: {
end: {
character: 1,
line: 0,
},
start: {
character: 0,
line: 0,
},
},
severity: 1,
source: 'typescript',
},
filename: 'index.ts',
kind: 'diagnostic',
},
{
kind: 'file',
file: {
name: 'index.js',
// TODO(aomarks) This should probably return a 400 error instead of an
// empty but valid file.
content: '',
contentType: 'text/javascript',
},
},
];
await checkTransform(files, expected);
});
test('emits local semantic error', async () => {
const files: SampleFile[] = [
{
name: 'index.ts',
content: `
let foo: number = 3;
foo = "foo";
`,
},
];
const expected: BuildOutput[] = [
{
diagnostic: {
code: 2322,
message: "Type 'string' is not assignable to type 'number'.",
range: {
end: {
character: 13,
line: 2,
},
start: {
character: 10,
line: 2,
},
},
severity: 1,
source: 'typescript',
},
filename: 'index.ts',
kind: 'diagnostic',
},
{
kind: 'file',
file: {
name: 'index.js',
content: 'let foo = 3;\r\n' + 'foo = "foo";\r\n',
contentType: 'text/javascript',
},
},
];
await checkTransform(files, expected);
});
test('emits semantic error from bare module', async () => {
const files: SampleFile[] = [
{
name: 'index.ts',
content: `
import {strFn} from "foo";
import {numFn} from "foo/bar.js";
strFn(123);
numFn("str");
`,
},
];
const cdn: CdnData = {
foo: {
versions: {
'2.0.0': {
files: {
'package.json': {
content: '{"main": "index.js"}',
},
'index.js': {
content: 'export const strFn = (s) => s;',
},
'bar.js': {
content: 'export const numFn = (n) => n;',
},
'index.d.ts': {
content: 'export declare const strFn: (s: string) => string;',
},
'bar.d.ts': {
content: 'export declare const numFn: (n: number) => number;',
},
},
},
},
},
};
const expected: BuildOutput[] = [
{
diagnostic: {
code: 2345,
message:
"Argument of type 'number' is not assignable to parameter of type 'string'.",
range: {
end: {
character: 19,
line: 3,
},
start: {
character: 16,
line: 3,
},
},
severity: 1,
source: 'typescript',
},
filename: 'index.ts',
kind: 'diagnostic',
},
{
diagnostic: {
code: 2345,
message:
"Argument of type 'string' is not assignable to parameter of type 'number'.",
range: {
end: {
character: 21,
line: 4,
},
start: {
character: 16,
line: 4,
},
},
severity: 1,
source: 'typescript',
},
filename: 'index.ts',
kind: 'diagnostic',
},
{
kind: 'file',
file: {
name: 'index.js',
content:
'import { strFn } from "./node_modules/foo@2.0.0/index.js";\r\nimport { numFn } from "./node_modules/foo@2.0.0/bar.js";\r\nstrFn(123);\r\nnumFn("str");\r\n',
contentType: 'text/javascript',
},
},
{
kind: 'file',
file: {
name: 'node_modules/foo@2.0.0/index.js',
content: 'export const strFn = (s) => s;',
contentType: 'text/javascript; charset=utf-8',
},
},
{
kind: 'file',
file: {
name: 'node_modules/foo@2.0.0/bar.js',
content: 'export const numFn = (n) => n;',
contentType: 'text/javascript; charset=utf-8',
},
},
];
await checkTransform(files, expected, {}, cdn);
});
test('respects package.json dependency for semantic errors', async () => {
const files: SampleFile[] = [
{
name: 'index.ts',
content: `
import {foo} from "foo";
foo(123);
`,
},
{
name: 'package.json',
content: `{
"dependencies": {
"foo": "^1.0.0"
}
}`,
},
];
const cdn: CdnData = {
foo: {
// foo takes a string in 1.0.0, and a number in 2.0.0. We should expect
// an error because we depend on 1.0.0.
versions: {
'1.0.0': {
files: {
'index.js': {
content: 'export const foo = (s) => s;',
},
'index.d.ts': {
content: `
import type {t} from './type.js';
export declare const foo: (s: t) => t;
`,
},
'type.d.ts': {
content: `export type t = string;`,
},
},
},
'2.0.0': {
files: {
'index.js': {
content: 'export const foo = (n) => n;',
},
'index.d.ts': {
content: 'export declare const foo: (n: number) => number;',
},
},
},
},
},
};
const expected: BuildOutput[] = [
{
diagnostic: {
code: 2345,
message:
"Argument of type 'number' is not assignable to parameter of type 'string'.",
range: {
end: {
character: 17,
line: 2,
},
start: {
character: 14,
line: 2,
},
},
severity: 1,
source: 'typescript',
},
filename: 'index.ts',
kind: 'diagnostic',
},
{
kind: 'file',
file: {
name: 'index.js',
content:
'import { foo } from "./node_modules/foo@1.0.0/index.js";\r\nfoo(123);\r\n',
contentType: 'text/javascript',
},
},
{
kind: 'file',
file: {
name: 'node_modules/foo@1.0.0/index.js',
content: 'export const foo = (s) => s;',
contentType: 'text/javascript; charset=utf-8',
},
},
{
kind: 'file',
file: {
name: 'package.json',
content: `{
"dependencies": {
"foo": "^1.0.0"
}
}`,
},
},
];
await checkTransform(files, expected, {}, cdn);
});
test('prefers typings from: typings, types, main, index.d.ts', async () => {
const wrong = {
content: 'export type StringType = number;',
};
const files: SampleFile[] = [
{
name: 'index.ts',
content: `
import {StringType} from "a";
export const str: StringType = "foo";
`,
},
];
const cdn: CdnData = {
a: {
versions: {
'1.0.0': {
files: {
'package.json': {
content: `{
"typings": "typings.d.ts",
"types": "types.d.ts",
"main": "main.js"
}`,
},
'typings.d.ts': {
content: 'export * from "b";',
},
'types.d.ts': wrong,
'main.d.ts': wrong,
'index.d.ts': wrong,
},
},
},
},
b: {
versions: {
'1.0.0': {
files: {
'package.json': {
content: `{
"types": "types.d.ts",
"main": "main.js"
}`,
},
'typings.d.ts': wrong,
'types.d.ts': {
content: 'export * from "c";',
},
'main.d.ts': wrong,
'index.d.ts': wrong,
},
},
},
},
c: {
versions: {
'1.0.0': {
files: {
'package.json': {
content: `{
"main": "main.js"
}`,
},
'typings.d.ts': wrong,
'types.d.ts': wrong,
'main.d.ts': {
content: 'export * from "d";',
},
'index.d.ts': wrong,
},
},
},
},
d: {
versions: {
'1.0.0': {
files: {
'package.json': {
content: `{}`,
},
'typings.d.ts': wrong,
'types.d.ts': wrong,
'main.d.ts': wrong,
'index.d.ts': {
content: 'export type StringType = string;',
},
},
},
},
},
};
const expected: BuildOutput[] = [
{
kind: 'file',
file: {
name: 'index.js',
content: `export const str = "foo";\r\n`,
contentType: 'text/javascript',
},
},
];
await checkTransform(files, expected, {}, cdn);
});
test('handles multiple versions', async () => {
const files: SampleFile[] = [
{
name: 'index.ts',
content: `
import {num} from "foo";
import {str} from "str-or-num";
const a: string = str;
const b: number = num
`,
},
{
name: 'package.json',
content: `{
"dependencies": {
"foo": "^1.0.0",
"str-or-num": "^1.0.0"
}
}`,
},
];
const cdn: CdnData = {
'str-or-num': {
versions: {
'1.0.0': {
files: {
'index.js': {
content: 'export const str = "str";',
},
'index.d.ts': {
content: 'declare export const str: string;',
},
},
},
'2.0.0': {
files: {
'index.js': {
content: 'export const num = 0;',
},
'index.d.ts': {
content: 'declare export const num: number;',
},
},
},
},
},
foo: {
versions: {
'1.0.0': {
files: {
'package.json': {
content: `{
"dependencies": {
"str-or-num": "^2.0.0"
}
}`,
},
'index.js': {
content: `export * from 'str-or-num';`,
},
'index.d.ts': {
content: `declare export * from 'str-or-num';`,
},
},
},
},
},
typescript: {
versions: {
'4.3.5': {
files: {
'lib/lib.dom.d.ts': {
content: '',
},
'lib/lib.esnext.d.ts': {
content: '',
},
'lib/lib.dom.iterable.d.ts': {
content: '',
},
},
},
},
},
};
const expected: BuildOutput[] = [
{
kind: 'file',
file: {
name: 'index.js',
content:
'import { num } from "./node_modules/foo@1.0.0/index.js";\r\nimport { str } from "./node_modules/str-or-num@1.0.0/index.js";\r\nconst a = str;\r\nconst b = num;\r\n',
contentType: 'text/javascript',
},
},
{
file: {
content: "export * from '../str-or-num@2.0.0/index.js';",
contentType: 'text/javascript; charset=utf-8',
name: 'node_modules/foo@1.0.0/index.js',
},
kind: 'file',
},
{
file: {
content: 'export const str = "str";',
contentType: 'text/javascript; charset=utf-8',
name: 'node_modules/str-or-num@1.0.0/index.js',
},
kind: 'file',
},
{
file: {
content: 'export const num = 0;',
contentType: 'text/javascript; charset=utf-8',
name: 'node_modules/str-or-num@2.0.0/index.js',
},
kind: 'file',
},
{
file: {
content:
'{\n "dependencies": {\n "foo": "^1.0.0",\n "str-or-num": "^1.0.0"\n }\n }',
name: 'package.json',
},
kind: 'file',
},
];
await checkTransform(files, expected, {}, cdn);
});
}); | the_stack |
import './index.less';
import classname from 'classname';
import Sortable from 'sortablejs';
import { ModalComponent, mountModal } from '../modal';
import { Component, createVNode } from 'jeact';
type ImageInfo = {
url: string;
width?: number;
height?: number;
type?: string;
propertyCode?: string;
platform?: string;
}
export class PictureSelectorComponent extends Component {
imageList: ImageInfo[] = [];
poaList: { code: string; label: string }[] = [];
poaFilter: string;
platformList: { value: string; label: string }[] = [];
platformFilter: string;
currentCode: string;
selectedImg: Record<string, ImageInfo[]> = { [this.currentCode]: [] };
bgxCode: string;
bgxSubCode: string;
bgxMaxImageNum: number;
bgxMaxImageSize: number;
bgxMinImageSize: number;
bgxMustSquare: boolean;
bgxLoadImageByCode: (code) => Promise<ImageInfo[]>;
bgxOnOk: (imageList: Record<string, string[]>) => void;
set bgxInitImg(value: Record<string, string[]>) {
this.currentCode = Object.keys(value)[0] || '';
Object.keys(value).forEach((code) => {
this.getImageInfos(value[code].map((value1) => ({ url: value1 }))).then((res) => {
this.selectedImg[code] = res;
});
});
}
get displayImage() {
return this.imageList.filter(
(value) =>
(!this.poaFilter || value.propertyCode === this.poaFilter) &&
(!this.platformFilter || value.platform === this.platformFilter),
);
}
loadPoaList() {
const poaList = [
...new Set(this.imageList.map((value) => value.propertyCode).filter((value) => value)),
];
return poaList.map(function (value) {
return {
code: value,
label: value,
};
});
}
loadPlatformList() {
const platformList = [
...new Set(this.imageList.map((value) => value.platform).filter((value) => value)),
];
return platformList.map(function (value) {
return {
value,
label: value,
};
});
}
getImageInfos(images: ImageInfo[]) {
return Promise.all(images.map((image) => this.getImgInfo(image)));
}
getImgInfo(image: ImageInfo): Promise<ImageInfo> {
const newImage: ImageInfo = { ...image };
return new Promise<ImageInfo>((resolve, reject) => {
const img = new Image();
img.src = image.url;
img.onerror = function (e) {
resolve(newImage);
};
const arr = newImage.url.split('.');
newImage.type = arr[arr.length - 1].toUpperCase();
if (img.complete) {
newImage.width = img.width;
newImage.height = img.height;
resolve(newImage);
} else {
img.onload = function () {
newImage.width = img.width;
newImage.height = img.height;
img.onload = null; // 避免重复加载
resolve(newImage);
};
}
});
}
constructor(args) {
super(args);
}
mounted() {
super.mounted();
const wrapper = this.refs.sortWrapper as HTMLElement;
// tslint:disable-next-line:no-unused-expression
new Sortable(wrapper, {
animation: 150,
onUpdate: (event) => {
const item = this.selectedImg[this.currentCode].splice(event.oldIndex, 1)[0];
this.selectedImg[this.currentCode].splice(event.newIndex, 0, item);
this.update();
},
});
this.loadByCode();
}
async loadByCode() {
if (this.bgxLoadImageByCode && this.bgxCode) {
try {
this.imageList = await this.bgxLoadImageByCode(this.bgxCode);
} catch (e) {
this.imageList = [];
}
this.update();
this.poaList = this.loadPoaList();
if (this.bgxSubCode && this.poaList.some((value) => value.code === this.bgxSubCode)) {
this.poaFilter = this.bgxSubCode;
this.bgxSubCode = null;
}
this.platformList = this.loadPlatformList();
this.imageList = await this.getImageInfos(this.imageList);
this.update();
}
}
selectAll = (e) => {
const num =
this.bgxMaxImageNum != null
? this.bgxMaxImageNum - this.selectedImg[this.currentCode].length
: this.selectedImg.length;
const unselectedImg = this.displayImage.filter(
(value) => !this.isSelected(value) && this.sizeCheck(value),
);
const newImgs = unselectedImg[this.currentCode].slice(0, num);
this.selectedImg[this.currentCode] = this.selectedImg[this.currentCode].concat(newImgs);
this.update();
};
isSelected = (item: ImageInfo) => {
return (
this.selectedImg &&
this.selectedImg[this.currentCode].some((val) => val.url === (item && item.url))
);
};
private clickImg(item: ImageInfo) {
if (this.isSelected(item)) {
this.removeImg(item);
} else if (this.sizeCheck(item)) {
this.selectImg(item);
}
this.update();
}
selectImg(item: ImageInfo) {
if (this.selectedImg[this.currentCode].length >= this.bgxMaxImageNum) {
alert(`最多选择${this.bgxMaxImageNum}张图片!`);
return;
}
this.selectedImg[this.currentCode] = [...this.selectedImg[this.currentCode], item];
}
removeImg(item: ImageInfo) {
const index = this.selectedImg[this.currentCode].findIndex((val) => val.url === item.url);
this.selectedImg[this.currentCode].splice(index, 1);
this.selectedImg[this.currentCode] = [...this.selectedImg[this.currentCode]];
this.update();
}
preview(item: ImageInfo, imageList: ImageInfo[]) {
let currItem = item;
const modal = Component.create<ModalComponent>(
ModalComponent,
{
title: '预览图片',
content: () => {
return (
<div style="background: #fff; min-height: 600px; position: relative">
<img src={currItem.url} alt="" style="width: 100%" />
<div class="preview-left" onclick={() => lastImg()}>
<i class="fa fa-arrow-left" />
</div>
<div class="preview-right" onclick={() => nextImg()}>
<i class="fa fa-arrow-right" />
</div>
</div>
);
},
maskCloseable: true,
style: 'width: 900px;',
buttons: null,
},
document.body,
);
this.update();
const nextImg = () => {
const index = imageList.findIndex((value) => value === currItem);
currItem = imageList[(index + 1) % imageList.length];
modal.update();
};
const lastImg = () => {
const index = imageList.findIndex((value) => value === currItem);
const newIndex = index - 1 < 0 ? index + imageList.length : index - 1;
currItem = imageList[newIndex];
modal.update();
};
}
async codeChange(value: any) {
this.bgxCode = value;
this.loadByCode();
}
poaFilterChange() {
const that = this;
return function (this: HTMLSelectElement) {
that.poaFilter = this.value;
that.loadByCode();
};
}
platformFilterChange() {
const that = this;
return function (this: HTMLSelectElement) {
that.platformFilter = this.value;
that.loadByCode();
};
}
render() {
const SelectedImg = ({ item, imageList }: { item: ImageInfo; imageList: ImageInfo[] }) => {
return (
<div class="bgx-pic-selected-option-wrapper">
<img src={item.url} class="bgx-pic-selected-img" />
<div class="bgx-pic-selected-operation">
<i
class="fa fa-times-circle bgx-pic-selected-close"
onclick={() => this.removeImg(item)}
title="取消选择"
/>
<i
class="fa fa-search-plus bgx-pic-selected-icon"
onclick={() => this.preview(item, imageList)}
title="查看大图"
/>
</div>
</div>
);
};
const DisplayImg = ({ item, imageList }: { item: ImageInfo; imageList: ImageInfo[] }) => {
return (
<div
onclick={() => this.clickImg(item)}
class={classname([
'bgx-pic-images-option',
{ 'bgx-pic-images-option-selected': this.isSelected(item) },
])}
>
<div class="bgx-pic-images-option-wrapper">
<img src={item.url} class="bgx-pic-images-option-img" />
<div class="bgx-pic-images-option-mask">
{this.isSelected(item) && (
<i class={'fa fa-check-circle-o bgx-pic-images-option-icon'} />
)}
<i
class="fa fa-search-plus bgx-pic-images-option-preview"
onclick={(e) => {
this.preview(item, imageList);
e.stopPropagation();
}}
title="查看大图"
/>
</div>
</div>
<div>
<span>
{item.width}*{item.height} {item.type}
</span>
</div>
</div>
);
};
return (
<div class="bgx-picture-selector">
<div class="bgx-pic-tabs">
{Object.keys(this.selectedImg)
.filter(Boolean)
.map((code) => {
return (
<div
class={classname([
'bgx-pic-tab',
{ 'bgx-pic-tab-selected': code === this.currentCode },
])}
onclick={() => {
this.currentCode = code;
this.update();
}}
>
{code}
</div>
);
})}
</div>
<div class="bgx-pic-selected-images" ref="sortWrapper">
{this.selectedImg[this.currentCode].map((item) => (
<SelectedImg item={item} imageList={this.selectedImg[this.currentCode]} />
))}
</div>
<div class="bgx-pic-selector-content">
<div class="bgx-pic-toolbar">
<input
class="form-control bgx-pic-toolbar-input"
placeholder="搜索SKU/POA"
value={this.bgxCode}
onChange={(e) => this.codeChange(e.target.value)}
onkeydown={(e) => e.key === 'Enter' && this.codeChange(e.target.value)}
/>
<select
class="form-control bgx-pic-toolbar-input"
value={this.poaFilter}
placeholder="过滤POA图片"
onchange={this.poaFilterChange()}
>
<option value="">所有POA</option>
{this.poaList.map((value) => {
return (
<option value={value.code} selected={this.poaFilter === value.code}>
{value.label || value.code}
</option>
);
})}
</select>
{/* <select class='form-control bgx-pic-toolbar-input' ngModel='poaFilter' placeholder='图片类型' */}
{/* ngModelChange='loadImage($event)'> */}
{/* <option value={1}>{''}</option> */}
{/* </select> */}
<select
class="form-control bgx-pic-toolbar-input"
value={this.poaFilter}
placeholder="平台"
onchange={this.platformFilterChange()}
>
<option value="">所有平台</option>
{this.platformList.map((value) => (
<option value={value.value}>{value.label || value.value}</option>
))}
</select>
<div class="bgx-pic-toolbar-space" />
<button class="btn btn-default toolbar-select-all" onclick={this.selectAll}>
全选
</button>
</div>
<div class="bgx-pic-images">
{this.displayImage.map((item) => (
<DisplayImg item={item} imageList={this.displayImage} />
))}
</div>
</div>
</div>
);
}
private sizeCheck(value: ImageInfo) {
if (
this.bgxMaxImageSize != null &&
value.height > this.bgxMaxImageSize &&
value.width > this.bgxMaxImageSize
) {
alert(`请选择长宽小于 ${this.bgxMaxImageSize} 的图片`);
return false;
}
if (
this.bgxMinImageSize != null &&
value.height < this.bgxMinImageSize &&
value.width < this.bgxMinImageSize
) {
alert(`请选择长宽大于 ${this.bgxMinImageSize} 的图片`);
return false;
}
if (this.bgxMustSquare && value.height !== value.width) {
alert(`请选择长度宽度相等的图片`);
return false;
}
return true;
}
}
// 挂载为jquery插件
mountModal({
name: 'pictureSelector',
title: '图片选择',
content: PictureSelectorComponent,
style: 'width: 1000px;',
onOk(instance: PictureSelectorComponent) {
instance?.bgxOnOk(
Object.keys(instance.selectedImg).reduce((obj, key) => {
obj[key] = instance.selectedImg[key].map((value) => value.url);
return obj;
}, {}),
);
},
}); | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/extensionsMappers";
import * as Parameters from "../models/parameters";
import { HDInsightManagementClientContext } from "../hDInsightManagementClientContext";
/** Class representing a Extensions. */
export class Extensions {
private readonly client: HDInsightManagementClientContext;
/**
* Create a Extensions.
* @param {HDInsightManagementClientContext} client Reference to the service client.
*/
constructor(client: HDInsightManagementClientContext) {
this.client = client;
}
/**
* Enables the Operations Management Suite (OMS) on the HDInsight cluster.
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param parameters The Operations Management Suite (OMS) workspace parameters.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
enableMonitoring(
resourceGroupName: string,
clusterName: string,
parameters: Models.ClusterMonitoringRequest,
options?: msRest.RequestOptionsBase
): Promise<msRest.RestResponse> {
return this.beginEnableMonitoring(
resourceGroupName,
clusterName,
parameters,
options
).then((lroPoller) => lroPoller.pollUntilFinished());
}
/**
* Gets the status of Operations Management Suite (OMS) on the HDInsight cluster.
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param [options] The optional parameters
* @returns Promise<Models.ExtensionsGetMonitoringStatusResponse>
*/
getMonitoringStatus(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<Models.ExtensionsGetMonitoringStatusResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param callback The callback
*/
getMonitoringStatus(
resourceGroupName: string,
clusterName: string,
callback: msRest.ServiceCallback<Models.ClusterMonitoringResponse>
): void;
/**
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param options The optional parameters
* @param callback The callback
*/
getMonitoringStatus(
resourceGroupName: string,
clusterName: string,
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.ClusterMonitoringResponse>
): void;
getMonitoringStatus(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ClusterMonitoringResponse>,
callback?: msRest.ServiceCallback<Models.ClusterMonitoringResponse>
): Promise<Models.ExtensionsGetMonitoringStatusResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
clusterName,
options
},
getMonitoringStatusOperationSpec,
callback
) as Promise<Models.ExtensionsGetMonitoringStatusResponse>;
}
/**
* Disables the Operations Management Suite (OMS) on the HDInsight cluster.
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
disableMonitoring(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<msRest.RestResponse> {
return this.beginDisableMonitoring(resourceGroupName, clusterName, options).then((lroPoller) =>
lroPoller.pollUntilFinished()
);
}
/**
* Enables the Azure Monitor on the HDInsight cluster.
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param parameters The Log Analytics workspace parameters.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
enableAzureMonitor(
resourceGroupName: string,
clusterName: string,
parameters: Models.AzureMonitorRequest,
options?: msRest.RequestOptionsBase
): Promise<msRest.RestResponse> {
return this.beginEnableAzureMonitor(
resourceGroupName,
clusterName,
parameters,
options
).then((lroPoller) => lroPoller.pollUntilFinished());
}
/**
* Gets the status of Azure Monitor on the HDInsight cluster.
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param [options] The optional parameters
* @returns Promise<Models.ExtensionsGetAzureMonitorStatusResponse>
*/
getAzureMonitorStatus(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<Models.ExtensionsGetAzureMonitorStatusResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param callback The callback
*/
getAzureMonitorStatus(
resourceGroupName: string,
clusterName: string,
callback: msRest.ServiceCallback<Models.AzureMonitorResponse>
): void;
/**
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param options The optional parameters
* @param callback The callback
*/
getAzureMonitorStatus(
resourceGroupName: string,
clusterName: string,
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.AzureMonitorResponse>
): void;
getAzureMonitorStatus(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AzureMonitorResponse>,
callback?: msRest.ServiceCallback<Models.AzureMonitorResponse>
): Promise<Models.ExtensionsGetAzureMonitorStatusResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
clusterName,
options
},
getAzureMonitorStatusOperationSpec,
callback
) as Promise<Models.ExtensionsGetAzureMonitorStatusResponse>;
}
/**
* Disables the Azure Monitor on the HDInsight cluster.
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
disableAzureMonitor(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<msRest.RestResponse> {
return this.beginDisableAzureMonitor(
resourceGroupName,
clusterName,
options
).then((lroPoller) => lroPoller.pollUntilFinished());
}
/**
* Creates an HDInsight cluster extension.
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param extensionName The name of the cluster extension.
* @param parameters The cluster extensions create request.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
create(
resourceGroupName: string,
clusterName: string,
extensionName: string,
parameters: Models.Extension,
options?: msRest.RequestOptionsBase
): Promise<msRest.RestResponse> {
return this.beginCreate(
resourceGroupName,
clusterName,
extensionName,
parameters,
options
).then((lroPoller) => lroPoller.pollUntilFinished());
}
/**
* Gets the extension properties for the specified HDInsight cluster extension.
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param extensionName The name of the cluster extension.
* @param [options] The optional parameters
* @returns Promise<Models.ExtensionsGetResponse>
*/
get(
resourceGroupName: string,
clusterName: string,
extensionName: string,
options?: msRest.RequestOptionsBase
): Promise<Models.ExtensionsGetResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param extensionName The name of the cluster extension.
* @param callback The callback
*/
get(
resourceGroupName: string,
clusterName: string,
extensionName: string,
callback: msRest.ServiceCallback<Models.ClusterMonitoringResponse>
): void;
/**
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param extensionName The name of the cluster extension.
* @param options The optional parameters
* @param callback The callback
*/
get(
resourceGroupName: string,
clusterName: string,
extensionName: string,
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.ClusterMonitoringResponse>
): void;
get(
resourceGroupName: string,
clusterName: string,
extensionName: string,
options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ClusterMonitoringResponse>,
callback?: msRest.ServiceCallback<Models.ClusterMonitoringResponse>
): Promise<Models.ExtensionsGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
clusterName,
extensionName,
options
},
getOperationSpec,
callback
) as Promise<Models.ExtensionsGetResponse>;
}
/**
* Deletes the specified extension for HDInsight cluster.
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param extensionName The name of the cluster extension.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(
resourceGroupName: string,
clusterName: string,
extensionName: string,
options?: msRest.RequestOptionsBase
): Promise<msRest.RestResponse> {
return this.beginDeleteMethod(
resourceGroupName,
clusterName,
extensionName,
options
).then((lroPoller) => lroPoller.pollUntilFinished());
}
/**
* Gets the async operation status.
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param extensionName The name of the cluster extension.
* @param operationId The long running operation id.
* @param [options] The optional parameters
* @returns Promise<Models.ExtensionsGetAzureAsyncOperationStatusResponse>
*/
getAzureAsyncOperationStatus(
resourceGroupName: string,
clusterName: string,
extensionName: string,
operationId: string,
options?: msRest.RequestOptionsBase
): Promise<Models.ExtensionsGetAzureAsyncOperationStatusResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param extensionName The name of the cluster extension.
* @param operationId The long running operation id.
* @param callback The callback
*/
getAzureAsyncOperationStatus(
resourceGroupName: string,
clusterName: string,
extensionName: string,
operationId: string,
callback: msRest.ServiceCallback<Models.AsyncOperationResult>
): void;
/**
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param extensionName The name of the cluster extension.
* @param operationId The long running operation id.
* @param options The optional parameters
* @param callback The callback
*/
getAzureAsyncOperationStatus(
resourceGroupName: string,
clusterName: string,
extensionName: string,
operationId: string,
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.AsyncOperationResult>
): void;
getAzureAsyncOperationStatus(
resourceGroupName: string,
clusterName: string,
extensionName: string,
operationId: string,
options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AsyncOperationResult>,
callback?: msRest.ServiceCallback<Models.AsyncOperationResult>
): Promise<Models.ExtensionsGetAzureAsyncOperationStatusResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
clusterName,
extensionName,
operationId,
options
},
getAzureAsyncOperationStatusOperationSpec,
callback
) as Promise<Models.ExtensionsGetAzureAsyncOperationStatusResponse>;
}
/**
* Enables the Operations Management Suite (OMS) on the HDInsight cluster.
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param parameters The Operations Management Suite (OMS) workspace parameters.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginEnableMonitoring(
resourceGroupName: string,
clusterName: string,
parameters: Models.ClusterMonitoringRequest,
options?: msRest.RequestOptionsBase
): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
parameters,
options
},
beginEnableMonitoringOperationSpec,
options
);
}
/**
* Disables the Operations Management Suite (OMS) on the HDInsight cluster.
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDisableMonitoring(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
options
},
beginDisableMonitoringOperationSpec,
options
);
}
/**
* Enables the Azure Monitor on the HDInsight cluster.
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param parameters The Log Analytics workspace parameters.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginEnableAzureMonitor(
resourceGroupName: string,
clusterName: string,
parameters: Models.AzureMonitorRequest,
options?: msRest.RequestOptionsBase
): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
parameters,
options
},
beginEnableAzureMonitorOperationSpec,
options
);
}
/**
* Disables the Azure Monitor on the HDInsight cluster.
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDisableAzureMonitor(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
options
},
beginDisableAzureMonitorOperationSpec,
options
);
}
/**
* Creates an HDInsight cluster extension.
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param extensionName The name of the cluster extension.
* @param parameters The cluster extensions create request.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreate(
resourceGroupName: string,
clusterName: string,
extensionName: string,
parameters: Models.Extension,
options?: msRest.RequestOptionsBase
): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
extensionName,
parameters,
options
},
beginCreateOperationSpec,
options
);
}
/**
* Deletes the specified extension for HDInsight cluster.
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster.
* @param extensionName The name of the cluster extension.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(
resourceGroupName: string,
clusterName: string,
extensionName: string,
options?: msRest.RequestOptionsBase
): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
extensionName,
options
},
beginDeleteMethodOperationSpec,
options
);
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const getMonitoringStatusOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/clustermonitoring",
urlParameters: [Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {
bodyMapper: Mappers.ClusterMonitoringResponse
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getAzureMonitorStatusOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/azureMonitor",
urlParameters: [Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {
bodyMapper: Mappers.AzureMonitorResponse
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/{extensionName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.clusterName,
Parameters.extensionName
],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {
bodyMapper: Mappers.ClusterMonitoringResponse
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getAzureAsyncOperationStatusOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/{extensionName}/azureAsyncOperations/{operationId}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.clusterName,
Parameters.extensionName,
Parameters.operationId
],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {
bodyMapper: Mappers.AsyncOperationResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const beginEnableMonitoringOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/clustermonitoring",
urlParameters: [Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.ClusterMonitoringRequest,
required: true
}
},
responses: {
200: {},
202: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const beginDisableMonitoringOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/clustermonitoring",
urlParameters: [Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const beginEnableAzureMonitorOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/azureMonitor",
urlParameters: [Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.AzureMonitorRequest,
required: true
}
},
responses: {
200: {},
202: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const beginDisableAzureMonitorOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/azureMonitor",
urlParameters: [Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const beginCreateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/{extensionName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.clusterName,
Parameters.extensionName
],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.Extension,
required: true
}
},
responses: {
200: {},
202: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/{extensionName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.clusterName,
Parameters.extensionName
],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
import MiniProgram from 'miniprogram-automator/out/MiniProgram'
import Page from 'miniprogram-automator/out/Page'
import automator from 'miniprogram-automator'
import { resolve } from 'path'
import {
WxPerformanceData,
WxPerformanceDataType,
WxPerformanceItemType,
WxPerformanceItem
} from '../../../packages/wx-mini-performance/src/types'
const APPID = 'a1329cc0-563b-11eb-98fe-259847d73cdd'
const WIFI = ['wifi', '2g', '3g', '4g', '5g', 'unknown', 'none']
const TEMP_FILE = 'http://tmp/2rPKfFSlT4jcf43b31be29a47fecd8890b363180b043.jpg'
describe('Min e2e:', () => {
const timeout = 60000 // 打开开发工具较慢
const waitFor = 1000
let _miniProgram: MiniProgram
let _page: Page
async function getData(): Promise<WxPerformanceData[][]> {
return await _miniProgram.evaluate(() => {
return wx['__MITO_MINI_PERFORMANCE__'].data as WxPerformanceData[][]
})
}
async function reset() {
return await _miniProgram.evaluate(() => {
wx['__MITO_MINI_PERFORMANCE__'].data = []
return
})
}
/**
* 请确保本地安装了开发工具并打开了安全端口
* 如何打开端口
* 微信开发工具设置 -> 安全设置 -> 安全 -> 打开服务端口
*/
beforeAll(async () => {
try {
const miniProgram: MiniProgram = await automator.launch({
projectPath: resolve(__dirname, '../../../examples/MiniPerformance')
})
_miniProgram = miniProgram
const page: Page = await miniProgram.currentPage()
_page = page
} catch (err) {
console.warn('err = ', err)
}
}, timeout)
it(
'The Performance Data in Wx_Launch include Wx_Lifestyle, WX_PERFORMANCE and WxCustomPaint',
async (done) => {
await _page.waitFor(waitFor)
await _page.waitFor(async () => {
return (await getData()).length > 0
})
// Wx_Lifestyle
const data: WxPerformanceData[][] = await getData()
const launchData = data[0][0]
expect(launchData).toHaveProperty('timestamp')
expect(launchData).toHaveProperty('uuid')
expect(launchData).toHaveProperty('systemInfo')
expect(launchData).toHaveProperty('deviceId')
expect(launchData).toHaveProperty('item')
expect(launchData).toHaveProperty('page')
expect(launchData).toHaveProperty('wxLaunch')
expect(launchData.appId).toBe(APPID)
expect(launchData.type).toBe(WxPerformanceDataType.WX_LIFE_STYLE)
expect(WIFI.some((x) => x === launchData.networkType)).toBeTruthy()
const launchItem = launchData.item
expect(Array.isArray(launchItem)).toBeTruthy()
expect(launchItem[0]).toHaveProperty('timestamp')
expect((launchItem[0] as WxPerformanceItem).itemType).toBe(WxPerformanceItemType.AppOnLaunch)
const wxShowData = data[1][0]
expect(wxShowData.type).toBe(WxPerformanceDataType.WX_LIFE_STYLE)
const wxShowItem = wxShowData.item
expect((wxShowItem[0] as WxPerformanceItem).itemType).toBe(WxPerformanceItemType.AppOnShow)
const wxLoadData = data[2][0]
expect(wxLoadData.type).toBe(WxPerformanceDataType.WX_LIFE_STYLE)
const wxLoadItem = wxLoadData.item
expect((wxLoadItem[0] as WxPerformanceItem).itemType).toBe(WxPerformanceItemType.PageOnLoad)
const wxReadyData = data[3][0]
expect(wxReadyData.type).toBe(WxPerformanceDataType.WX_LIFE_STYLE)
const wxReadyItem = wxReadyData.item
expect((wxReadyItem[0] as WxPerformanceItem).itemType).toBe(WxPerformanceItemType.PageOnReady)
// WX_PERFORMANCE
const performanceData = data[4][0]
expect(performanceData.type).toBe(WxPerformanceDataType.WX_PERFORMANCE)
const performanceItem = performanceData.item
expect(Array.isArray(performanceItem)).toBeTruthy()
expect(performanceItem.length).toBe(3)
expect((performanceItem[0] as WxPerformanceItem).itemType).toBe(WxPerformanceItemType.Performance)
expect((performanceItem[1] as WxPerformanceItem).itemType).toBe(WxPerformanceItemType.Performance)
expect((performanceItem[2] as WxPerformanceItem).itemType).toBe(WxPerformanceItemType.Performance)
// WxCustomPaint
const wxCustomPaintData = data[5][0]
expect(wxCustomPaintData.type).toBe(WxPerformanceDataType.WX_LIFE_STYLE)
const wxCustomPaintItem = wxCustomPaintData.item
expect((wxCustomPaintItem[0] as WxPerformanceItem).itemType).toBe(WxPerformanceItemType.WxCustomPaint)
expect(wxCustomPaintItem[0] as WxPerformanceItem).toHaveProperty('duration')
expect(wxCustomPaintItem[0] as WxPerformanceItem).toHaveProperty('navigationStart')
expect(wxCustomPaintItem[0] as WxPerformanceItem).toHaveProperty('timestamp')
done()
},
timeout
)
it(
'The Performance Data on Click',
async (done) => {
await reset()
const element = await _page.$('#click-btn')
await element.tap()
await _page.waitFor(async () => {
return (await getData()).length > 0
})
const data: WxPerformanceData[][] = await getData()
const clickData = data[0][0]
expect(clickData).toHaveProperty('timestamp')
expect(clickData).toHaveProperty('uuid')
expect(clickData).toHaveProperty('systemInfo')
expect(clickData).toHaveProperty('deviceId')
expect(clickData).toHaveProperty('item')
expect(clickData).toHaveProperty('page')
expect(clickData).toHaveProperty('wxLaunch')
expect(clickData.appId).toBe(APPID)
// expect(clickData.page).toBe('pages/index/index?')
expect(clickData.type).toBe(WxPerformanceDataType.WX_USER_ACTION)
expect(WIFI.some((x) => x === clickData.networkType)).toBeTruthy()
const clickItem = clickData.item
expect(Array.isArray(clickItem)).toBeTruthy()
expect(clickItem[0]).toHaveProperty('timestamp')
expect((clickItem[0] as WxPerformanceItem).itemType).toBe(WxPerformanceItemType.UserTap)
done()
},
timeout
)
it(
'The Performance Data on Request',
async (done) => {
await reset()
const element = await _page.$('#click-request-btn')
await element.tap()
await _page.waitFor(async () => {
return (await getData()).length > 0
})
const data: WxPerformanceData[][] = await getData()
const requestData = data[0][0]
expect(requestData).toHaveProperty('timestamp')
expect(requestData).toHaveProperty('uuid')
expect(requestData).toHaveProperty('systemInfo')
expect(requestData).toHaveProperty('deviceId')
expect(requestData).toHaveProperty('item')
expect(requestData).toHaveProperty('page')
expect(requestData).toHaveProperty('wxLaunch')
expect(requestData.appId).toBe(APPID)
expect(requestData.page).toBe('pages/index/index?')
expect(requestData.type).toBe(WxPerformanceDataType.WX_NETWORK)
expect(WIFI.some((x) => x === requestData.networkType)).toBeTruthy()
const requestItem = requestData.item
expect(Array.isArray(requestItem)).toBeTruthy()
expect(requestItem[0]).toHaveProperty('startTime')
expect(requestItem[0]).toHaveProperty('endTime')
expect(requestItem[0]).toHaveProperty('url')
expect(requestItem[0]).toHaveProperty('status')
expect(requestItem[0]).toHaveProperty('header')
expect(requestItem[0]).toHaveProperty('errMsg')
expect((requestItem[0] as WxPerformanceItem).method).toBe('GET')
done()
},
timeout
)
it(
'The Performance Data on Download File',
async (done) => {
await reset()
const element = await _page.$('#click-down-file-btn')
await element.tap()
await _page.waitFor(async () => {
return (await getData()).length > 0
})
const data: WxPerformanceData[][] = await getData()
const downFileData = data[0][0]
expect(downFileData).toHaveProperty('timestamp')
expect(downFileData).toHaveProperty('uuid')
expect(downFileData).toHaveProperty('systemInfo')
expect(downFileData).toHaveProperty('deviceId')
expect(downFileData).toHaveProperty('item')
expect(downFileData).toHaveProperty('page')
expect(downFileData).toHaveProperty('wxLaunch')
expect(downFileData.appId).toBe(APPID)
expect(downFileData.page).toBe('pages/index/index?')
expect(downFileData.type).toBe(WxPerformanceDataType.WX_NETWORK)
expect(WIFI.some((x) => x === downFileData.networkType)).toBeTruthy()
const downFileItem = downFileData.item
expect(Array.isArray(downFileItem)).toBeTruthy()
expect(downFileItem[0]).toHaveProperty('startTime')
expect(downFileItem[0]).toHaveProperty('endTime')
expect(downFileItem[0]).toHaveProperty('url')
expect(downFileItem[0]).toHaveProperty('header')
expect(downFileItem[0]).toHaveProperty('errMsg')
// expect((downFileItem[0] as WxPerformanceItem).method).toBe('GET')
expect((downFileItem[0] as WxPerformanceItem).status).toBe(200)
done()
},
timeout
)
it(
'The Performance Data on Upload File',
async (done) => {
await reset()
await _miniProgram.mockWxMethod('chooseImage', {
tempFilePaths: [TEMP_FILE]
})
const element = await _page.$('#click-up-file-btn')
await element.tap()
await _page.waitFor(async () => {
return (await getData()).length > 0
})
const data: WxPerformanceData[][] = await getData()
const upFileData = data[0][0]
expect(upFileData).toHaveProperty('timestamp')
expect(upFileData).toHaveProperty('uuid')
expect(upFileData).toHaveProperty('systemInfo')
expect(upFileData).toHaveProperty('deviceId')
expect(upFileData).toHaveProperty('item')
expect(upFileData).toHaveProperty('page')
expect(upFileData).toHaveProperty('wxLaunch')
expect(upFileData.appId).toBe(APPID)
expect(upFileData.page).toBe('pages/index/index?')
expect(upFileData.type).toBe(WxPerformanceDataType.WX_NETWORK)
expect(WIFI.some((x) => x === upFileData.networkType)).toBeTruthy()
const upFileItem = upFileData.item
expect(Array.isArray(upFileItem)).toBeTruthy()
expect(upFileItem[0]).toHaveProperty('startTime')
expect(upFileItem[0]).toHaveProperty('endTime')
expect(upFileItem[0]).toHaveProperty('header')
expect(upFileItem[0]).toHaveProperty('errMsg')
expect(upFileItem[0]).toHaveProperty('filePath')
expect((upFileItem[0] as WxPerformanceItem).status).toBe(0)
expect((upFileItem[0] as WxPerformanceItem).filePath).toBe(TEMP_FILE)
done()
},
timeout
)
it(
'The Performance Data on Navigate',
async (done) => {
await reset()
const element = await _page.$('#navigate-btn')
await element.tap()
await _page.waitFor(async () => {
return (await getData()).length > 0
})
await _page.waitFor(waitFor)
const data: WxPerformanceData[][] = await getData()
// Wx_Lifestyle
const wxLoadData = data[0][0]
expect(wxLoadData.type).toBe(WxPerformanceDataType.WX_LIFE_STYLE)
const wxLoadItem = wxLoadData.item
expect((wxLoadItem[0] as WxPerformanceItem).itemType).toBe(WxPerformanceItemType.PageOnLoad)
const wxReadyData = data[1][0]
expect(wxReadyData.type).toBe(WxPerformanceDataType.WX_LIFE_STYLE)
const wxReadyItem = wxReadyData.item
expect((wxReadyItem[0] as WxPerformanceItem).itemType).toBe(WxPerformanceItemType.PageOnReady)
// WX_PERFORMANCE
const performanceData = data[2][0]
expect(performanceData.type).toBe(WxPerformanceDataType.WX_PERFORMANCE)
expect(performanceData.page).toBe('pages/test/test?')
const performanceItem = performanceData.item
expect(Array.isArray(performanceItem)).toBeTruthy()
expect(performanceItem.length).toBe(2)
expect((performanceItem[0] as WxPerformanceItem).itemType).toBe(WxPerformanceItemType.Performance)
expect((performanceItem[1] as WxPerformanceItem).itemType).toBe(WxPerformanceItemType.Performance)
done()
},
timeout
)
}) | the_stack |
import {
Program,
EmbeddedCode,
CodeText,
JSXElement,
JSXElementKind,
JSXText,
JSXComment,
JSXInsert,
JSXField,
JSXStaticField,
JSXDynamicField,
JSXStyleProperty,
JSXFunction,
JSXContent,
JSXSpread,
CodeSegment
} from './AST';
import { LOC } from './parse';
import { locationMark } from './sourcemap';
import { Params } from './compile';
import { getFieldData, FieldFlags } from './fieldData';
export { codeGen, codeStr };
// pre-compiled regular expressions
const rx = {
backslashes : /\\/g,
newlines : /\r?\n/g,
hasParen : /\(/,
loneFunction: /^function |^\(\w*\) =>|^\w+ =>/,
endsInParen : /\)\s*$/,
nonIdChars : /[^a-zA-Z0-9]/g,
doubleQuotes: /"/g,
indent : /\n(?=[^\n]+$)([ \t]*)/
};
class DOMExpression {
constructor(
public readonly ids : string[],
public readonly statements : string[],
public readonly computations : Computation[]
) { }
}
class Computation {
constructor(
public readonly statements : string[],
public readonly loc : LOC,
public readonly stateVar : string | null,
public readonly seed : string | null,
) { }
}
class SubComponent {
constructor(
public readonly name : string,
public readonly refs : string[],
public readonly fns : string[],
public readonly properties : (string | { [ name : string ] : string })[],
public readonly children : string[],
public readonly loc : LOC
) { }
}
const codeGen = (ctl : Program, opts : Params) => {
const compileSegments = (node : Program | EmbeddedCode) => {
return node.segments.reduce((res, s) => res + compileSegment(s, res), "");
},
compileSegment = (node : CodeSegment, previousCode : string) =>
node.type === CodeText ? compileCodeText(node) : compileJSXElement(node, indent(previousCode)),
compileCodeText = (node : CodeText) =>
markBlockLocs(node.text, node.loc, opts),
compileJSXElement = (node : JSXElement, indent : Indents) : string => {
const code =
node.kind === JSXElementKind.SubComponent
? compileSubComponent(node, indent)
: compileHtmlElement(node, indent);
return markLoc(code, node.loc, opts);
},
compileSubComponent = (node : JSXElement, indent : Indents) : string => {
return emitSubComponent(buildSubComponent(node), indent);
},
compileHtmlElement = (node : JSXElement, indent : Indents) : string => {
const svg = node.kind === JSXElementKind.SVG;
return (
// optimization: don't need IIFE for simple single nodes
(node.fields.length === 0 && node.functions.length === 0 && node.content.length === 0) ?
node.references.map(r => compileSegments(r.code) + ' = ').join('')
+ `Surplus.create${svg ? 'Svg' : ''}Element('${node.tag}', null, null)` :
// optimization: don't need IIFE for simple single nodes with a single class attribute
(node.fields.length === 1
&& isStaticClassField(node.fields[0], svg)
&& node.functions.length === 0
&& node.content.length === 0) ?
node.references.map(r => compileSegments(r.code) + ' = ').join('')
+ `Surplus.create${svg ? 'Svg' : ''}Element(${codeStr(node.tag)}, ${(node.fields[0] as JSXStaticField).value}, null)` :
emitDOMExpression(buildDOMExpression(node), indent)
);
},
buildSubComponent = (node : JSXElement) => {
const
refs = node.references.map(r => compileSegments(r.code)),
fns = node.functions.map(r => compileSegments(r.code)),
// group successive properties into property objects, but spreads stand alone
// e.g. a="1" b={foo} {...spread} c="3" gets combined into [{a: "1", b: foo}, spread, {c: "3"}]
properties = node.fields.reduce((props : (string | { [name : string] : string })[], p) => {
const lastSegment = props.length > 0 ? props[props.length - 1] : null,
value = p.type === JSXStaticField ? p.value : compileSegments(p.code);
if (p.type === JSXSpread) {
props.push(value);
} else if (lastSegment === null
|| typeof lastSegment === 'string'
|| (p.type === JSXStyleProperty && lastSegment["style"])
) {
props.push({ [p.name]: value });
} else {
lastSegment[p.name] = value;
}
return props;
}, []),
children = node.content.map(c =>
c.type === JSXElement ? compileJSXElement(c, indent("")) :
c.type === JSXText ? codeStr(c.text) :
c.type === JSXInsert ? compileSegments(c.code) :
`document.createComment(${codeStr(c.text)})`
);
return new SubComponent(node.tag, refs, fns, properties, children, node.loc);
},
emitSubComponent = (sub : SubComponent, indent : Indents) => {
const { nl, nli, nlii } = indent;
// build properties expression
const
// convert children to an array expression
children = sub.children.length === 0 ? null :
sub.children.length === 1 ? sub.children[0] :
'[' + nlii
+ sub.children.join(',' + nlii) + nli
+ ']',
lastProperty = sub.properties.length === 0 ? null : sub.properties[sub.properties.length - 1],
// if there are any children, add them to (or add a) last object
propertiesWithChildren =
children === null ? sub.properties :
lastProperty === null || typeof lastProperty === 'string' ?
// add a new property object to hold children
[...sub.properties, { children: children }] :
// add children to last property object
[...sub.properties.slice(0, sub.properties.length - 1), { ...lastProperty, children: children }],
// if we're going to be Object.assign'ing to the first object, it needs to be one we made, not a spread
propertiesWithInitialObject =
propertiesWithChildren.length === 0 || (propertiesWithChildren.length > 1 && typeof propertiesWithChildren[0] === 'string')
? [ {}, ...propertiesWithChildren ]
: propertiesWithChildren,
propertyExprs = propertiesWithInitialObject.map(obj =>
typeof obj === 'string' ? obj :
'{' + Object.keys(obj).map(p => `${nli}${codeStr(p)}: ${obj[p]}`).join(',') + nl + '}'
),
properties = propertyExprs.length === 1 ? propertyExprs[0] :
`Object.assign(${propertyExprs.join(', ')})`;
// main call to sub-component
let expr = `${sub.name}(${properties})`;
// ref assignments
if (sub.refs.length > 0) {
expr = sub.refs.map(r => r + " = ").join("") + expr;
}
// build computations for fns
if (sub.fns.length > 0) {
const comps = sub.fns.map(fn => new Computation([`(${fn})(__, __state);`], sub.loc, '__state', null));
expr = `(function (__) {${
nli}var __ = ${expr};${
nli}${comps.map(comp => emitComputation(comp, indent)).join(nli)}${
nli}return __;${
nl}})()`;
}
return expr;
},
buildDOMExpression = (top : JSXElement) => {
const ids = [] as string[],
statements = [] as string[],
computations = [] as Computation[];
const buildHtmlElement = (node : JSXElement, parent : string, n : number) => {
const { tag, fields, references, functions, content, loc } = node;
if (node.kind === JSXElementKind.SubComponent) {
buildInsertedSubComponent(node, parent, n);
} else {
const
id = addId(parent, tag, n),
svg = node.kind === JSXElementKind.SVG,
fieldExprs = fields.map(p => p.type === JSXStaticField ? '' : compileSegments(p.code)),
spreads = fields.filter(p => p.type === JSXSpread || p.type === JSXStyleProperty),
classField = spreads.length === 0 && fields.filter(p => isStaticClassField(p, svg))[0] as JSXStaticField || null,
fieldsDynamic = fieldExprs.some(e => !noApparentSignals(e)),
fieldStmts = fields.map((f, i) =>
f === classField ? '' :
f.type === JSXStaticField ? buildField(id, f, f.value, node) :
f.type === JSXDynamicField ? buildField(id, f, fieldExprs[i], node) :
f.type === JSXStyleProperty ? buildStyle(f, id, fieldExprs[i], fieldsDynamic, spreads) :
buildSpread(id, fieldExprs[i], svg)
).filter(s => s !== ''),
refStmts = references.map(r => compileSegments(r.code) + ' = ').join('');
addStatement(`${id} = ${refStmts}Surplus.create${svg ? 'Svg' : ''}Element(${codeStr(tag)}, ${classField && classField.value}, ${parent || null});`);
if (!fieldsDynamic) {
fieldStmts.forEach(addStatement);
}
if (content.length === 1 && content[0].type === JSXInsert) {
buildJSXContent(content[0] as JSXInsert, id);
} else {
content.forEach((c, i) => buildChild(c, id, i));
}
if (fieldsDynamic) {
addComputation(fieldStmts, null, null, loc);
}
functions.forEach(f => buildNodeFn(f, id));
}
},
buildField = (id : string, field : JSXStaticField | JSXDynamicField, expr : string, parent : JSXElement) => {
const [ name, namespace, flags ] = getFieldData(field.name, parent.kind === JSXElementKind.SVG),
type = flags & FieldFlags.Type;
return (
type === FieldFlags.Property ? buildProperty(id, name, namespace, expr) :
type === FieldFlags.Attribute ? buildAttribute(id, name, namespace, expr) :
''
);
},
buildProperty = (id : string, name : string, namespace : string | null, expr : string) =>
namespace ? `${id}.${namespace}.${name} = ${expr};` : `${id}.${name} = ${expr};`,
buildAttribute = (id : string, name : string, namespace : string | null, expr : string) =>
namespace ? `Surplus.setAttributeNS(${id}, ${codeStr(namespace)}, ${codeStr(name)}, ${expr});` :
`Surplus.setAttribute(${id}, ${codeStr(name)}, ${expr});`,
buildSpread = (id : string, expr : string, svg : boolean) =>
`Surplus.spread(${id}, ${expr}, ${svg});`,
buildNodeFn = (node : JSXFunction, id : string) => {
var expr = compileSegments(node.code);
addComputation([`(${expr})(${id}, __state);`], '__state', null, node.loc);
},
buildStyle = (node : JSXStyleProperty, id : string, expr : string, dynamic : boolean, spreads : JSXField[]) =>
`Surplus.assign(${id}.style, ${expr});`,
buildChild = (node : JSXContent, parent : string, n : number) =>
node.type === JSXElement ? buildHtmlElement(node, parent, n) :
node.type === JSXComment ? buildHtmlComment(node, parent) :
node.type === JSXText ? buildJSXText(node, parent, n) :
buildJSXInsert(node, parent, n),
buildInsertedSubComponent = (node : JSXElement, parent : string, n : number) =>
buildJSXInsert({ type: JSXInsert, code: { type: EmbeddedCode, segments: [node] }, loc: node.loc }, parent, n),
buildHtmlComment = (node : JSXComment, parent : string) =>
addStatement(`Surplus.createComment(${codeStr(node.text)}, ${parent})`),
buildJSXText = (node : JSXText, parent : string, n : number) =>
addStatement(`Surplus.createTextNode(${codeStr(node.text)}, ${parent})`),
buildJSXInsert = (node : JSXInsert, parent : string, n : number) => {
const id = addId(parent, 'insert', n),
ins = compileSegments(node.code),
range = `{ start: ${id}, end: ${id} }`;
addStatement(`${id} = Surplus.createTextNode('', ${parent})`);
addComputation([`Surplus.insert(__range, ${ins});`], "__range", range, node.loc);
},
buildJSXContent = (node : JSXInsert, parent : string) => {
const content = compileSegments(node.code),
dynamic = !noApparentSignals(content);
if (dynamic) addComputation([`Surplus.content(${parent}, ${content}, __current);`], '__current', "''", node.loc);
else addStatement(`Surplus.content(${parent}, ${content}, "");`);
},
addId = (parent : string, tag : string, n : number) => {
tag = tag.replace(rx.nonIdChars, '_');
const id = parent === '' ? '__' : parent + (parent[parent.length - 1] === '_' ? '' : '_') + tag + (n + 1);
ids.push(id);
return id;
},
addStatement = (stmt : string) =>
statements.push(stmt),
addComputation = (body : string[], stateVar : string | null, seed : string | null, loc : LOC) => {
computations.push(new Computation(body, loc, stateVar, seed));
}
buildHtmlElement(top, '', 0);
return new DOMExpression(ids, statements, computations);
},
emitDOMExpression = (code : DOMExpression, indent : Indents) => {
const { nl, nli, nlii } = indent;
return '(function () {' + nli
+ 'var ' + code.ids.join(', ') + ';' + nli
+ code.statements.join(nli) + nli
+ code.computations.map(comp => emitComputation(comp, indent))
.join(nli) + (code.computations.length === 0 ? '' : nli)
+ 'return __;' + nl
+ '})()';
},
emitComputation = (comp : Computation, { nli, nlii } : Indents) => {
const { statements, loc, stateVar, seed } = comp;
if (stateVar) statements[statements.length - 1] = 'return ' + statements[statements.length - 1];
const body = statements.length === 1 ? (' ' + statements[0] + ' ') : (nlii + statements.join(nlii) + nli),
code = `Surplus.S.effect(function (${stateVar || ''}) {${body}}${seed !== null ? `, ${seed}` : ''});`;
return markLoc(code, loc, opts);
};
return compileSegments(ctl);
};
const
isStaticClassField = (p : JSXField, svg : boolean) =>
p.type === JSXStaticField && getFieldData(p.name, svg)[0] === (svg ? 'class' : 'className'),
noApparentSignals = (code : string) =>
!rx.hasParen.test(code) || (rx.loneFunction.test(code) && !rx.endsInParen.test(code)),
indent = (previousCode : string) : Indents => {
const m = rx.indent.exec(previousCode),
pad = m ? m[1] : '',
nl = "\r\n" + pad,
nli = nl + ' ',
nlii = nli + ' ';
return { nl, nli, nlii };
},
codeStr = (str : string) =>
'"' +
str.replace(rx.backslashes, "\\\\")
.replace(rx.doubleQuotes, "\\\"")
.replace(rx.newlines, "\\n") +
'"';
interface Indents { nl : string, nli : string, nlii : string }
const
markLoc = (str : string, loc : LOC, opts : Params) =>
opts.sourcemap ? locationMark(loc) + str : str,
markBlockLocs = (str : string, loc : LOC, opts : Params) => {
if (!opts.sourcemap) return str;
let lines = str.split('\n'),
offset = 0;
for (let i = 1; i < lines.length; i++) {
let line = lines[i];
offset += line.length;
let lineloc = { line: loc.line + i, col: 0, pos: loc.pos + offset + i };
lines[i] = locationMark(lineloc) + line;
}
return locationMark(loc) + lines.join('\n');
}; | the_stack |
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
/** References another document, used as a foreign key */
Reference: any;
JSON: any;
};
export type SystemInfo = {
__typename?: 'SystemInfo';
filename: Scalars['String'];
basename: Scalars['String'];
breadcrumbs: Array<Scalars['String']>;
path: Scalars['String'];
relativePath: Scalars['String'];
extension: Scalars['String'];
template: Scalars['String'];
collection: Collection;
};
export type SystemInfoBreadcrumbsArgs = {
excludeExtension?: Maybe<Scalars['Boolean']>;
};
export type PageInfo = {
__typename?: 'PageInfo';
hasPreviousPage: Scalars['Boolean'];
hasNextPage: Scalars['Boolean'];
startCursor: Scalars['String'];
endCursor: Scalars['String'];
};
export type Node = {
id: Scalars['ID'];
};
export type Document = {
sys?: Maybe<SystemInfo>;
id: Scalars['ID'];
};
/** A relay-compliant pagination connection */
export type Connection = {
totalCount: Scalars['Int'];
};
export type Query = {
__typename?: 'Query';
getCollection: Collection;
getCollections: Array<Collection>;
node: Node;
getDocument: DocumentNode;
getDocumentList: DocumentConnection;
getThemeDocument: ThemeDocument;
getThemeList: ThemeConnection;
getPageDocument: PageDocument;
getPageList: PageConnection;
};
export type QueryGetCollectionArgs = {
collection?: Maybe<Scalars['String']>;
};
export type QueryNodeArgs = {
id?: Maybe<Scalars['String']>;
};
export type QueryGetDocumentArgs = {
collection?: Maybe<Scalars['String']>;
relativePath?: Maybe<Scalars['String']>;
};
export type QueryGetDocumentListArgs = {
before?: Maybe<Scalars['String']>;
after?: Maybe<Scalars['String']>;
first?: Maybe<Scalars['Int']>;
last?: Maybe<Scalars['Int']>;
};
export type QueryGetThemeDocumentArgs = {
relativePath?: Maybe<Scalars['String']>;
};
export type QueryGetThemeListArgs = {
before?: Maybe<Scalars['String']>;
after?: Maybe<Scalars['String']>;
first?: Maybe<Scalars['Int']>;
last?: Maybe<Scalars['Int']>;
};
export type QueryGetPageDocumentArgs = {
relativePath?: Maybe<Scalars['String']>;
};
export type QueryGetPageListArgs = {
before?: Maybe<Scalars['String']>;
after?: Maybe<Scalars['String']>;
first?: Maybe<Scalars['Int']>;
last?: Maybe<Scalars['Int']>;
};
export type DocumentConnectionEdges = {
__typename?: 'DocumentConnectionEdges';
cursor?: Maybe<Scalars['String']>;
node?: Maybe<DocumentNode>;
};
export type DocumentConnection = Connection & {
__typename?: 'DocumentConnection';
pageInfo?: Maybe<PageInfo>;
totalCount: Scalars['Int'];
edges?: Maybe<Array<Maybe<DocumentConnectionEdges>>>;
};
export type Collection = {
__typename?: 'Collection';
name: Scalars['String'];
slug: Scalars['String'];
label: Scalars['String'];
path: Scalars['String'];
format?: Maybe<Scalars['String']>;
matches?: Maybe<Scalars['String']>;
templates?: Maybe<Array<Maybe<Scalars['JSON']>>>;
fields?: Maybe<Array<Maybe<Scalars['JSON']>>>;
documents: DocumentConnection;
};
export type CollectionDocumentsArgs = {
before?: Maybe<Scalars['String']>;
after?: Maybe<Scalars['String']>;
first?: Maybe<Scalars['Int']>;
last?: Maybe<Scalars['Int']>;
};
export type DocumentNode = ThemeDocument | PageDocument;
export type Theme = {
__typename?: 'Theme';
color?: Maybe<Scalars['String']>;
btnStyle?: Maybe<Scalars['String']>;
};
export type ThemeDocument = Node & Document & {
__typename?: 'ThemeDocument';
id: Scalars['ID'];
sys: SystemInfo;
data: Theme;
form: Scalars['JSON'];
values: Scalars['JSON'];
dataJSON: Scalars['JSON'];
};
export type ThemeConnectionEdges = {
__typename?: 'ThemeConnectionEdges';
cursor?: Maybe<Scalars['String']>;
node?: Maybe<ThemeDocument>;
};
export type ThemeConnection = Connection & {
__typename?: 'ThemeConnection';
pageInfo?: Maybe<PageInfo>;
totalCount: Scalars['Int'];
edges?: Maybe<Array<Maybe<ThemeConnectionEdges>>>;
};
export type PageNavWordmarkIcon = {
__typename?: 'PageNavWordmarkIcon';
color?: Maybe<Scalars['String']>;
name?: Maybe<Scalars['String']>;
style?: Maybe<Scalars['String']>;
};
export type PageNavWordmark = {
__typename?: 'PageNavWordmark';
icon?: Maybe<PageNavWordmarkIcon>;
name?: Maybe<Scalars['String']>;
};
export type PageNavItems = {
__typename?: 'PageNavItems';
label?: Maybe<Scalars['String']>;
link?: Maybe<Scalars['String']>;
};
export type PageNav = {
__typename?: 'PageNav';
wordmark?: Maybe<PageNavWordmark>;
items?: Maybe<Array<Maybe<PageNavItems>>>;
};
export type PageBlocksHeroString = {
__typename?: 'PageBlocksHeroString';
color?: Maybe<Scalars['String']>;
};
export type PageBlocksHeroImage = {
__typename?: 'PageBlocksHeroImage';
src?: Maybe<Scalars['String']>;
alt?: Maybe<Scalars['String']>;
};
export type PageBlocksHeroActions = {
__typename?: 'PageBlocksHeroActions';
label?: Maybe<Scalars['String']>;
type?: Maybe<Scalars['String']>;
icon?: Maybe<Scalars['Boolean']>;
};
export type PageBlocksHeroStyle = {
__typename?: 'PageBlocksHeroStyle';
color?: Maybe<Scalars['String']>;
};
export type PageBlocksHero = {
__typename?: 'PageBlocksHero';
tagline?: Maybe<Scalars['String']>;
headline?: Maybe<Scalars['String']>;
paragraph?: Maybe<Scalars['String']>;
string?: Maybe<PageBlocksHeroString>;
image?: Maybe<PageBlocksHeroImage>;
actions?: Maybe<Array<Maybe<PageBlocksHeroActions>>>;
style?: Maybe<PageBlocksHeroStyle>;
};
export type PageBlocksTestimonialStyle = {
__typename?: 'PageBlocksTestimonialStyle';
color?: Maybe<Scalars['String']>;
};
export type PageBlocksTestimonial = {
__typename?: 'PageBlocksTestimonial';
quote?: Maybe<Scalars['String']>;
author?: Maybe<Scalars['String']>;
style?: Maybe<PageBlocksTestimonialStyle>;
};
export type PageBlocksFeaturesItemsIcon = {
__typename?: 'PageBlocksFeaturesItemsIcon';
color?: Maybe<Scalars['String']>;
name?: Maybe<Scalars['String']>;
style?: Maybe<Scalars['String']>;
};
export type PageBlocksFeaturesItemsActions = {
__typename?: 'PageBlocksFeaturesItemsActions';
label?: Maybe<Scalars['String']>;
type?: Maybe<Scalars['String']>;
icon?: Maybe<Scalars['Boolean']>;
};
export type PageBlocksFeaturesItems = {
__typename?: 'PageBlocksFeaturesItems';
icon?: Maybe<PageBlocksFeaturesItemsIcon>;
title?: Maybe<Scalars['String']>;
text?: Maybe<Scalars['String']>;
actions?: Maybe<Array<Maybe<PageBlocksFeaturesItemsActions>>>;
};
export type PageBlocksFeaturesStyle = {
__typename?: 'PageBlocksFeaturesStyle';
color?: Maybe<Scalars['String']>;
};
export type PageBlocksFeatures = {
__typename?: 'PageBlocksFeatures';
items?: Maybe<Array<Maybe<PageBlocksFeaturesItems>>>;
style?: Maybe<PageBlocksFeaturesStyle>;
};
export type PageBlocks = PageBlocksHero | PageBlocksTestimonial | PageBlocksFeatures;
export type PageNavlistNavItems = {
__typename?: 'PageNavlistNavItems';
label?: Maybe<Scalars['String']>;
link?: Maybe<Scalars['String']>;
};
export type PageNavlistNav = {
__typename?: 'PageNavlistNav';
title?: Maybe<Scalars['String']>;
items?: Maybe<Array<Maybe<PageNavlistNavItems>>>;
};
export type PageNavlist = PageNavlistNav;
export type PageFooterSocial = {
__typename?: 'PageFooterSocial';
facebook?: Maybe<Scalars['String']>;
twitter?: Maybe<Scalars['String']>;
instagram?: Maybe<Scalars['String']>;
github?: Maybe<Scalars['String']>;
};
export type PageFooter = {
__typename?: 'PageFooter';
social?: Maybe<PageFooterSocial>;
};
export type Page = {
__typename?: 'Page';
nav?: Maybe<PageNav>;
blocks?: Maybe<Array<Maybe<PageBlocks>>>;
navlist?: Maybe<Array<Maybe<PageNavlist>>>;
footer?: Maybe<PageFooter>;
};
export type PageDocument = Node & Document & {
__typename?: 'PageDocument';
id: Scalars['ID'];
sys: SystemInfo;
data: Page;
form: Scalars['JSON'];
values: Scalars['JSON'];
dataJSON: Scalars['JSON'];
};
export type PageConnectionEdges = {
__typename?: 'PageConnectionEdges';
cursor?: Maybe<Scalars['String']>;
node?: Maybe<PageDocument>;
};
export type PageConnection = Connection & {
__typename?: 'PageConnection';
pageInfo?: Maybe<PageInfo>;
totalCount: Scalars['Int'];
edges?: Maybe<Array<Maybe<PageConnectionEdges>>>;
};
export type Mutation = {
__typename?: 'Mutation';
addPendingDocument: DocumentNode;
updateDocument: DocumentNode;
updateThemeDocument: ThemeDocument;
updatePageDocument: PageDocument;
};
export type MutationAddPendingDocumentArgs = {
collection: Scalars['String'];
relativePath: Scalars['String'];
template?: Maybe<Scalars['String']>;
};
export type MutationUpdateDocumentArgs = {
collection: Scalars['String'];
relativePath: Scalars['String'];
params: DocumentMutation;
};
export type MutationUpdateThemeDocumentArgs = {
relativePath: Scalars['String'];
params: ThemeMutation;
};
export type MutationUpdatePageDocumentArgs = {
relativePath: Scalars['String'];
params: PageMutation;
};
export type DocumentMutation = {
theme?: Maybe<ThemeMutation>;
page?: Maybe<PageMutation>;
};
export type ThemeMutation = {
color?: Maybe<Scalars['String']>;
btnStyle?: Maybe<Scalars['String']>;
};
export type PageNavWordmarkIconMutation = {
color?: Maybe<Scalars['String']>;
name?: Maybe<Scalars['String']>;
style?: Maybe<Scalars['String']>;
};
export type PageNavWordmarkMutation = {
icon?: Maybe<PageNavWordmarkIconMutation>;
name?: Maybe<Scalars['String']>;
};
export type PageNavItemsMutation = {
label?: Maybe<Scalars['String']>;
link?: Maybe<Scalars['String']>;
};
export type PageNavMutation = {
wordmark?: Maybe<PageNavWordmarkMutation>;
items?: Maybe<Array<Maybe<PageNavItemsMutation>>>;
};
export type PageBlocksHeroStringMutation = {
color?: Maybe<Scalars['String']>;
};
export type PageBlocksHeroImageMutation = {
src?: Maybe<Scalars['String']>;
alt?: Maybe<Scalars['String']>;
};
export type PageBlocksHeroActionsMutation = {
label?: Maybe<Scalars['String']>;
type?: Maybe<Scalars['String']>;
icon?: Maybe<Scalars['Boolean']>;
};
export type PageBlocksHeroStyleMutation = {
color?: Maybe<Scalars['String']>;
};
export type PageBlocksHeroMutation = {
tagline?: Maybe<Scalars['String']>;
headline?: Maybe<Scalars['String']>;
paragraph?: Maybe<Scalars['String']>;
string?: Maybe<PageBlocksHeroStringMutation>;
image?: Maybe<PageBlocksHeroImageMutation>;
actions?: Maybe<Array<Maybe<PageBlocksHeroActionsMutation>>>;
style?: Maybe<PageBlocksHeroStyleMutation>;
};
export type PageBlocksTestimonialStyleMutation = {
color?: Maybe<Scalars['String']>;
};
export type PageBlocksTestimonialMutation = {
quote?: Maybe<Scalars['String']>;
author?: Maybe<Scalars['String']>;
style?: Maybe<PageBlocksTestimonialStyleMutation>;
};
export type PageBlocksFeaturesItemsIconMutation = {
color?: Maybe<Scalars['String']>;
name?: Maybe<Scalars['String']>;
style?: Maybe<Scalars['String']>;
};
export type PageBlocksFeaturesItemsActionsMutation = {
label?: Maybe<Scalars['String']>;
type?: Maybe<Scalars['String']>;
icon?: Maybe<Scalars['Boolean']>;
};
export type PageBlocksFeaturesItemsMutation = {
icon?: Maybe<PageBlocksFeaturesItemsIconMutation>;
title?: Maybe<Scalars['String']>;
text?: Maybe<Scalars['String']>;
actions?: Maybe<Array<Maybe<PageBlocksFeaturesItemsActionsMutation>>>;
};
export type PageBlocksFeaturesStyleMutation = {
color?: Maybe<Scalars['String']>;
};
export type PageBlocksFeaturesMutation = {
items?: Maybe<Array<Maybe<PageBlocksFeaturesItemsMutation>>>;
style?: Maybe<PageBlocksFeaturesStyleMutation>;
};
export type PageBlocksMutation = {
hero?: Maybe<PageBlocksHeroMutation>;
testimonial?: Maybe<PageBlocksTestimonialMutation>;
features?: Maybe<PageBlocksFeaturesMutation>;
};
export type PageNavlistNavItemsMutation = {
label?: Maybe<Scalars['String']>;
link?: Maybe<Scalars['String']>;
};
export type PageNavlistNavMutation = {
title?: Maybe<Scalars['String']>;
items?: Maybe<Array<Maybe<PageNavlistNavItemsMutation>>>;
};
export type PageNavlistMutation = {
nav?: Maybe<PageNavlistNavMutation>;
};
export type PageFooterSocialMutation = {
facebook?: Maybe<Scalars['String']>;
twitter?: Maybe<Scalars['String']>;
instagram?: Maybe<Scalars['String']>;
github?: Maybe<Scalars['String']>;
};
export type PageFooterMutation = {
social?: Maybe<PageFooterSocialMutation>;
};
export type PageMutation = {
nav?: Maybe<PageNavMutation>;
blocks?: Maybe<Array<Maybe<PageBlocksMutation>>>;
navlist?: Maybe<Array<Maybe<PageNavlistMutation>>>;
footer?: Maybe<PageFooterMutation>;
}; | the_stack |
import {
rightClickOpen,
updateRightClickMenu,
} from "./renderer";
import { pointFallsWithin, determineAngle, radiansToDegrees } from "./utils/number";
import {
getCurrentBoard,
ISpace,
addSpace,
getSpacesOfType,
IBoard,
currentBoardIsROM,
removeSpace,
getSpaceIndex,
addConnection,
setSpaceRotation,
copyCurrentBoard,
setHostsStar
} from "./boards";
import { Action, Space, SpaceSubtype } from "./types";
import { getEventParamDropHandler } from "./utils/drag";
import { $$log, $$hex } from "./utils/debug";
import { changeCurrentAction, changeSelectedSpaces, clearSelectedSpaces, drawConnection, getCurrentAction,
getSelectedSpaceIndices, getSelectedSpaces, getValidSelectedSpaceIndices } from "./app/appControl";
import { getMouseCoordsOnCanvas } from "./utils/canvas";
import { addSelectedSpaceAction,
eraseConnectionsAction,
removeSpacesAction,
selectSelectedSpaceIndices,
setSelectedSpaceAction, setSelectionBoxCoordsAction, setSpacePositionsAction, setSpaceSubtypeAction, setTemporaryUIConnections } from "./app/boardState";
import { store } from "./app/store";
import { isEmpty } from "./utils/obj";
let spaceWasMouseDownedOn = false;
let startX = -1;
let startY = -1;
let lastX = -1;
let lastY = -1;
let canvasRect: (ClientRect | DOMRect) | null = null;
function onEditorMouseDown(event: MouseEvent) {
const canvas = event.currentTarget as HTMLCanvasElement;
_onEditorDown(canvas, event.clientX, event.clientY, event.ctrlKey);
}
function onEditorTouchStart(event: TouchEvent) {
if (event.touches.length !== 1)
return;
const touch = event.touches[0];
const canvas = event.currentTarget as HTMLCanvasElement;
_onEditorDown(canvas, touch.clientX, touch.clientY, event.ctrlKey);
}
/** mousedown or touchstart */
function _onEditorDown(canvas: HTMLCanvasElement, clientX: number, clientY: number, ctrlKey: boolean) {
canvasRect = canvas.getBoundingClientRect();
const [clickX, clickY] = getMouseCoordsOnCanvas(canvas, clientX, clientY);
startX = lastX = clickX;
startY = lastY = clickY;
const clickedSpaceIndex = _getClickedSpace(lastX, lastY);
$$log(`Clicked space: ${$$hex(clickedSpaceIndex)} (${clickedSpaceIndex})`,
getCurrentBoard().spaces[clickedSpaceIndex]);
const spaceWasClicked = clickedSpaceIndex !== -1;
// ROM boards cannot be edited, so create a copy right now and switch to it.
if (currentBoardIsROM() && spaceWasClicked) {
changeCurrentAction(Action.MOVE); // Avoid destructive actions like delete.
clearSelectedSpaces();
copyCurrentBoard(true);
}
const curAction = getCurrentAction();
switch (curAction) {
case Action.MOVE:
if (spaceWasClicked) {
if (ctrlKey) {
_addSelectedSpace(clickedSpaceIndex);
}
else if (!_spaceIsSelected(clickedSpaceIndex)) {
_setSelectedSpace(clickedSpaceIndex);
}
}
else {
clearSelectedSpaces();
}
break;
case Action.ADD_OTHER:
case Action.ADD_BLUE:
case Action.ADD_RED:
case Action.ADD_MINIGAME:
case Action.ADD_HAPPENING:
case Action.ADD_STAR:
case Action.ADD_BLACKSTAR:
case Action.ADD_START:
case Action.ADD_CHANCE:
case Action.ADD_SHROOM:
case Action.ADD_BOWSER:
case Action.ADD_ITEM:
case Action.ADD_BATTLE:
case Action.ADD_BANK:
case Action.ADD_GAMEGUY:
case Action.ADD_ARROW:
case Action.MARK_STAR:
case Action.MARK_GATE:
case Action.ADD_TOAD_CHARACTER:
case Action.ADD_BOWSER_CHARACTER:
case Action.ADD_KOOPA_CHARACTER:
case Action.ADD_BOO_CHARACTER:
case Action.ADD_BANK_SUBTYPE:
case Action.ADD_BANKCOIN_SUBTYPE:
case Action.ADD_ITEMSHOP_SUBTYPE:
case Action.ADD_DUEL_BASIC:
case Action.ADD_DUEL_REVERSE:
case Action.ADD_DUEL_POWERUP:
case Action.ADD_DUEL_START_BLUE:
case Action.ADD_DUEL_START_RED:
if (spaceWasClicked) {
if (ctrlKey) {
_addSelectedSpace(clickedSpaceIndex);
}
else if (!_spaceIsSelected(clickedSpaceIndex)) {
_setSelectedSpace(clickedSpaceIndex);
}
}
else if (!ctrlKey) {
clearSelectedSpaces();
}
break;
case Action.LINE:
case Action.LINE_STICKY:
case Action.ROTATE:
if (spaceWasClicked) {
_setSelectedSpace(clickedSpaceIndex);
}
else {
clearSelectedSpaces();
}
break;
case Action.ERASE:
clearSelectedSpaces();
break;
}
const selectedSpaces = getSelectedSpaces();
const curBoard = getCurrentBoard();
const clickedSpace = curBoard.spaces[clickedSpaceIndex];
switch (curAction) {
case Action.LINE:
if (selectedSpaces.length === 1) {
let space = selectedSpaces[0];
// Draw a line from the start space to the current location.
drawConnection(space.x, space.y, clickX, clickY);
if (rightClickOpen()) {
updateRightClickMenu(-1);
}
}
break;
case Action.LINE_STICKY:
if (selectedSpaces.length === 1) {
let space = selectedSpaces[0];
// Make a connection if we are in sticky mode and have reached a new space.
if (clickedSpace && clickedSpace !== space) {
const selectedSpaceIndex = getSpaceIndex(space, curBoard);
addConnection(selectedSpaceIndex, clickedSpaceIndex);
_setSelectedSpace(clickedSpaceIndex);
}
else {
// Draw a line from the start space to the current location.
drawConnection(space.x, space.y, clickX, clickY);
}
}
break;
case Action.ROTATE:
break;
case Action.ERASE:
if (clickedSpaceIndex !== -1 && _canRemoveSpaceAtIndex(curBoard, clickedSpaceIndex)) {
removeSpace(clickedSpaceIndex);
clearSelectedSpaces();
}
else {
_eraseLines(clickX, clickY); // Try to slice some lines!
}
break;
case Action.ADD_OTHER:
case Action.ADD_BLUE:
case Action.ADD_RED:
case Action.ADD_MINIGAME:
case Action.ADD_HAPPENING:
case Action.ADD_STAR:
case Action.ADD_BLACKSTAR:
case Action.ADD_START:
case Action.ADD_CHANCE:
case Action.ADD_SHROOM:
case Action.ADD_BOWSER:
case Action.ADD_ITEM:
case Action.ADD_BATTLE:
case Action.ADD_BANK:
case Action.ADD_GAMEGUY:
case Action.ADD_ARROW:
case Action.ADD_DUEL_BASIC:
case Action.ADD_DUEL_REVERSE:
case Action.ADD_DUEL_POWERUP:
case Action.ADD_DUEL_START_BLUE:
case Action.ADD_DUEL_START_RED:
_addSpace(curAction, clickX, clickY, clickedSpaceIndex, false, ctrlKey);
break;
case Action.MARK_STAR:
case Action.MARK_GATE:
case Action.ADD_TOAD_CHARACTER:
case Action.ADD_BOWSER_CHARACTER:
case Action.ADD_KOOPA_CHARACTER:
case Action.ADD_BOO_CHARACTER:
case Action.ADD_BANK_SUBTYPE:
case Action.ADD_BANKCOIN_SUBTYPE:
case Action.ADD_ITEMSHOP_SUBTYPE:
if (clickedSpaceIndex === -1) {
_addSpace(curAction, clickX, clickY, clickedSpaceIndex, false, ctrlKey);
}
break;
case Action.MOVE:
default:
if (rightClickOpen()) {
updateRightClickMenu(getValidSelectedSpaceIndices()[0]);
}
break;
}
spaceWasMouseDownedOn = spaceWasClicked;
}
function onEditorTouchMove(event: TouchEvent) {
let clickX, clickY;
if (event.touches.length !== 1)
return;
if (!_hasAnySelectedSpace())
return;
event.preventDefault(); // Don't drag around the board.
let touch = event.touches[0];
clickX = touch.clientX - canvasRect!.left;
clickY = touch.clientY - canvasRect!.top;
_onEditorMove(clickX, clickY);
}
function onEditorMouseMove(event: MouseEvent) {
let clickX, clickY;
if (!canvasRect || event.buttons !== 1)
return;
clickX = event.clientX - canvasRect.left;
clickY = event.clientY - canvasRect.top;
_onEditorMove(clickX, clickY);
}
function _onEditorMove(clickX: number, clickY: number) {
if (currentBoardIsROM())
return;
clickX = Math.round(clickX);
clickY = Math.round(clickY);
const curAction = getCurrentAction();
const selectedSpaceIndices = getValidSelectedSpaceIndices();
const selectedSpaces = getSelectedSpaces();
const curBoard = getCurrentBoard();
const clickedSpaceIndex = _getClickedSpace(clickX, clickY);
switch (curAction) {
case Action.LINE:
if (selectedSpaces.length === 1) {
let space = selectedSpaces[0];
// Draw a line from the start space to the current location.
drawConnection(space.x, space.y, clickX, clickY);
if (rightClickOpen()) {
updateRightClickMenu(-1);
}
}
break;
case Action.LINE_STICKY:
if (selectedSpaces.length === 1) {
const space = selectedSpaces[0];
// Make a connection if we are in sticky mode and have reached a new space.
const endSpace = curBoard.spaces[clickedSpaceIndex];
if (endSpace && endSpace !== space) {
const selectedSpaceIndex = getSpaceIndex(space, curBoard);
addConnection(selectedSpaceIndex, clickedSpaceIndex);
_setSelectedSpace(clickedSpaceIndex);
}
else {
// Draw a line from the start space to the current location.
drawConnection(space.x, space.y, clickX, clickY);
}
}
break;
case Action.ROTATE:
if (selectedSpaces.length === 1) {
const space = selectedSpaces[0];
if (space.type === Space.ARROW) {
// Adjust rotation of the space.
const angleXAxisRad = determineAngle(space.x, space.y, clickX, clickY);
const angleYAxisRad = ((Math.PI * 1.5) + angleXAxisRad) % (Math.PI * 2);
const angleYAxisDeg = radiansToDegrees(angleYAxisRad);
const selectedSpaceIndex = getSpaceIndex(space, curBoard);
//$$log(`Space ${selectedSpaceIndex} rotated ${angleYAxisDeg} degrees`);
setSpaceRotation(selectedSpaceIndex, angleYAxisDeg);
}
}
break;
case Action.ERASE:
if (clickedSpaceIndex !== -1 && _canRemoveSpaceAtIndex(curBoard, clickedSpaceIndex)) {
removeSpace(clickedSpaceIndex);
clearSelectedSpaces();
}
else {
_eraseLines(clickX, clickY); // Try to slice some lines!
}
break;
case Action.MOVE:
case Action.ADD_OTHER:
case Action.ADD_BLUE:
case Action.ADD_RED:
case Action.ADD_MINIGAME:
case Action.ADD_HAPPENING:
case Action.ADD_STAR:
case Action.ADD_BLACKSTAR:
case Action.ADD_START:
case Action.ADD_CHANCE:
case Action.ADD_SHROOM:
case Action.ADD_BOWSER:
case Action.ADD_ITEM:
case Action.ADD_BATTLE:
case Action.ADD_BANK:
case Action.ADD_GAMEGUY:
case Action.ADD_ARROW:
case Action.MARK_STAR:
case Action.MARK_GATE:
case Action.ADD_TOAD_CHARACTER:
case Action.ADD_BOWSER_CHARACTER:
case Action.ADD_KOOPA_CHARACTER:
case Action.ADD_BOO_CHARACTER:
case Action.ADD_BANK_SUBTYPE:
case Action.ADD_BANKCOIN_SUBTYPE:
case Action.ADD_ITEMSHOP_SUBTYPE:
case Action.ADD_DUEL_BASIC:
case Action.ADD_DUEL_REVERSE:
case Action.ADD_DUEL_POWERUP:
case Action.ADD_DUEL_START_BLUE:
case Action.ADD_DUEL_START_RED:
default:
const doingSelectionBox = !spaceWasMouseDownedOn && curAction === Action.MOVE;
if (!doingSelectionBox && selectedSpaces.length) {
// Move the space(s)
const deltaX = clickX - lastX;
const deltaY = clickY - lastY;
const indicesToUpdate = [];
const coordsToUpdate = [];
for (const spaceIndex of selectedSpaceIndices) {
const space = curBoard.spaces[spaceIndex];
if (space) {
indicesToUpdate.push(spaceIndex);
const newX = Math.round(space.x) + deltaX;
const newY = Math.round(space.y) + deltaY;
coordsToUpdate.push({
x: Math.max(0, Math.min(newX, curBoard.bg.width)),
y: Math.max(0, Math.min(newY, curBoard.bg.height))
});
}
}
if (indicesToUpdate.length) {
store.dispatch(setSpacePositionsAction({ spaceIndices: indicesToUpdate, coords: coordsToUpdate }));
}
if (rightClickOpen()) {
updateRightClickMenu(selectedSpaceIndices[0]);
}
}
if (doingSelectionBox) {
// Draw selection box, update selection.
_updateSelectionAndBox(clickX, clickY);
}
break;
}
//$$log("dX: " + deltaX + ", dY: " + deltaY);
lastX = clickX;
lastY = clickY;
}
function onEditorMouseUp(event: MouseEvent) {
if (event.button !== 0)
return;
_onEditorUp();
}
function onEditorTouchEnd(event: TouchEvent) {
if (event.touches.length !== 1)
return;
_onEditorUp();
}
function _onEditorUp() {
if (currentBoardIsROM())
return;
const curAction = getCurrentAction();
switch (curAction) {
case Action.MOVE:
if (!spaceWasMouseDownedOn) {
// Clear the selection we were drawing.
_clearSelectionBox();
}
break;
case Action.LINE:
const selectedSpaceIndices = getValidSelectedSpaceIndices();
const endSpaceIdx = _getClickedSpace(lastX, lastY);
if (endSpaceIdx !== -1) {
for (let index of selectedSpaceIndices) {
addConnection(index, endSpaceIdx);
}
}
_clearTemporaryConnections();
break;
case Action.LINE_STICKY:
_clearTemporaryConnections();
break;
}
}
function onEditorClick(event: MouseEvent) {
//console.log("onEditorClick", event);
if (currentBoardIsROM())
return;
const moved = Math.abs(startX - lastX) > 5 || Math.abs(startY - lastY) > 5;
const movedAtAll = Math.abs(startX - lastX) > 0 || Math.abs(startY - lastY) > 0;
startX = lastX = -1;
startY = lastY = -1;
const ctrlKey = event.ctrlKey;
const clientX = Math.round(event.clientX);
const clientY = Math.round(event.clientY);
const clickX = clientX - Math.round(canvasRect!.left);
const clickY = clientY - Math.round(canvasRect!.top);
let clickedSpaceIdx = _getClickedSpace(clickX, clickY);
const curBoard = getCurrentBoard();
const clickedSpace = clickedSpaceIdx === -1 ? null : curBoard.spaces[clickedSpaceIdx];
if (event.button !== 0)
return;
const curAction = getCurrentAction();
switch (curAction) {
case Action.MOVE:
case Action.ADD_OTHER:
case Action.ADD_BLUE:
case Action.ADD_RED:
case Action.ADD_MINIGAME:
case Action.ADD_HAPPENING:
case Action.ADD_STAR:
case Action.ADD_BLACKSTAR:
case Action.ADD_START:
case Action.ADD_CHANCE:
case Action.ADD_SHROOM:
case Action.ADD_BOWSER:
case Action.ADD_ITEM:
case Action.ADD_BATTLE:
case Action.ADD_BANK:
case Action.ADD_GAMEGUY:
case Action.ADD_ARROW:
case Action.ADD_DUEL_BASIC:
case Action.ADD_DUEL_REVERSE:
case Action.ADD_DUEL_POWERUP:
case Action.ADD_DUEL_START_BLUE:
case Action.ADD_DUEL_START_RED:
if (!movedAtAll && !ctrlKey) {
if (!clickedSpace) {
clearSelectedSpaces();
}
else {
_setSelectedSpace(clickedSpaceIdx);
}
}
break;
case Action.MARK_GATE:
case Action.ADD_TOAD_CHARACTER:
case Action.ADD_BOWSER_CHARACTER:
case Action.ADD_KOOPA_CHARACTER:
case Action.ADD_BOO_CHARACTER:
case Action.ADD_BANK_SUBTYPE:
case Action.ADD_BANKCOIN_SUBTYPE:
case Action.ADD_ITEMSHOP_SUBTYPE:
// Toggle the subtype only at the moment of mouse up, if we didn't move.
if (spaceWasMouseDownedOn) {
_addSpace(curAction, clickX, clickY, clickedSpaceIdx, moved, ctrlKey);
}
if (!movedAtAll && !ctrlKey) {
if (!clickedSpace) {
clearSelectedSpaces();
}
else {
_setSelectedSpace(clickedSpaceIdx);
}
}
break;
case Action.MARK_STAR:
if (!moved) {
_toggleHostsStar(getValidSelectedSpaceIndices());
}
break;
case Action.LINE:
case Action.LINE_STICKY:
_clearTemporaryConnections();
break;
case Action.ERASE:
case Action.ROTATE:
break;
}
spaceWasMouseDownedOn = false;
}
function onEditorRightClick(event: MouseEvent) {
//console.log("onEditorRightClick", event);
event.preventDefault();
event.stopPropagation();
const selectedSpaceIndices = getValidSelectedSpaceIndices();
const space = selectedSpaceIndices.length !== 1 ? -1 : selectedSpaceIndices[0];
updateRightClickMenu(space);
};
function onEditorDrop(event: DragEvent) {
event.preventDefault();
if (currentBoardIsROM())
return;
if (rightClickOpen())
updateRightClickMenu(-1);
if (!event.dataTransfer)
return;
let data;
try {
data = JSON.parse(event.dataTransfer.getData("text"));
} catch (e) {
return;
}
const canvas = event.currentTarget as HTMLCanvasElement;
const [clickX, clickY] = getMouseCoordsOnCanvas(canvas, event.clientX, event.clientY);
canvasRect = canvas.getBoundingClientRect();
const droppedOnSpaceIdx = _getClickedSpace(clickX, clickY);
if (typeof data === "object") {
if (data.action) {
clearSelectedSpaces();
_addSpace(data.action.type, clickX, clickY, droppedOnSpaceIdx, false, false);
}
else if (data.isEventParamDrop) {
const handler = getEventParamDropHandler();
if (handler) {
handler(droppedOnSpaceIdx);
}
}
}
}
function onEditorKeyDown(event: KeyboardEvent) {
const selectedSpaces = getSelectedSpaces();
if (!selectedSpaces || !selectedSpaces.length)
return;
const selectedSpaceIndices = getValidSelectedSpaceIndices();
const board = getCurrentBoard();
switch (event.key) {
case "Up":
case "ArrowUp":
_updateSpaceCoords(selectedSpaceIndices, board, (space) => ({
y: Math.max(space.y - 1, 0)
}));
break;
case "Down":
case "ArrowDown":
_updateSpaceCoords(selectedSpaceIndices, board, (space) => ({
y: Math.min(space.y + 1, board.bg.height)
}));
break;
case "Left":
case "ArrowLeft":
_updateSpaceCoords(selectedSpaceIndices, board, (space) => ({
x: Math.max(space.x - 1, 0)
}));
break;
case "Right":
case "ArrowRight":
_updateSpaceCoords(selectedSpaceIndices, board, (space) => ({
x: Math.min(space.x + 1, board.bg.width)
}));
break;
case "Delete":
// If any characters are on the spaces, first press just deletes them.
// If there are no characters, selected spaces are deleted.
let onlySubtype = false
selectedSpaces.forEach(space => {
if (space.subtype !== undefined) {
onlySubtype = true;
}
});
if (onlySubtype) {
// Delete the character(s) off first.
store.dispatch(setSpaceSubtypeAction({ spaceIndices: selectedSpaceIndices, subtype: undefined }));
}
else {
const spaceIndicesToRemove: number[] = [];
selectedSpaceIndices.forEach(spaceIndex => {
if (_canRemoveSpaceAtIndex(board, spaceIndex)) {
spaceIndicesToRemove.push(spaceIndex);
}
});
if (spaceIndicesToRemove.length > 0) {
store.dispatch(removeSpacesAction({ spaceIndices: spaceIndicesToRemove }));
}
clearSelectedSpaces();
}
break;
}
}
function onEditorMouseOut(event: MouseEvent) {
if (event.button !== 0)
return;
if (currentBoardIsROM())
return;
const curAction = getCurrentAction();
const doingSelectionBox = !spaceWasMouseDownedOn && curAction === Action.MOVE;
if (doingSelectionBox) {
_clearSelectionBox();
startX = lastX = -1;
startY = lastY = -1;
}
}
function _hasAnySelectedSpace() {
return !isEmpty(getSelectedSpaceIndices());
}
function _spaceIsSelected(spaceIndex: number) {
const selectedSpaceIndices = selectSelectedSpaceIndices(store.getState());
return !!selectedSpaceIndices[spaceIndex];
}
function _addSelectedSpace(spaceIndex: number) {
store.dispatch(addSelectedSpaceAction(spaceIndex));
}
function _setSelectedSpace(spaceIndex: number) {
store.dispatch(setSelectedSpaceAction(spaceIndex));
}
function _getSpaceRadius() {
const curBoard = getCurrentBoard();
return curBoard.game === 3 ? 14 : 8;
}
function _getClickedSpace(x: number, y: number) {
const curBoard = getCurrentBoard();
const spaceRadius = _getSpaceRadius();
// Search for the last space that could be clicked. (FIXME: consider circular shape.)
let spaceIdx = -1;
for (let index = 0; index < curBoard.spaces.length; index++) {
let space = curBoard.spaces[index];
if (!space)
continue;
if (Math.abs(space.x - x) <= spaceRadius && Math.abs(space.y - y) <= spaceRadius)
spaceIdx = index;
}
return spaceIdx;
}
function _canRemoveSpaceAtIndex(board: IBoard, spaceIndex: number) {
const space = board.spaces[spaceIndex];
if (!space)
return false;
// Don't allow removing the last start space, since in
// non-advanced mode you can't add it back.
if (space.type === Space.START) {
const startSpaces = getSpacesOfType(Space.START, board);
return startSpaces.length > 1;
}
return true;
}
function _addSpace(action: Action, x: number, y: number, clickedSpaceIndex: number, moved?: boolean, ctrlKey?: boolean) {
const clickedSpace = getCurrentBoard().spaces[clickedSpaceIndex];
let spaceType = _getSpaceTypeFromAction(action);
let spaceSubType = _getSpaceSubTypeFromAction(action);
let shouldChangeSelection = false;
if (clickedSpace) {
// If we are clicking a space, the only "add" action could be to toggle subtype.
if (spaceSubType !== undefined && !moved) {
if (clickedSpace.subtype === spaceSubType) {
store.dispatch(setSpaceSubtypeAction({
spaceIndices: [clickedSpaceIndex],
subtype: undefined,
}));
}
else if (_canSetSubtypeOnSpaceType(clickedSpace.type, spaceSubType)) {
store.dispatch(setSpaceSubtypeAction({
spaceIndices: [clickedSpaceIndex],
subtype: spaceSubType,
}));
}
changeSelectedSpaces([clickedSpaceIndex]);
shouldChangeSelection = true;
}
}
else {
const newSpaceIdx = addSpace(x, y, spaceType, spaceSubType);
if (ctrlKey) {
_addSelectedSpace(newSpaceIdx);
}
else {
changeSelectedSpaces([newSpaceIdx]);
}
shouldChangeSelection = true;
}
return shouldChangeSelection;
}
function _canSetSubtypeOnSpaceType(type: Space, subtype: SpaceSubtype): boolean {
if (type !== Space.OTHER && subtype === SpaceSubtype.GATE) {
// Don't add gate to non-invisible space.
return false;
}
return true;
}
type SpaceCoordUpdater = (space: ISpace) => { x?: number, y?: number, z?: number };
function _updateSpaceCoords(spaceIndices: number[], board: IBoard, updater: SpaceCoordUpdater) {
const indicesToUpdate = [];
const coordsToUpdate = [];
for (const spaceIndex of spaceIndices) {
const space = board.spaces[spaceIndex];
if (space) {
indicesToUpdate.push(spaceIndex);
coordsToUpdate.push(updater(space));
}
}
if (indicesToUpdate.length) {
store.dispatch(setSpacePositionsAction({ spaceIndices: indicesToUpdate, coords: coordsToUpdate }));
}
}
function _toggleHostsStar(selectedSpacesIndices: number[]) {
if (!selectedSpacesIndices.length)
return;
// If any space does not have star hosting, we add to all.
// Otherwise remove from all.
let adding = false;
const board = getCurrentBoard();
for (const spaceIndex of selectedSpacesIndices) {
const space = board.spaces[spaceIndex];
if (!space.star) {
adding = true;
break;
}
}
setHostsStar(selectedSpacesIndices, adding);
}
function _clearTemporaryConnections(): void {
store.dispatch(setTemporaryUIConnections({ connections: null }));
}
function _eraseLines(x: number, y: number) {
store.dispatch(eraseConnectionsAction({ x, y }));
}
function _getSpaceTypeFromAction(action: Action): Space {
switch (action) {
case Action.ADD_BLUE: return Space.BLUE;
case Action.ADD_RED: return Space.RED;
case Action.ADD_HAPPENING: return Space.HAPPENING;
case Action.ADD_STAR: return Space.STAR;
case Action.ADD_BLACKSTAR: return Space.BLACKSTAR;
case Action.ADD_MINIGAME: return Space.MINIGAME;
case Action.ADD_CHANCE: return Space.CHANCE;
case Action.ADD_START: return Space.START;
case Action.ADD_SHROOM: return Space.SHROOM;
case Action.ADD_BOWSER: return Space.BOWSER;
case Action.ADD_ITEM: return Space.ITEM;
case Action.ADD_BATTLE: return Space.BATTLE;
case Action.ADD_BANK: return Space.BANK;
case Action.ADD_ARROW: return Space.ARROW;
case Action.ADD_GAMEGUY: return Space.GAMEGUY;
case Action.ADD_DUEL_BASIC: return Space.DUEL_BASIC;
case Action.ADD_DUEL_REVERSE: return Space.DUEL_REVERSE;
case Action.ADD_DUEL_POWERUP: return Space.DUEL_POWERUP;
case Action.ADD_DUEL_START_BLUE: return Space.DUEL_START_BLUE;
case Action.ADD_DUEL_START_RED: return Space.DUEL_START_RED;
default: return Space.OTHER;
}
}
function _getSpaceSubTypeFromAction(action: Action): SpaceSubtype | undefined {
switch (action) {
case Action.ADD_TOAD_CHARACTER: return SpaceSubtype.TOAD;
case Action.ADD_BOWSER_CHARACTER: return SpaceSubtype.BOWSER;
case Action.ADD_KOOPA_CHARACTER: return SpaceSubtype.KOOPA;
case Action.ADD_BOO_CHARACTER: return SpaceSubtype.BOO;
case Action.ADD_BANK_SUBTYPE: return SpaceSubtype.BANK;
case Action.ADD_BANKCOIN_SUBTYPE: return SpaceSubtype.BANKCOIN;
case Action.ADD_ITEMSHOP_SUBTYPE: return SpaceSubtype.ITEMSHOP;
case Action.MARK_GATE: return SpaceSubtype.GATE;
default: return undefined;
}
}
function _updateSelectionAndBox(curX: number, curY: number) {
if (startX === -1 || startY === -1)
return;
clearSelectedSpaces();
const curBoard = getCurrentBoard();
const spaces = curBoard.spaces;
const selectedSpaceIndices = [];
for (let i = 0; i < spaces.length; i++) {
const space = spaces[i];
if (pointFallsWithin(space.x, space.y, startX, startY, curX, curY)) {
selectedSpaceIndices.push(i);
}
}
changeSelectedSpaces(selectedSpaceIndices);
_setSelectionBox(startX, startY, curX, curY);
}
function _setSelectionBox(startX: number, startY: number, curX: number, curY: number): void {
store.dispatch(setSelectionBoxCoordsAction({
selectionCoords: [startX, startY, curX, curY]
}));
}
function _clearSelectionBox() {
store.dispatch(setSelectionBoxCoordsAction({ selectionCoords: null }));
}
function preventDefault(event: Event) { event.preventDefault(); }
export function attachToCanvas(canvas: HTMLCanvasElement) {
canvas.addEventListener("contextmenu", onEditorRightClick, false);
canvas.addEventListener("click", onEditorClick, false);
canvas.addEventListener("mousedown", onEditorMouseDown, false);
canvas.addEventListener("mousemove", onEditorMouseMove, false);
canvas.addEventListener("mouseup", onEditorMouseUp, false);
canvas.addEventListener("mouseout", onEditorMouseOut, false);
canvas.addEventListener("touchstart", onEditorTouchStart, false);
canvas.addEventListener("touchmove", onEditorTouchMove, false);
canvas.addEventListener("touchend", onEditorTouchEnd, false);
canvas.addEventListener("drop", onEditorDrop, false);
canvas.addEventListener("dragover", preventDefault, false);
canvas.addEventListener("keydown", onEditorKeyDown, false);
}
export function detachFromCanvas(canvas: HTMLCanvasElement) {
canvas.removeEventListener("contextmenu", onEditorRightClick);
canvas.removeEventListener("click", onEditorClick);
canvas.removeEventListener("mousedown", onEditorMouseDown);
canvas.removeEventListener("mousemove", onEditorMouseMove);
canvas.removeEventListener("mouseup", onEditorMouseUp);
canvas.removeEventListener("mouseout", onEditorMouseOut);
canvas.removeEventListener("touchstart", onEditorTouchStart);
canvas.removeEventListener("touchmove", onEditorTouchMove);
canvas.removeEventListener("touchend", onEditorTouchEnd);
canvas.removeEventListener("drop", onEditorDrop);
canvas.removeEventListener("dragover", preventDefault);
canvas.removeEventListener("keydown", onEditorKeyDown);
} | the_stack |
* @fileoverview Utility functions for the newcommand package.
*
* @author v.sorge@mathjax.org (Volker Sorge)
*/
import ParseUtil from '../ParseUtil.js';
import TexError from '../TexError.js';
import TexParser from '../TexParser.js';
import {Macro, Symbol} from '../Symbol.js';
import {Args, Attributes, ParseMethod} from '../Types.js';
import * as sm from '../SymbolMap.js';
namespace NewcommandUtil {
/**
* Transforms the attributes of a symbol into the arguments of a macro. E.g.,
* Symbol('ell', 'l', {mathvariant: "italic"}) is turned into Macro arguments:
* ['ell', 'l', 'mathvariant', 'italic'].
*
* @param {string} name The command name for the symbol.
* @param {Symbol} symbol The symbol associated with name.
* @return {Args[]} Arguments for a macro.
*/
export function disassembleSymbol(name: string, symbol: Symbol): Args[] {
let newArgs = [name, symbol.char] as Args[];
// @test Let Relet, Let Let, Let Circular Macro
if (symbol.attributes) {
// @test Let Relet
for (let key in symbol.attributes) {
newArgs.push(key);
newArgs.push(symbol.attributes[key] as Args);
}
}
return newArgs;
}
/**
* Assembles a symbol from a list of macro arguments. This is the inverse
* method of the one above.
*
* @param {Args[]} args The arguments of the macro.
* @return {Symbol} The Symbol generated from the arguments..
*/
export function assembleSymbol(args: Args[]): Symbol {
// @test Let Relet, Let Let, Let Circular Macro
let name = args[0] as string;
let char = args[1] as string;
let attrs: Attributes = {};
for (let i = 2; i < args.length; i = i + 2) {
// @test Let Relet
attrs[args[i] as string] = args[i + 1];
}
return new Symbol(name, char, attrs);
}
/**
* Get the next CS name or give an error.
* @param {TexParser} parser The calling parser.
* @param {string} cmd The string starting with a control sequence.
* @return {string} The control sequence.
*/
export function GetCSname(parser: TexParser, cmd: string): string {
// @test Def ReDef, Let Bar, Let Brace Equal
let c = parser.GetNext();
if (c !== '\\') {
// @test No CS
throw new TexError('MissingCS',
'%1 must be followed by a control sequence', cmd);
}
let cs = ParseUtil.trimSpaces(parser.GetArgument(cmd));
return cs.substr(1);
}
/**
* Get a control sequence name as an argument (doesn't require the backslash)
* @param {TexParser} parser The calling parser.
* @param {string} name The macro that is getting the name.
* @return {string} The control sequence.
*/
export function GetCsNameArgument(parser: TexParser, name: string): string {
let cs = ParseUtil.trimSpaces(parser.GetArgument(name));
if (cs.charAt(0) === '\\') {
// @test Newcommand Simple
cs = cs.substr(1);
}
if (!cs.match(/^(.|[a-z]+)$/i)) {
// @test Illegal CS
throw new TexError('IllegalControlSequenceName',
'Illegal control sequence name for %1', name);
}
return cs;
}
/**
* Get the number of arguments for a macro definition
* @param {TexParser} parser The calling parser.
* @param {string} name The macro that is getting the argument count.
* @return {string} The number of arguments (or blank).
*/
export function GetArgCount(parser: TexParser, name: string): string {
let n = parser.GetBrackets(name);
if (n) {
// @test Newcommand Optional, Newcommand Arg, Newcommand Arg Optional
// @test Newenvironment Optional, Newenvironment Arg Optional
n = ParseUtil.trimSpaces(n);
if (!n.match(/^[0-9]+$/)) {
// @test Illegal Argument Number
throw new TexError('IllegalParamNumber',
'Illegal number of parameters specified in %1', name);
}
}
return n;
}
/**
* Get a \def parameter template.
* @param {TexParser} parser The calling parser.
* @param {string} cmd The string starting with the template.
* @param {string} cs The control sequence of the \def.
* @return {number | string[]} The number of parameters or a string array if
* there is an optional argument.
*/
export function GetTemplate(parser: TexParser, cmd: string, cs: string): number | string[] {
// @test Def Double Let, Def ReDef, Def Let
let c = parser.GetNext();
let params: string[] = [];
let n = 0;
let i = parser.i;
while (parser.i < parser.string.length) {
c = parser.GetNext();
if (c === '#') {
// @test Def ReDef, Def Let, Def Optional Brace
if (i !== parser.i) {
// @test Def Let, Def Optional Brace
params[n] = parser.string.substr(i, parser.i - i);
}
c = parser.string.charAt(++parser.i);
if (!c.match(/^[1-9]$/)) {
// @test Illegal Hash
throw new TexError('CantUseHash2',
'Illegal use of # in template for %1', cs);
}
if (parseInt(c) !== ++n) {
// @test No Sequence
throw new TexError('SequentialParam',
'Parameters for %1 must be numbered sequentially', cs);
}
i = parser.i + 1;
} else if (c === '{') {
// @test Def Double Let, Def ReDef, Def Let
if (i !== parser.i) {
// @test Optional Brace Error
params[n] = parser.string.substr(i, parser.i - i);
}
if (params.length > 0) {
// @test Def Let, Def Optional Brace
return [n.toString()].concat(params);
} else {
// @test Def Double Let, Def ReDef
return n;
}
}
parser.i++;
}
// @test No Replacement
throw new TexError('MissingReplacementString',
'Missing replacement string for definition of %1', cmd);
}
/**
* Find a single parameter delimited by a trailing template.
* @param {TexParser} parser The calling parser.
* @param {string} name The name of the calling command.
* @param {string} param The parameter for the macro.
*/
export function GetParameter(parser: TexParser, name: string, param: string) {
if (param == null) {
// @test Def Let, Def Optional Brace, Def Options CS
return parser.GetArgument(name);
}
let i = parser.i;
let j = 0;
let hasBraces = 0;
while (parser.i < parser.string.length) {
let c = parser.string.charAt(parser.i);
// @test Def Let, Def Optional Brace, Def Options CS
if (c === '{') {
// @test Def Optional Brace, Def Options CS
if (parser.i === i) {
// @test Def Optional Brace
hasBraces = 1;
}
parser.GetArgument(name);
j = parser.i - i;
} else if (MatchParam(parser, param)) {
// @test Def Let, Def Optional Brace, Def Options CS
if (hasBraces) {
// @test Def Optional Brace
i++;
j -= 2;
}
return parser.string.substr(i, j);
} else if (c === '\\') {
// @test Def Options CS
parser.i++;
j++;
hasBraces = 0;
let match = parser.string.substr(parser.i).match(/[a-z]+|./i);
if (match) {
// @test Def Options CS
parser.i += match[0].length;
j = parser.i - i;
}
} else {
// @test Def Let
parser.i++;
j++;
hasBraces = 0;
}
}
// @test Runaway Argument
throw new TexError('RunawayArgument', 'Runaway argument for %1?', name);
}
/**
* Check if a template is at the current location.
* (The match must be exact, with no spacing differences. TeX is
* a little more forgiving than this about spaces after macro names)
* @param {TexParser} parser The calling parser.
* @param {string} param Tries to match an optional parameter.
* @return {number} The number of optional parameters, either 0 or 1.
*/
export function MatchParam(parser: TexParser, param: string): number {
// @test Def Let, Def Optional Brace, Def Options CS
if (parser.string.substr(parser.i, param.length) !== param) {
// @test Def Let, Def Options CS
return 0;
}
if (param.match(/\\[a-z]+$/i) &&
parser.string.charAt(parser.i + param.length).match(/[a-z]/i)) {
// @test (missing)
return 0;
}
// @test Def Let, Def Optional Brace, Def Options CS
parser.i += param.length;
return 1;
}
/**
* Adds a new delimiter as extension to the parser.
* @param {TexParser} parser The current parser.
* @param {string} cs The control sequence of the delimiter.
* @param {string} char The corresponding character.
* @param {Attributes} attr The attributes needed for parsing.
*/
export function addDelimiter(parser: TexParser, cs: string, char: string, attr: Attributes) {
const handlers = parser.configuration.handlers;
const handler = handlers.retrieve(NEW_DELIMITER) as sm.DelimiterMap;
handler.add(cs, new Symbol(cs, char, attr));
}
/**
* Adds a new macro as extension to the parser.
* @param {TexParser} parser The current parser.
* @param {string} cs The control sequence of the delimiter.
* @param {ParseMethod} func The parse method for this macro.
* @param {Args[]} attr The attributes needed for parsing.
* @param {string=} symbol Optionally original symbol for macro, in case it is
* different from the control sequence.
*/
export function addMacro(parser: TexParser, cs: string, func: ParseMethod, attr: Args[],
symbol: string = '') {
const handlers = parser.configuration.handlers;
const handler = handlers.retrieve(NEW_COMMAND) as sm.CommandMap;
handler.add(cs, new Macro(symbol ? symbol : cs, func, attr));
}
/**
* Adds a new environment as extension to the parser.
* @param {TexParser} parser The current parser.
* @param {string} env The environment name.
* @param {ParseMethod} func The parse method for this macro.
* @param {Args[]} attr The attributes needed for parsing.
*/
export function addEnvironment(parser: TexParser, env: string, func: ParseMethod, attr: Args[]) {
const handlers = parser.configuration.handlers;
const handler = handlers.retrieve(NEW_ENVIRONMENT) as sm.EnvironmentMap;
handler.add(env, new Macro(env, func, attr));
}
/**
* Naming constants for the extension mappings.
*/
export const NEW_DELIMITER = 'new-Delimiter';
export const NEW_COMMAND = 'new-Command';
export const NEW_ENVIRONMENT = 'new-Environment';
}
export default NewcommandUtil; | the_stack |
import {
CandidateReleasePullRequest,
RepositoryConfig,
ROOT_PROJECT_PATH,
} from '../manifest';
import {logger} from '../util/logger';
import {
WorkspacePlugin,
DependencyGraph,
DependencyNode,
WorkspacePluginOptions,
} from './workspace';
import {
CargoManifest,
parseCargoManifest,
CargoDependencies,
CargoDependency,
} from '../updaters/rust/common';
import {VersionsMap, Version} from '../version';
import {GitHub} from '../github';
import {CargoToml} from '../updaters/rust/cargo-toml';
import {RawContent} from '../updaters/raw-content';
import {Changelog} from '../updaters/changelog';
import {ReleasePullRequest} from '../release-pull-request';
import {PullRequestTitle} from '../util/pull-request-title';
import {PullRequestBody} from '../util/pull-request-body';
import {BranchName} from '../util/branch-name';
import {PatchVersionUpdate} from '../versioning-strategy';
interface CrateInfo {
/**
* e.g. `crates/crate-a`
*/
path: string;
/**
* e.g. `crate-a`
*/
name: string;
/**
* e.g. `1.0.0`
*/
version: string;
/**
* e.g. `crates/crate-a/Cargo.toml`
*/
manifestPath: string;
/**
* text content of the manifest, used for updates
*/
manifestContent: string;
/**
* Parsed cargo manifest
*/
manifest: CargoManifest;
}
/**
* The plugin analyzed a cargo workspace and will bump dependencies
* of managed packages if those dependencies are being updated.
*
* If multiple rust packages are being updated, it will merge them
* into a single rust package.
*/
export class CargoWorkspace extends WorkspacePlugin<CrateInfo> {
constructor(
github: GitHub,
targetBranch: string,
repositoryConfig: RepositoryConfig,
options: WorkspacePluginOptions = {}
) {
super(github, targetBranch, repositoryConfig, {
...options,
updateAllPackages: true,
});
}
protected async buildAllPackages(
candidates: CandidateReleasePullRequest[]
): Promise<{
allPackages: CrateInfo[];
candidatesByPackage: Record<string, CandidateReleasePullRequest>;
}> {
const cargoManifestContent = await this.github.getFileContentsOnBranch(
'Cargo.toml',
this.targetBranch
);
const cargoManifest = parseCargoManifest(
cargoManifestContent.parsedContent
);
if (!cargoManifest.workspace?.members) {
logger.warn(
"cargo-workspace plugin used, but top-level Cargo.toml isn't a cargo workspace"
);
return {allPackages: [], candidatesByPackage: {}};
}
const allCrates: CrateInfo[] = [];
const candidatesByPackage: Record<string, CandidateReleasePullRequest> = {};
for (const path of cargoManifest.workspace.members) {
const manifestPath = addPath(path, 'Cargo.toml');
logger.info(`looking for candidate with path: ${path}`);
const candidate = candidates.find(c => c.path === path);
// get original content of the crate
const manifestContent =
candidate?.pullRequest.updates.find(
update => update.path === manifestPath
)?.cachedFileContents ||
(await this.github.getFileContentsOnBranch(
manifestPath,
this.targetBranch
));
const manifest = parseCargoManifest(manifestContent.parsedContent);
const packageName = manifest.package?.name;
if (!packageName) {
throw new Error(
`package manifest at ${manifestPath} is missing [package.name]`
);
}
if (candidate) {
candidatesByPackage[packageName] = candidate;
}
const version = manifest.package?.version;
if (!version) {
throw new Error(
`package manifest at ${manifestPath} is missing [package.version]`
);
}
allCrates.push({
path,
name: packageName,
version,
manifest,
manifestContent: manifestContent.parsedContent,
manifestPath,
});
}
return {
allPackages: allCrates,
candidatesByPackage,
};
}
protected bumpVersion(pkg: CrateInfo): Version {
const version = Version.parse(pkg.version);
return new PatchVersionUpdate().bump(version);
}
protected updateCandidate(
existingCandidate: CandidateReleasePullRequest,
pkg: CrateInfo,
updatedVersions: VersionsMap
): CandidateReleasePullRequest {
const version = updatedVersions.get(pkg.name);
if (!version) {
throw new Error(`Didn't find updated version for ${pkg.name}`);
}
const updater = new CargoToml({
version,
versionsMap: updatedVersions,
});
const updatedContent = updater.updateContent(pkg.manifestContent);
const originalManifest = parseCargoManifest(pkg.manifestContent);
const updatedManifest = parseCargoManifest(updatedContent);
const dependencyNotes = getChangelogDepsNotes(
originalManifest,
updatedManifest
);
existingCandidate.pullRequest.updates =
existingCandidate.pullRequest.updates.map(update => {
if (update.path === addPath(existingCandidate.path, 'Cargo.toml')) {
update.updater = new RawContent(updatedContent);
} else if (update.updater instanceof Changelog) {
update.updater.changelogEntry = appendDependenciesSectionToChangelog(
update.updater.changelogEntry,
dependencyNotes
);
}
return update;
});
// append dependency notes
if (dependencyNotes) {
if (existingCandidate.pullRequest.body.releaseData.length > 0) {
existingCandidate.pullRequest.body.releaseData[0].notes =
appendDependenciesSectionToChangelog(
existingCandidate.pullRequest.body.releaseData[0].notes,
dependencyNotes
);
} else {
existingCandidate.pullRequest.body.releaseData.push({
component: pkg.name,
version: existingCandidate.pullRequest.version,
notes: appendDependenciesSectionToChangelog('', dependencyNotes),
});
}
}
return existingCandidate;
}
protected newCandidate(
pkg: CrateInfo,
updatedVersions: VersionsMap
): CandidateReleasePullRequest {
const version = updatedVersions.get(pkg.name);
if (!version) {
throw new Error(`Didn't find updated version for ${pkg.name}`);
}
const updater = new CargoToml({
version,
versionsMap: updatedVersions,
});
const updatedContent = updater.updateContent(pkg.manifestContent);
const originalManifest = parseCargoManifest(pkg.manifestContent);
const updatedManifest = parseCargoManifest(updatedContent);
const dependencyNotes = getChangelogDepsNotes(
originalManifest,
updatedManifest
);
const pullRequest: ReleasePullRequest = {
title: PullRequestTitle.ofTargetBranch(this.targetBranch),
body: new PullRequestBody([
{
component: pkg.name,
version,
notes: appendDependenciesSectionToChangelog('', dependencyNotes),
},
]),
updates: [
{
path: addPath(pkg.path, 'Cargo.toml'),
createIfMissing: false,
updater: new RawContent(updatedContent),
},
{
path: addPath(pkg.path, 'CHANGELOG.md'),
createIfMissing: false,
updater: new Changelog({
version,
changelogEntry: dependencyNotes,
}),
},
],
labels: [],
headRefName: BranchName.ofTargetBranch(this.targetBranch).toString(),
version,
draft: false,
};
return {
path: pkg.path,
pullRequest,
config: {
releaseType: 'rust',
},
};
}
protected async buildGraph(
allPackages: CrateInfo[]
): Promise<DependencyGraph<CrateInfo>> {
const workspaceCrateNames = new Set(
allPackages.map(crateInfo => crateInfo.name)
);
const graph = new Map<string, DependencyNode<CrateInfo>>();
for (const crateInfo of allPackages) {
const allDeps = Object.keys({
...(crateInfo.manifest.dependencies ?? {}),
...(crateInfo.manifest['dev-dependencies'] ?? {}),
...(crateInfo.manifest['build-dependencies'] ?? {}),
});
const workspaceDeps = allDeps.filter(dep => workspaceCrateNames.has(dep));
graph.set(crateInfo.name, {
deps: workspaceDeps,
value: crateInfo,
});
}
return graph;
}
protected inScope(candidate: CandidateReleasePullRequest): boolean {
return (
candidate.config.releaseType === 'rust' &&
candidate.path !== ROOT_PROJECT_PATH
);
}
protected packageNameFromPackage(pkg: CrateInfo): string {
return pkg.name;
}
}
function getChangelogDepsNotes(
originalManifest: CargoManifest,
updatedManifest: CargoManifest
): string {
let depUpdateNotes = '';
type DT = 'dependencies' | 'dev-dependencies' | 'build-dependencies';
const depTypes: DT[] = [
'dependencies',
'dev-dependencies',
'build-dependencies',
];
const depVer = (
s: string | CargoDependency | undefined
): string | undefined => {
if (s === undefined) {
return undefined;
}
if (typeof s === 'string') {
return s;
} else {
return s.version;
}
};
type DepMap = Record<string, string>;
const getDepMap = (cargoDeps: CargoDependencies): DepMap => {
const result: DepMap = {};
for (const [key, val] of Object.entries(cargoDeps)) {
const ver = depVer(val);
if (ver) {
result[key] = ver;
}
}
return result;
};
const updates: Map<DT, string[]> = new Map();
for (const depType of depTypes) {
const depUpdates = [];
const pkgDepTypes = updatedManifest[depType];
if (pkgDepTypes === undefined) {
continue;
}
for (const [depName, currentDepVer] of Object.entries(
getDepMap(pkgDepTypes)
)) {
const origDepVer = depVer(originalManifest[depType]?.[depName]);
if (currentDepVer !== origDepVer) {
depUpdates.push(
`\n * ${depName} bumped from ${origDepVer} to ${currentDepVer}`
);
}
}
if (depUpdates.length > 0) {
updates.set(depType, depUpdates);
}
}
for (const [dt, notes] of updates) {
depUpdateNotes += `\n * ${dt}`;
for (const note of notes) {
depUpdateNotes += note;
}
}
if (depUpdateNotes) {
return `* The following workspace dependencies were updated${depUpdateNotes}`;
}
return '';
}
const DEPENDENCY_HEADER = new RegExp('### Dependencies');
function appendDependenciesSectionToChangelog(
changelog: string,
notes: string
): string {
if (!changelog) {
return `### Dependencies\n\n${notes}`;
}
const newLines: string[] = [];
let seenDependenciesSection = false;
let seenDependencySectionSpacer = false;
let injected = false;
for (const line of changelog.split('\n')) {
if (seenDependenciesSection) {
const trimmedLine = line.trim();
if (
seenDependencySectionSpacer &&
!injected &&
!trimmedLine.startsWith('*')
) {
newLines.push(changelog);
injected = true;
}
if (trimmedLine === '') {
seenDependencySectionSpacer = true;
}
}
if (line.match(DEPENDENCY_HEADER)) {
seenDependenciesSection = true;
}
newLines.push(line);
}
if (injected) {
return newLines.join('\n');
}
if (seenDependenciesSection) {
return `${changelog}\n${notes}`;
}
return `${changelog}\n\n\n### Dependencies\n\n${notes}`;
}
function addPath(path: string, file: string): string {
return path === ROOT_PROJECT_PATH ? file : `${path}/${file}`;
} | the_stack |
import {Component, ElementRef, HostBinding, Injector, Input, OnDestroy, OnInit} from '@angular/core';
import {AbstractComponent} from '@common/component/abstract.component';
import * as _ from 'lodash';
import {EventsService} from './service/events.service';
import {CommonUtil} from '@common/util/common.util';
import {WorkspaceAdmin} from '@domain/workspace/workspace';
namespace Entity {
export enum Role {
WATCHER = 'Watcher',
OWNER = 'Owner',
MANAGER = 'Manager',
EDITOR = 'Editor'
}
export class Member {
id: string;
email: string;
fullName: string;
username: string;
role: Role;
constructor(id: string, email: string, fullName: string, username: string, role: Role) {
this.id = id;
this.email = email;
this.fullName = fullName;
this.username = username;
this.role = role;
}
public equals(member: Member) {
return this.username === member.username;
}
}
export class SelectValue<T> {
label: string;
value: T;
checked: boolean;
disabled: boolean;
constructor(label: string, value: T, checked: boolean, disabled: boolean) {
this.label = label;
this.value = value;
this.checked = checked;
this.disabled = disabled;
}
public static ofOther(member: Member) {
return this.createMemberSelectValue(member, false, false);
}
public static ofOwner(member: Member) {
return this.createMemberSelectValue(member, true, true);
}
private static createMemberSelectValue(member: Entity.Member, checked: boolean, disabled: boolean) {
return new SelectValue<Member>(member.fullName, member, checked, disabled);
}
}
}
@Component({
selector: '[workspace-members-select-box]',
templateUrl: './workspace-members-select-box.component.html'
})
export class WorkspaceMembersSelectBoxComponent extends AbstractComponent implements OnInit, OnDestroy {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
private readonly _SELECT_BOX_DATAS_LAYER_TOP = 32;
private readonly _DEFAULT_OFFSET_X = '0px';
private readonly _DEFAULT_OFFSET_Y = '0px';
private readonly _OFFSET_SUBFIX = 'px';
private readonly _DEFAULT_SEARCH_KEY = '';
private readonly _NO_MEMBER = 'No member';
private _originOwnerMember: Entity.Member;
private _isWorkspaceOwnerChanged: boolean;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
@HostBinding('class')
public hostClass: string = 'ddp-ui-edit-option';
public readonly UUID: string = CommonUtil.getUUID();
@Input()
public readonly workspace: WorkspaceAdmin;
@Input()
public readonly member = [];
public readonly selectValues: Entity.SelectValue<Entity.Member>[] = [];
public offsetX: string = this._DEFAULT_OFFSET_X;
public offsetY: string = this._DEFAULT_OFFSET_Y;
public searchKey: string = this._DEFAULT_SEARCH_KEY;
public isSelected: boolean;
public isSearchInputElementFocused: boolean;
public isSelectBoxDatasLayerElement: boolean;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
constructor(
protected elementRef: ElementRef,
protected injector: Injector,
private eventsService: EventsService) {
super(elementRef, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Getter & Setter
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
get isWorkspaceOwnerChanged(): boolean {
return this._isWorkspaceOwnerChanged;
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
public ngOnInit() {
super.ngOnInit();
this.setOriginMember();
this.generateSelectValuesWithMembers();
this.subscriptions.push(
this.eventsService.scroll$.subscribe(() => {
if (this.isSelected) {
this.searchKey = '';
this.isSelected = false;
}
}),
);
this.subscriptions.push(
this.eventsService.hideWorkspaceMemeberSelectBoxs$.subscribe((uuid) => {
if (this.UUID !== uuid) {
this.isSelected = false;
}
}),
);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
public getCheckedSelectValueLabel(): string {
const checkedMember = this.getCheckedMember();
if (_.isNil(checkedMember)) {
this.translateService.instant('msg.comm.menu.admin.user.modal.change.owner.please.select');
return;
}
if (checkedMember.label === this._NO_MEMBER) {
return this._NO_MEMBER;
} else {
return `${checkedMember.value.fullName} (${checkedMember.value.role})`;
}
}
public clickSelectValue(member: Entity.SelectValue<Entity.Member>): void {
if (member.checked) {
this.isSelected = false;
return;
}
if (member.disabled) {
this.isSelected = false;
return;
}
_.forEach(this.selectValues, (selectValue, index) => {
selectValue.checked = false;
if (this.selectValues.length - 1 === index) {
member.checked = true;
}
return selectValue;
});
this.isSelected = false;
this.workspaceOwnerChecksForChange(member.value);
}
public toggleSelectBoxSelectedState(element: HTMLDivElement): void {
if (element && !this.isSelected) {
this._closeExcludSelf();
const selectBoxDivElementOffset: ClientRect = this._getSelectBoxDivElementOffset(element);
this._setSelectBoxDatasLayerDivElementOffsetX(selectBoxDivElementOffset);
this._setSelectBoxDatasLayerDivElementOffsetY(selectBoxDivElementOffset);
} else {
this.offsetX = this._DEFAULT_OFFSET_X;
this.offsetY = this._DEFAULT_OFFSET_Y;
this.searchKey = this._DEFAULT_SEARCH_KEY;
}
this.isSelected = !this.isSelected;
}
public searchInputFocus(htmlInputElement: HTMLInputElement): void {
this._changeSearchInputElementFocusState();
this._delaySearchInputElementFocus(htmlInputElement);
}
public clickOutside(): void {
if (this.isSelectBoxDatasLayerElement || this.isSearchInputElementFocused) {
return;
}
if (this.isSelected) {
this.searchKey = '';
this.isSelected = false;
}
}
public mouseOverSelectBoxDatasLayerElement(): void {
this.isSelectBoxDatasLayerElement = true;
}
public mouseLeaveSelectBoxDatasLayerElement(): void {
this.isSelectBoxDatasLayerElement = false;
}
public selectSelectBox(componentWarpDivElement: HTMLDivElement, searchInputElement: HTMLInputElement): void {
this.toggleSelectBoxSelectedState(componentWarpDivElement);
this.searchInputFocus(searchInputElement);
}
public focusOutSearchInputElement() {
this.isSearchInputElementFocused = false;
}
public workspaceOwnerChecksForChange(member?: Entity.Member) {
this._isWorkspaceOwnerChanged = this._checkWorspaceOwnerChanged(
_.isNil(member) ? this.getCheckedMember().value : member);
}
public getCheckedMember(): Entity.SelectValue<Entity.Member> {
return this._getCheckedMembers()[0];
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
private _closeExcludSelf(): void {
this.eventsService.hideWorkspaceMemeberSelectBoxs.next(this.UUID);
}
private _changeSearchInputElementFocusState(): void {
this.isSearchInputElementFocused = true;
}
private _delaySearchInputElementFocus(htmlInputElement: HTMLInputElement, delayTime: number = 50): void {
setTimeout(() => htmlInputElement.focus(), delayTime);
}
// noinspection JSMethodCanBeStatic
private _getSelectBoxDivElementOffset(element: HTMLDivElement): ClientRect {
return element.getBoundingClientRect();
}
private _calculatorSelectBoxDatasLayerDivElementOffsetY(offset: ClientRect): string {
return String(offset.top + this._SELECT_BOX_DATAS_LAYER_TOP) + this._OFFSET_SUBFIX;
}
private _calculatorSelectBoxDatasLayerDivElementOffsetX(offset: ClientRect): string {
return String(offset.left) + this._OFFSET_SUBFIX;
}
private _setSelectBoxDatasLayerDivElementOffsetY(selectBoxDivElementOffset: ClientRect): void {
this.offsetY = this._calculatorSelectBoxDatasLayerDivElementOffsetY(selectBoxDivElementOffset);
}
private _setSelectBoxDatasLayerDivElementOffsetX(selectBoxDivElementOffset: ClientRect): void {
this.offsetX = this._calculatorSelectBoxDatasLayerDivElementOffsetX(selectBoxDivElementOffset);
}
private _getCheckedMembers(): Entity.SelectValue<Entity.Member>[] {
return _.filter(this.selectValues, selectValue => {
return selectValue.checked;
});
}
private _checkWorspaceOwnerChanged(member: Entity.Member): boolean {
return this._originOwnerMember.equals(member);
}
private setOriginMember() {
this._originOwnerMember = new Entity.Member(
this.workspace.id,
this.workspace.owner.email,
this.workspace.owner.fullName,
this.workspace.owner.username,
Entity.Role.OWNER,
);
}
private generateSelectValuesWithMembers() {
if (this.member.length > 0) {
this.selectValues.push(Entity.SelectValue.ofOwner(this._originOwnerMember));
_.forEach(this.member, value => {
let role: Entity.Role = Entity.Role.OWNER;
if (value.role === Entity.Role.WATCHER.toString()) {
role = Entity.Role.WATCHER;
}
if (value.role === Entity.Role.EDITOR.toString()) {
role = Entity.Role.EDITOR;
}
if (value.role === Entity.Role.MANAGER.toString()) {
role = Entity.Role.MANAGER;
}
const member = Entity.SelectValue.ofOther(
new Entity.Member(
value.id,
value.member.email,
value.member.fullName,
value.member.username,
role),
);
// Although designated as the workspace owner, it can still be registered as a workspace member
// If the current owner is included in the list of members, it is excluded from the list of members
if (!this._originOwnerMember.equals(member.value)) {
this.selectValues.push(member);
}
});
} else {
this.selectValues.push(Entity.SelectValue.ofOwner(new Entity.Member(
null, null, this._NO_MEMBER, null, null)));
}
}
} | the_stack |
import cheerio from 'cheerio';
import * as esbuild from 'esbuild';
import {promises as fs, readFileSync, unlinkSync, writeFileSync} from 'fs';
import {fdir} from 'fdir';
import mkdirp from 'mkdirp';
import path from 'path';
import {logger} from '../logger';
import {OptimizeOptions, SnowpackConfig} from '../types';
import {
addLeadingSlash,
addTrailingSlash,
hasExtension,
isRemoteUrl,
isTruthy,
removeLeadingSlash,
removeTrailingSlash,
deleteFromBuildSafe,
} from '../util';
import {getUrlsForFile} from './file-urls';
interface ScannedHtmlEntrypoint {
file: string;
root: cheerio.Root;
getScripts: () => cheerio.Cheerio;
getStyles: () => cheerio.Cheerio;
getLinks: (rel: 'stylesheet') => cheerio.Cheerio;
}
// The manifest type is the one from ESBuild, but we might delete the outputs key
type SnowpackMetaManifest = Omit<esbuild.Metafile, 'outputs'> & Partial<esbuild.Metafile>;
// We want to output our bundled build directly into our build directory, but esbuild
// has a bug where it complains about overwriting source files even when write: false.
// We create a fake bundle directory for now. Nothing ever actually gets written here.
const FAKE_BUILD_DIRECTORY = path.join(process.cwd(), '~~bundle~~');
const FAKE_BUILD_DIRECTORY_REGEX = /.*\~\~bundle\~\~[\\\/]/;
/** Collect deep imports in the given set, recursively. */
function collectDeepImports(
config: SnowpackConfig,
url: string,
manifest: SnowpackMetaManifest,
set: Set<string>,
): void {
const buildPrefix = removeLeadingSlash(config.buildOptions.out.replace(process.cwd(), ''))
.split(path.sep)
.join(path.posix.sep);
const normalizedUrl = !url.startsWith(buildPrefix) ? path.posix.join(buildPrefix, url) : url;
const relativeImportUrl = url.replace(buildPrefix, '');
if (set.has(relativeImportUrl)) {
return;
}
set.add(relativeImportUrl);
const manifestEntry = manifest.inputs[normalizedUrl];
if (!manifestEntry) {
throw new Error('Not Found in manifest: ' + normalizedUrl);
}
manifestEntry.imports.forEach(({path}) => collectDeepImports(config, path, manifest, set));
return;
}
/**
* Scan a collection of HTML files for entrypoints. A file is deemed an "html entrypoint"
* if it contains an <html> element. This prevents partials from being scanned.
*/
async function scanHtmlEntrypoints(htmlFiles: string[]): Promise<(ScannedHtmlEntrypoint | null)[]> {
return Promise.all(
htmlFiles.map(async (htmlFile) => {
const code = await fs.readFile(htmlFile, 'utf8');
const root = cheerio.load(code, {decodeEntities: false});
const isHtmlFragment = root.html().startsWith('<html><head></head><body>');
if (isHtmlFragment) {
return null;
}
return {
file: htmlFile,
root,
getScripts: () => root('script[type="module"]'),
getStyles: () => root('style'),
getLinks: (rel: 'stylesheet') => root(`link[rel="${rel}"]`),
};
}),
);
}
async function extractBaseUrl(htmlData: ScannedHtmlEntrypoint, baseUrl: string): Promise<void> {
const {root, getScripts, getLinks} = htmlData;
if (!baseUrl || baseUrl === '/') {
return;
}
getScripts().each((_, elem) => {
const scriptRoot = root(elem);
const scriptSrc = scriptRoot.attr('src');
if (!scriptSrc || !scriptSrc.startsWith(baseUrl)) {
return;
}
scriptRoot.attr('src', addLeadingSlash(scriptSrc.replace(baseUrl, '')));
scriptRoot.attr('snowpack-baseurl', 'true');
});
getLinks('stylesheet').each((_, elem) => {
const linkRoot = root(elem);
const styleHref = linkRoot.attr('href');
if (!styleHref || !styleHref.startsWith(baseUrl)) {
return;
}
linkRoot.attr('href', addLeadingSlash(styleHref.replace(baseUrl, '')));
linkRoot.attr('snowpack-baseurl', 'true');
});
}
async function restitchBaseUrl(htmlData: ScannedHtmlEntrypoint, baseUrl: string): Promise<void> {
const {root, getScripts, getLinks} = htmlData;
getScripts()
.filter('[snowpack-baseurl]')
.each((_, elem) => {
const scriptRoot = root(elem);
const scriptSrc = scriptRoot.attr('src')!;
scriptRoot.attr('src', removeTrailingSlash(baseUrl) + addLeadingSlash(scriptSrc));
scriptRoot.removeAttr('snowpack-baseurl');
});
getLinks('stylesheet')
.filter('[snowpack-baseurl]')
.each((_, elem) => {
const linkRoot = root(elem);
const styleHref = linkRoot.attr('href')!;
linkRoot.attr('href', removeTrailingSlash(baseUrl) + addLeadingSlash(styleHref));
linkRoot.removeAttr('snowpack-baseurl');
});
}
async function extractInlineScripts(htmlData: ScannedHtmlEntrypoint): Promise<void> {
const {file, root, getScripts, getStyles} = htmlData;
getScripts().each((i, elem) => {
const scriptRoot = root(elem);
const scriptContent = scriptRoot.contents().text();
if (!scriptContent) {
return;
}
scriptRoot.empty();
writeFileSync(file + `.inline.${i}.js`, scriptContent);
scriptRoot.attr('src', `./${path.basename(file)}.inline.${i}.js`);
scriptRoot.attr('snowpack-inline', `true`);
});
getStyles().each((i, elem) => {
const styleRoot = root(elem);
const styleContent = styleRoot.contents().text();
if (!styleContent) {
return;
}
styleRoot.after(
`<link rel="stylesheet" href="./${path.basename(
file,
)}.inline.${i}.css" snowpack-inline="true" />`,
);
styleRoot.remove();
writeFileSync(file + `.inline.${i}.css`, styleContent);
});
}
async function restitchInlineScripts(htmlData: ScannedHtmlEntrypoint): Promise<void> {
const {file, root, getScripts, getLinks} = htmlData;
getScripts()
.filter('[snowpack-inline]')
.each((_, elem) => {
const scriptRoot = root(elem);
const scriptFile = path.resolve(file, '..', scriptRoot.attr('src')!);
const scriptContent = readFileSync(scriptFile, 'utf8');
scriptRoot.text(scriptContent);
scriptRoot.removeAttr('src');
scriptRoot.removeAttr('snowpack-inline');
unlinkSync(scriptFile);
});
getLinks('stylesheet')
.filter('[snowpack-inline]')
.each((_, elem) => {
const linkRoot = root(elem);
const styleFile = path.resolve(file, '..', linkRoot.attr('href')!);
const styleContent = readFileSync(styleFile, 'utf8');
const newStyleEl = root('<style></style>');
newStyleEl.text(styleContent);
linkRoot.after(newStyleEl);
linkRoot.remove();
unlinkSync(styleFile);
});
}
/** Add new bundled CSS files to the HTML entrypoint file, if not already there. */
function addNewBundledCss(
htmlData: ScannedHtmlEntrypoint,
manifest: SnowpackMetaManifest,
baseUrl: string,
): void {
if (!manifest.outputs) {
return;
}
for (const key of Object.keys(manifest.outputs)) {
if (!hasExtension(key, '.css')) {
continue;
}
const scriptKey = key.replace('.css', '.js');
if (!manifest.outputs[scriptKey]) {
continue;
}
const hasCssImportAlready = htmlData
.getLinks('stylesheet')
.toArray()
.some((v) => {
const {attribs} = v as cheerio.TagElement;
return attribs && attribs.href.includes(removeLeadingSlash(key));
});
const hasScriptImportAlready = htmlData
.getScripts()
.toArray()
.some((v) => {
const {attribs} = v as cheerio.TagElement;
return attribs && attribs.src.includes(removeLeadingSlash(scriptKey));
});
if (hasCssImportAlready || !hasScriptImportAlready) {
continue;
}
const linkHref = removeTrailingSlash(baseUrl) + addLeadingSlash(key);
htmlData.root('head').append(`<link rel="stylesheet" href="${linkHref}" />`);
}
}
/**
* Traverse the entrypoint for JS scripts, and add preload links to the HTML entrypoint.
*/
function preloadEntrypoint(
htmlData: ScannedHtmlEntrypoint,
manifest: SnowpackMetaManifest,
config: SnowpackConfig,
): void {
const {root, getScripts} = htmlData;
const preloadScripts = getScripts()
.map((_, elem) => {
const {attribs} = elem as cheerio.TagElement;
return attribs.src;
})
.get()
.filter(isTruthy);
const collectedDeepImports = new Set<string>();
for (const preloadScript of preloadScripts) {
collectDeepImports(config, preloadScript, manifest, collectedDeepImports);
}
const baseUrl = config.buildOptions.baseUrl;
for (const imp of collectedDeepImports) {
const preloadUrl = (baseUrl ? removeTrailingSlash(baseUrl) : '') + addLeadingSlash(imp);
root('head').append(`<link rel="modulepreload" href="${preloadUrl}" />`);
}
}
/**
* Handle the many different user input formats to return an array of strings.
* resolve "auto" mode here.
*/
async function getEntrypoints(
entrypoints: OptimizeOptions['entrypoints'],
allBuildFiles: string[],
) {
if (entrypoints === 'auto') {
// TODO: Filter allBuildFiles by HTML with head & body
return allBuildFiles.filter((f) => hasExtension(f, '.html'));
}
if (Array.isArray(entrypoints)) {
return entrypoints;
}
if (typeof entrypoints === 'function') {
return entrypoints({files: allBuildFiles});
}
throw new Error('UNEXPECTED ENTRYPOINTS: ' + entrypoints);
}
/**
* Resolve an array of string entrypoints to absolute file paths. Handle
* source vs. build directory relative entrypoints here as well.
*/
async function resolveEntrypoints(
entrypoints: string[],
cwd: string,
buildDirectoryLoc: string,
config: SnowpackConfig,
) {
return Promise.all(
entrypoints.map(async (entrypoint) => {
if (path.isAbsolute(entrypoint)) {
return entrypoint;
}
const buildEntrypoint = path.resolve(buildDirectoryLoc, entrypoint);
if (await fs.stat(buildEntrypoint).catch(() => null)) {
return buildEntrypoint;
}
const resolvedSourceFile = path.resolve(cwd, entrypoint);
let resolvedSourceEntrypoint: string | undefined;
if (await fs.stat(resolvedSourceFile).catch(() => null)) {
const resolvedSourceUrls = getUrlsForFile(resolvedSourceFile, config);
if (resolvedSourceUrls) {
resolvedSourceEntrypoint = path.resolve(
buildDirectoryLoc,
removeLeadingSlash(resolvedSourceUrls[0]),
);
if (await fs.stat(resolvedSourceEntrypoint).catch(() => null)) {
return resolvedSourceEntrypoint;
}
}
}
logger.error(`Error: entrypoint "${entrypoint}" not found in either build or source:`, {
name: 'optimize',
});
logger.error(` ✘ Build Entrypoint: ${buildEntrypoint}`, {name: 'optimize'});
logger.error(
` ✘ Source Entrypoint: ${resolvedSourceFile} ${
resolvedSourceEntrypoint ? `-> ${resolvedSourceEntrypoint}` : ''
}`,
{name: 'optimize'},
);
throw new Error(`Optimize entrypoint "${entrypoint}" does not exist.`);
}),
);
}
/**
* Process your entrypoints as either all JS or all HTML. If HTML,
* scan those HTML files and add a Cheerio-powered root document
* so that we can modify the HTML files as we go.
*/
async function processEntrypoints(
originalEntrypointValue: OptimizeOptions['entrypoints'],
entrypointFiles: string[],
buildDirectoryLoc: string,
baseUrl: string,
): Promise<{htmlEntrypoints: null | ScannedHtmlEntrypoint[]; bundleEntrypoints: string[]}> {
// If entrypoints are JS:
if (entrypointFiles.every((f) => hasExtension(f, '.js'))) {
return {htmlEntrypoints: null, bundleEntrypoints: entrypointFiles};
}
// If entrypoints are HTML:
if (entrypointFiles.every((f) => hasExtension(f, '.html'))) {
const rawHtmlEntrypoints = await scanHtmlEntrypoints(entrypointFiles);
const htmlEntrypoints = rawHtmlEntrypoints.filter(isTruthy);
if (
originalEntrypointValue !== 'auto' &&
rawHtmlEntrypoints.length !== htmlEntrypoints.length
) {
throw new Error('INVALID HTML ENTRYPOINTS: ' + originalEntrypointValue);
}
htmlEntrypoints.forEach((val) => extractBaseUrl(val, baseUrl));
htmlEntrypoints.forEach(extractInlineScripts);
const bundleEntrypoints = Array.from(
htmlEntrypoints.reduce((all, val) => {
val.getLinks('stylesheet').each((_, elem) => {
const {attribs} = elem as cheerio.TagElement;
if (!attribs || !attribs.href || isRemoteUrl(attribs.href)) {
return;
}
const resolvedCSS =
attribs.href[0] === '/'
? path.resolve(buildDirectoryLoc, removeLeadingSlash(attribs.href))
: path.resolve(val.file, '..', attribs.href);
all.add(resolvedCSS);
});
val.getScripts().each((_, elem) => {
const {attribs} = elem as cheerio.TagElement;
if (!attribs.src || isRemoteUrl(attribs.src)) {
return;
}
const resolvedJS =
attribs.src[0] === '/'
? path.join(buildDirectoryLoc, removeLeadingSlash(attribs.src))
: path.join(val.file, '..', attribs.src);
all.add(resolvedJS);
});
return all;
}, new Set<string>()),
);
return {htmlEntrypoints, bundleEntrypoints};
}
// If entrypoints are mixed or neither, throw an error.
throw new Error('MIXED ENTRYPOINTS: ' + entrypointFiles);
}
/**
* Run esbuild on the build directory. This is run regardless of bundle=true or false,
* since we use the generated manifest in either case.
*/
async function runEsbuildOnBuildDirectory(
bundleEntrypoints: string[],
allFiles: string[],
config: SnowpackConfig,
): Promise<{manifest: SnowpackMetaManifest; outputFiles: esbuild.OutputFile[]}> {
// esbuild requires publicPath to be a remote URL. Only pass to esbuild if baseUrl is remote.
let publicPath: string | undefined;
if (
config.buildOptions.baseUrl.startsWith('http:') ||
config.buildOptions.baseUrl.startsWith('https:') ||
config.buildOptions.baseUrl.startsWith('//')
) {
publicPath = config.buildOptions.baseUrl;
}
const {outputFiles, warnings, metafile} = await esbuild.build({
entryPoints: bundleEntrypoints,
outdir: FAKE_BUILD_DIRECTORY,
outbase: config.buildOptions.out,
write: false,
bundle: true,
loader: config.optimize!.loader,
sourcemap: config.optimize!.sourcemap,
splitting: config.optimize!.splitting,
format: 'esm',
platform: 'browser',
metafile: true,
publicPath,
minify: config.optimize!.minify,
target: config.optimize!.target,
external: Array.from(new Set(allFiles.map((f) => '*' + path.extname(f))))
.filter((ext) => ext !== '*.js' && ext !== '*.mjs' && ext !== '*.css' && ext !== '*')
.concat(config.packageOptions?.external ?? []),
charset: 'utf8',
});
if (!outputFiles) {
throw new Error('EMPTY BUILD');
}
if (warnings.length > 0) {
console.warn(warnings);
}
outputFiles.forEach((f) => {
f.path = f.path.replace(FAKE_BUILD_DIRECTORY_REGEX, addTrailingSlash(config.buildOptions.out));
});
const manifest = metafile!;
if (!config.optimize?.bundle) {
delete (manifest as SnowpackMetaManifest).outputs;
} else {
Object.entries(manifest.outputs).forEach(([f, val]) => {
const newKey = f.replace(FAKE_BUILD_DIRECTORY_REGEX, '/');
manifest.outputs[newKey] = val;
delete manifest.outputs[f];
});
}
logger.debug(`outputFiles: ${JSON.stringify(outputFiles.map((f) => f.path))}`);
logger.debug(`manifest: ${JSON.stringify(manifest)}`);
return {outputFiles, manifest};
}
/** The main optimize function: runs optimization on a build directory. */
export async function runBuiltInOptimize(config: SnowpackConfig) {
const originalCwd = process.cwd();
const buildDirectoryLoc = config.buildOptions.out;
const options = config.optimize;
if (!options) {
return;
}
// * Scan to collect all build files: We'll need this throughout.
const allBuildFiles = (await new fdir()
.withFullPaths()
.crawl(buildDirectoryLoc)
.withPromise()) as string[];
// * Resolve and validate your entrypoints: they may be JS or HTML
const userEntrypoints = await getEntrypoints(options.entrypoints, allBuildFiles);
logger.debug(JSON.stringify(userEntrypoints), {name: 'optimize.entrypoints'});
const resolvedEntrypoints = await resolveEntrypoints(
userEntrypoints,
originalCwd,
buildDirectoryLoc,
config,
);
logger.debug('(resolved) ' + JSON.stringify(resolvedEntrypoints), {name: 'optimize.entrypoints'});
const {htmlEntrypoints, bundleEntrypoints} = await processEntrypoints(
options.entrypoints,
resolvedEntrypoints,
buildDirectoryLoc,
config.buildOptions.baseUrl,
);
logger.debug(`htmlEntrypoints: ${JSON.stringify(htmlEntrypoints?.map((f) => f.file))}`);
logger.debug(`bundleEntrypoints: ${JSON.stringify(bundleEntrypoints)}`);
if (
(!htmlEntrypoints || htmlEntrypoints.length === 0) &&
bundleEntrypoints.length === 0 &&
(options.bundle || options.preload)
) {
throw new Error(
'[optimize] No HTML entrypoints detected. Set "entrypoints" manually if your site HTML is generated outside of Snowpack (SSR, Rails, PHP, etc.).',
);
}
// * Run esbuild on the entire build directory. Even if you are not writing the result
// to disk (bundle: false), we still use the bundle manifest as an in-memory representation
// of our import graph, saved to disk.
const {manifest, outputFiles} = await runEsbuildOnBuildDirectory(
bundleEntrypoints,
allBuildFiles,
config,
);
// * BUNDLE: TRUE - Save the bundle result to the build directory, and clean up to remove all original
// build files that now live in the bundles.
if (options.bundle) {
for (const bundledInput of Object.keys(manifest.inputs)) {
const outputKey = path.relative(buildDirectoryLoc, path.resolve(process.cwd(), bundledInput));
if (!manifest.outputs![`/` + outputKey]) {
logger.debug(`Removing bundled source file: ${path.resolve(buildDirectoryLoc, outputKey)}`);
deleteFromBuildSafe(path.resolve(buildDirectoryLoc, outputKey), config);
}
}
deleteFromBuildSafe(
path.resolve(
buildDirectoryLoc,
removeLeadingSlash(path.posix.join(config.buildOptions.metaUrlPath, 'pkg')),
),
config,
);
for (const outputFile of outputFiles!) {
mkdirp.sync(path.dirname(outputFile.path));
await fs.writeFile(outputFile.path, outputFile.contents);
}
if (htmlEntrypoints) {
for (const htmlEntrypoint of htmlEntrypoints) {
addNewBundledCss(htmlEntrypoint, manifest, config.buildOptions.baseUrl);
}
}
}
// * BUNDLE: FALSE - Just minifying & transform the CSS & JS files in place.
else if (options.minify || options.target) {
for (const f of allBuildFiles) {
if (['.js', '.css'].includes(path.extname(f))) {
let code = await fs.readFile(f, 'utf8');
const minified = await esbuild.transform(code, {
sourcefile: path.basename(f),
loader: path.extname(f).slice(1) as 'js' | 'css',
minify: options.minify,
target: options.target,
charset: 'utf8',
});
code = minified.code;
await fs.writeFile(f, code);
}
}
}
// * Restitch any inline scripts into HTML entrypoints that had been split out
// for the sake of bundling/manifest.
if (htmlEntrypoints) {
for (const htmlEntrypoint of htmlEntrypoints) {
restitchInlineScripts(htmlEntrypoint);
}
}
// * PRELOAD: TRUE - Add preload link elements for each HTML entrypoint, to flatten
// and optimize any deep import waterfalls.
if (options.preload) {
if (options.bundle) {
throw new Error('preload is not needed when bundle=true, and cannot be used in combination.');
}
if (!htmlEntrypoints || htmlEntrypoints.length === 0) {
throw new Error('preload only works with HTML entrypoints.');
}
for (const htmlEntrypoint of htmlEntrypoints) {
preloadEntrypoint(htmlEntrypoint, manifest, config);
}
}
// * Restitch any inline scripts into HTML entrypoints that had been split out
// for the sake of bundling/manifest.
if (htmlEntrypoints) {
for (const htmlEntrypoint of htmlEntrypoints) {
restitchBaseUrl(htmlEntrypoint, config.buildOptions.baseUrl);
}
}
// Write the final HTML entrypoints to disk (if they exist).
if (htmlEntrypoints) {
for (const htmlEntrypoint of htmlEntrypoints) {
await fs.writeFile(htmlEntrypoint.file, htmlEntrypoint.root.html());
}
}
// Write the final build manifest to disk.
if (options.manifest) {
await fs.writeFile(
path.join(config.buildOptions.out, 'build-manifest.json'),
JSON.stringify(manifest),
);
}
process.chdir(originalCwd);
return;
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { EmailTemplate } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { ApiManagementClient } from "../apiManagementClient";
import {
EmailTemplateContract,
EmailTemplateListByServiceNextOptionalParams,
EmailTemplateListByServiceOptionalParams,
EmailTemplateListByServiceResponse,
TemplateName,
EmailTemplateGetEntityTagOptionalParams,
EmailTemplateGetEntityTagResponse,
EmailTemplateGetOptionalParams,
EmailTemplateGetResponse,
EmailTemplateUpdateParameters,
EmailTemplateCreateOrUpdateOptionalParams,
EmailTemplateCreateOrUpdateResponse,
EmailTemplateUpdateOptionalParams,
EmailTemplateUpdateResponse,
EmailTemplateDeleteOptionalParams,
EmailTemplateListByServiceNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing EmailTemplate operations. */
export class EmailTemplateImpl implements EmailTemplate {
private readonly client: ApiManagementClient;
/**
* Initialize a new instance of the class EmailTemplate class.
* @param client Reference to the service client
*/
constructor(client: ApiManagementClient) {
this.client = client;
}
/**
* Gets all email templates
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param options The options parameters.
*/
public listByService(
resourceGroupName: string,
serviceName: string,
options?: EmailTemplateListByServiceOptionalParams
): PagedAsyncIterableIterator<EmailTemplateContract> {
const iter = this.listByServicePagingAll(
resourceGroupName,
serviceName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByServicePagingPage(
resourceGroupName,
serviceName,
options
);
}
};
}
private async *listByServicePagingPage(
resourceGroupName: string,
serviceName: string,
options?: EmailTemplateListByServiceOptionalParams
): AsyncIterableIterator<EmailTemplateContract[]> {
let result = await this._listByService(
resourceGroupName,
serviceName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByServiceNext(
resourceGroupName,
serviceName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByServicePagingAll(
resourceGroupName: string,
serviceName: string,
options?: EmailTemplateListByServiceOptionalParams
): AsyncIterableIterator<EmailTemplateContract> {
for await (const page of this.listByServicePagingPage(
resourceGroupName,
serviceName,
options
)) {
yield* page;
}
}
/**
* Gets all email templates
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param options The options parameters.
*/
private _listByService(
resourceGroupName: string,
serviceName: string,
options?: EmailTemplateListByServiceOptionalParams
): Promise<EmailTemplateListByServiceResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, options },
listByServiceOperationSpec
);
}
/**
* Gets the entity state (Etag) version of the email template specified by its identifier.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param templateName Email Template Name Identifier.
* @param options The options parameters.
*/
getEntityTag(
resourceGroupName: string,
serviceName: string,
templateName: TemplateName,
options?: EmailTemplateGetEntityTagOptionalParams
): Promise<EmailTemplateGetEntityTagResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, templateName, options },
getEntityTagOperationSpec
);
}
/**
* Gets the details of the email template specified by its identifier.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param templateName Email Template Name Identifier.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
serviceName: string,
templateName: TemplateName,
options?: EmailTemplateGetOptionalParams
): Promise<EmailTemplateGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, templateName, options },
getOperationSpec
);
}
/**
* Updates an Email Template.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param templateName Email Template Name Identifier.
* @param parameters Email Template update parameters.
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
serviceName: string,
templateName: TemplateName,
parameters: EmailTemplateUpdateParameters,
options?: EmailTemplateCreateOrUpdateOptionalParams
): Promise<EmailTemplateCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, templateName, parameters, options },
createOrUpdateOperationSpec
);
}
/**
* Updates API Management email template
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param templateName Email Template Name Identifier.
* @param ifMatch ETag of the Entity. ETag should match the current entity state from the header
* response of the GET request or it should be * for unconditional update.
* @param parameters Update parameters.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
serviceName: string,
templateName: TemplateName,
ifMatch: string,
parameters: EmailTemplateUpdateParameters,
options?: EmailTemplateUpdateOptionalParams
): Promise<EmailTemplateUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
serviceName,
templateName,
ifMatch,
parameters,
options
},
updateOperationSpec
);
}
/**
* Reset the Email Template to default template provided by the API Management service instance.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param templateName Email Template Name Identifier.
* @param ifMatch ETag of the Entity. ETag should match the current entity state from the header
* response of the GET request or it should be * for unconditional update.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
serviceName: string,
templateName: TemplateName,
ifMatch: string,
options?: EmailTemplateDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, templateName, ifMatch, options },
deleteOperationSpec
);
}
/**
* ListByServiceNext
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param nextLink The nextLink from the previous successful call to the ListByService method.
* @param options The options parameters.
*/
private _listByServiceNext(
resourceGroupName: string,
serviceName: string,
nextLink: string,
options?: EmailTemplateListByServiceNextOptionalParams
): Promise<EmailTemplateListByServiceNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, nextLink, options },
listByServiceNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listByServiceOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/templates",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.EmailTemplateCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.filter,
Parameters.top,
Parameters.skip,
Parameters.apiVersion
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const getEntityTagOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/templates/{templateName}",
httpMethod: "HEAD",
responses: {
200: {
headersMapper: Mappers.EmailTemplateGetEntityTagHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.templateName
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/templates/{templateName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.EmailTemplateContract,
headersMapper: Mappers.EmailTemplateGetHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.templateName
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/templates/{templateName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.EmailTemplateContract
},
201: {
bodyMapper: Mappers.EmailTemplateContract
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters29,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.templateName
],
headerParameters: [
Parameters.accept,
Parameters.contentType,
Parameters.ifMatch
],
mediaType: "json",
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/templates/{templateName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.EmailTemplateContract,
headersMapper: Mappers.EmailTemplateUpdateHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters29,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.templateName
],
headerParameters: [
Parameters.accept,
Parameters.contentType,
Parameters.ifMatch1
],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/templates/{templateName}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.templateName
],
headerParameters: [Parameters.accept, Parameters.ifMatch1],
serializer
};
const listByServiceNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.EmailTemplateCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.filter,
Parameters.top,
Parameters.skip,
Parameters.apiVersion
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import { Directionality } from '@angular/cdk/bidi';
import {
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
EventEmitter,
Input,
Optional,
Output,
ViewChild,
ViewEncapsulation
} from '@angular/core';
import { DateAdapter } from '@ptsecurity/cdk/datetime';
import {
DOWN_ARROW,
END,
ENTER,
HOME,
LEFT_ARROW,
PAGE_DOWN,
PAGE_UP,
RIGHT_ARROW,
UP_ARROW,
SPACE
} from '@ptsecurity/cdk/keycodes';
import { McCalendarBody, McCalendarCell } from './calendar-body.component';
import { createMissingDateImplError } from './datepicker-errors';
export const yearsPerPage = 24;
export const yearsPerRow = 4;
/**
* An internal component used to display a year selector in the datepicker.
* @docs-private
*/
@Component({
selector: 'mc-multi-year-view',
exportAs: 'mcMultiYearView',
templateUrl: 'multi-year-view.html',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class McMultiYearView<D> implements AfterContentInit {
/** The date to display in this multi-year view (everything other than the year is ignored). */
@Input()
get activeDate(): D {
return this._activeDate;
}
set activeDate(value: D) {
const oldActiveDate = this._activeDate;
const validDate =
this.getValidDateOrNull(this.dateAdapter.deserialize(value)) || this.dateAdapter.today();
this._activeDate = this.dateAdapter.clampDate(validDate, this.minDate, this.maxDate);
if (Math.floor(this.dateAdapter.getYear(oldActiveDate) / yearsPerPage) !==
Math.floor(this.dateAdapter.getYear(this._activeDate) / yearsPerPage)) {
this.init();
}
}
/** The currently selected date. */
@Input()
get selected(): D | null {
return this._selected;
}
set selected(value: D | null) {
this._selected = this.getValidDateOrNull(this.dateAdapter.deserialize(value));
this.selectedYear = this._selected && this.dateAdapter.getYear(this._selected);
}
/** The minimum selectable date. */
@Input()
get minDate(): D | null {
return this._minDate;
}
set minDate(value: D | null) {
this._minDate = this.getValidDateOrNull(this.dateAdapter.deserialize(value));
}
/** The maximum selectable date. */
@Input()
get maxDate(): D | null {
return this._maxDate;
}
set maxDate(value: D | null) {
this._maxDate = this.getValidDateOrNull(this.dateAdapter.deserialize(value));
}
/** A function used to filter which dates are selectable. */
@Input() dateFilter: (date: D) => boolean;
/** Emits when a new year is selected. */
@Output() readonly selectedChange: EventEmitter<D> = new EventEmitter<D>();
/** Emits the selected year. This doesn't imply a change on the selected date */
@Output() readonly yearSelected: EventEmitter<D> = new EventEmitter<D>();
/** Emits when any date is activated. */
@Output() readonly activeDateChange: EventEmitter<D> = new EventEmitter<D>();
/** The body of calendar table */
@ViewChild(McCalendarBody, {static: false}) mcCalendarBody: McCalendarBody;
/** Grid of calendar cells representing the currently displayed years. */
years: McCalendarCell[][];
/** The year that today falls on. */
todayYear: number;
/** The year of the selected date. Null if the selected date is null. */
selectedYear: number | null;
private _activeDate: D;
private _selected: D | null;
private _minDate: D | null;
private _maxDate: D | null;
constructor(
private readonly changeDetectorRef: ChangeDetectorRef,
@Optional() public dateAdapter: DateAdapter<D>,
@Optional() private dir?: Directionality
) {
if (!this.dateAdapter) {
throw createMissingDateImplError('DateAdapter');
}
this._activeDate = this.dateAdapter.today();
}
ngAfterContentInit() {
this.init();
}
/** Initializes this multi-year view. */
init() {
this.todayYear = this.dateAdapter.getYear(this.dateAdapter.today());
const activeYear = this.dateAdapter.getYear(this._activeDate);
const activeOffset = activeYear % yearsPerPage;
this.years = [];
for (let i = 0, row: number[] = []; i < yearsPerPage; i++) {
row.push(activeYear - activeOffset + i);
if (row.length === yearsPerRow) {
this.years.push(row.map((year) => this.createCellForYear(year)));
row = [];
}
}
this.changeDetectorRef.markForCheck();
}
/** Handles when a new year is selected. */
onYearSelected(year: number) {
this.yearSelected.emit(this.dateAdapter.createDate(year));
const month = this.dateAdapter.getMonth(this.activeDate);
const daysInMonth =
this.dateAdapter.getNumDaysInMonth(this.dateAdapter.createDate(year, month));
this.selectedChange.emit(
this.dateAdapter.createDate(year, month, Math.min(this.dateAdapter.getDate(this.activeDate), daysInMonth))
);
}
/** Handles keydown events on the calendar body when calendar is in multi-year view. */
handleCalendarBodyKeydown(event: KeyboardEvent): void {
// TODO(mmalerba): We currently allow keyboard navigation to disabled dates, but just prevent
// disabled ones from being selected. This may not be ideal, we should look into whether
// navigation should skip over disabled dates, and if so, how to implement that efficiently.
const oldActiveDate = this._activeDate;
const isRtl = this.isRtl();
// tslint:disable-next-line:deprecation
switch (event.keyCode) {
case LEFT_ARROW:
this.activeDate = this.dateAdapter.addCalendarYears(this._activeDate, isRtl ? 1 : -1);
break;
case RIGHT_ARROW:
this.activeDate = this.dateAdapter.addCalendarYears(this._activeDate, isRtl ? -1 : 1);
break;
case UP_ARROW:
this.activeDate = this.dateAdapter.addCalendarYears(this._activeDate, -yearsPerRow);
break;
case DOWN_ARROW:
this.activeDate = this.dateAdapter.addCalendarYears(this._activeDate, yearsPerRow);
break;
case HOME:
this.activeDate = this.dateAdapter.addCalendarYears(
this._activeDate,
-this.dateAdapter.getYear(this._activeDate) % yearsPerPage
);
break;
case END:
this.activeDate = this.dateAdapter.addCalendarYears(
this._activeDate,
yearsPerPage - this.dateAdapter.getYear(this._activeDate) % yearsPerPage - 1
);
break;
case PAGE_UP:
this.activeDate =
this.dateAdapter.addCalendarYears(
this._activeDate, event.altKey ? -yearsPerPage * 10 : -yearsPerPage);
break;
case PAGE_DOWN:
this.activeDate =
this.dateAdapter.addCalendarYears(
this._activeDate, event.altKey ? yearsPerPage * 10 : yearsPerPage);
break;
case ENTER:
case SPACE:
this.onYearSelected(this.dateAdapter.getYear(this._activeDate));
break;
default:
// Don't prevent default or focus active cell on keys that we don't explicitly handle.
return;
}
if (this.dateAdapter.compareDate(oldActiveDate, this.activeDate)) {
this.activeDateChange.emit(this.activeDate);
}
this.focusActiveCell();
// Prevent unexpected default actions such as form submission.
event.preventDefault();
}
getActiveCell(): number {
return this.dateAdapter.getYear(this.activeDate) % yearsPerPage;
}
/** Focuses the active cell after the microtask queue is empty. */
focusActiveCell() {
this.mcCalendarBody.focusActiveCell();
}
/** Creates an McCalendarCell for the given year. */
private createCellForYear(year: number) {
const yearName = this.dateAdapter.getYearName(this.dateAdapter.createDate(year));
return new McCalendarCell(year, yearName, yearName, this.shouldEnableYear(year));
}
/** Whether the given year is enabled. */
private shouldEnableYear(year: number) {
// disable if the year is greater than maxDate lower than minDate
if (year === undefined || year === null ||
(this.maxDate && year > this.dateAdapter.getYear(this.maxDate)) ||
(this.minDate && year < this.dateAdapter.getYear(this.minDate))) {
return false;
}
// enable if it reaches here and there's no filter defined
if (!this.dateFilter) {
return true;
}
const firstOfYear = this.dateAdapter.createDate(year);
// If any date in the year is enabled count the year as enabled.
for (let date = firstOfYear; this.dateAdapter.getYear(date) === year;
date = this.dateAdapter.addCalendarDays(date, 1)) {
if (this.dateFilter(date)) {
return true;
}
}
return false;
}
/**
* @param obj The object to check.
* @returns The given object if it is both a date instance and valid, otherwise null.
*/
private getValidDateOrNull(obj: any): D | null {
return (this.dateAdapter.isDateInstance(obj) && this.dateAdapter.isValid(obj)) ? obj : null;
}
/** Determines whether the user has the RTL layout direction. */
private isRtl() {
return this.dir && this.dir.value === 'rtl';
}
} | the_stack |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="ru_RU">
<context>
<name>UIHATControls</name>
<message>
<source>Head Arduino Tracker settings FaceTrackNoIR</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>General</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Serial port</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Zero</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Reset</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Axis Configuration</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Associate Axis</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>RotX</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>RotY</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>RotZ</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Enable Axis</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Pitch:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Enable</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Yaw:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Invert</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Y:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Invert Axis</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>X:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>X</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Y</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Z</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Roll:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Z:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Axis</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Status</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Trame per seconde</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>tps</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Info:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>HAT STOPPED</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Command</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Arduino Commands</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Init</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Start</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Command for Start send sequence</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Command for Initialising Arduino</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Command for Stop send sequence</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Center</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Stop</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Command for read Center Gyro arduino</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Command for Reset Arduino</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Command for reset Center Gyro arduino</source>
<translation type="unfinished"></translation>
</message>
<message>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Little or Big Endian for <span style=" font-family:'Arial,Geneva,Helvetica,sans-serif'; font-size:medium; color:#000000;">the serialization of byte order</span></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Arial,Geneva,Helvetica,sans-serif'; font-size:medium; color:#000000;">Arduino is LittleEndian ( unchecked)</span></p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Endian</source>
<translation type="unfinished"></translation>
</message>
<message>
<source><html><head/><body><p>Indicate at opentrack speed sketch FPS to adjust CPU </p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Delay before Init command in ms</span></p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Delay after Init command in ms</span></p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Delay</source>
<translation type="unfinished"></translation>
</message>
<message>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Delay after Start Command in ms</span></p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Delay after startup</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Serial Parameters</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Flow control</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Stop bits</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Parity</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>BaudRate:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Data bits</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>About</source>
<translation type="unfinished"></translation>
</message>
<message>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;">
<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt; font-weight:600;">FTNoIR HAT Plugin<br />by FuraX49</span></p>
<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="http://hatire.sourceforge.net/"><span style=" font-size:8pt; font-weight:600; text-decoration: underline; color:#0000ff;">Manual (external)</span></a></p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Version 1.0.0</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Send</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Disable when not in use, will have a performance impact</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Enable logging to diagnostic file</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>dialog_hatire</name>
<message>
<source>Version %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>HAT START</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>HAT STOPPED</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>hatire</name>
<message>
<source>Unable to open ComPort: %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Unknown error</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>hatire_metadata</name>
<message>
<source>Hatire Arduino</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>hatire_thread</name>
<message>
<source>Timeout during writing command</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>COM port not open</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Setting serial port name</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Opening serial port</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Port Open</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Port Parameters set</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Raising DTR</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Raising RTS</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Waiting on init</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Port setup, waiting for HAT frames to process</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS> | the_stack |
import * as vscode from 'vscode';
import { ExtensionUtil } from '../../extension/util/ExtensionUtil';
import { VSCodeBlockchainOutputAdapter } from '../../extension/logging/VSCodeBlockchainOutputAdapter';
import { TestUtil } from '../TestUtil';
import * as chai from 'chai';
import * as sinon from 'sinon';
import { ExtensionCommands } from '../../ExtensionCommands';
import { FabricGatewayConnectionManager } from '../../extension/fabric/FabricGatewayConnectionManager';
import { FabricEnvironmentRegistryEntry, FabricRuntimeUtil, LogType, FabricEnvironmentRegistry, EnvironmentType, FabricGatewayRegistry, FabricGatewayRegistryEntry, EnvironmentFlags } from 'ibm-blockchain-platform-common';
import { FabricEnvironmentManager } from '../../extension/fabric/environments/FabricEnvironmentManager';
import { UserInputUtil, IBlockchainQuickPickItem } from '../../extension/commands/UserInputUtil';
import { EnvironmentFactory } from '../../extension/fabric/environments/EnvironmentFactory';
import { RuntimeTreeItem } from '../../extension/explorer/runtimeOps/disconnectedTree/RuntimeTreeItem';
import { BlockchainEnvironmentExplorerProvider } from '../../extension/explorer/environmentExplorer';
import { LocalMicroEnvironmentManager } from '../../extension/fabric/environments/LocalMicroEnvironmentManager';
import { LocalMicroEnvironment } from '../../extension/fabric/environments/LocalMicroEnvironment';
chai.should();
// tslint:disable no-unused-expression
describe('restartFabricRuntime', () => {
const sandbox: sinon.SinonSandbox = sinon.createSandbox();
const connectionRegistry: FabricGatewayRegistry = FabricGatewayRegistry.instance();
let getGatewayRegistryEntryStub: sinon.SinonStub;
let getEnvironmentRegistryEntryStub: sinon.SinonStub;
let logSpy: sinon.SinonSpy;
let popupStub: sinon.SinonStub;
let restartStub: sinon.SinonStub;
let executeCommandSpy: sinon.SinonSpy;
let getConnectionStub: sinon.SinonStub;
let showFabricEnvironmentQuickPickBoxStub: sinon.SinonStub;
let localRegistryEntry: FabricEnvironmentRegistryEntry;
before(async () => {
await TestUtil.setupTests(sandbox);
});
beforeEach(async () => {
await ExtensionUtil.activateExtension();
await connectionRegistry.clear();
await TestUtil.startLocalFabric();
await LocalMicroEnvironmentManager.instance().ensureRuntime(FabricRuntimeUtil.LOCAL_FABRIC, undefined, 1);
const localGateway: FabricGatewayRegistryEntry = await FabricGatewayRegistry.instance().get(`${FabricRuntimeUtil.LOCAL_FABRIC} - Org1 Gateway`);
getGatewayRegistryEntryStub = sandbox.stub(FabricGatewayConnectionManager.instance(), 'getGatewayRegistryEntry');
getGatewayRegistryEntryStub.resolves(localGateway);
getEnvironmentRegistryEntryStub = sandbox.stub(FabricEnvironmentManager.instance(), 'getEnvironmentRegistryEntry');
getConnectionStub = sandbox.stub(FabricEnvironmentManager.instance(), 'getConnection');
getConnectionStub.returns(undefined);
const localEnvironment: FabricEnvironmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(FabricRuntimeUtil.LOCAL_FABRIC);
getEnvironmentRegistryEntryStub.returns(localEnvironment);
logSpy = sandbox.spy(VSCodeBlockchainOutputAdapter.instance(), 'log');
popupStub = sandbox.stub(UserInputUtil, 'failedNetworkStart').resolves();
executeCommandSpy = sandbox.spy(vscode.commands, 'executeCommand');
localRegistryEntry = await FabricEnvironmentRegistry.instance().get(FabricRuntimeUtil.LOCAL_FABRIC);
showFabricEnvironmentQuickPickBoxStub = sandbox.stub(UserInputUtil, 'showFabricEnvironmentQuickPickBox');
showFabricEnvironmentQuickPickBoxStub.resolves({label: FabricRuntimeUtil.LOCAL_FABRIC, data: localRegistryEntry});
});
afterEach(async () => {
sandbox.restore();
await connectionRegistry.clear();
});
it('should do nothing and report a warning on Eclipse Che', async () => {
sandbox.stub(ExtensionUtil, 'isChe').returns(true);
await vscode.commands.executeCommand(ExtensionCommands.RESTART_FABRIC_SHORT);
logSpy.should.have.been.calledWithExactly(LogType.ERROR, sinon.match(/not supported/));
});
it('should restart a Fabric environment from the tree', async () => {
const environment: LocalMicroEnvironment = EnvironmentFactory.getEnvironment(localRegistryEntry) as LocalMicroEnvironment;
restartStub = sandbox.stub(environment, 'restart').resolves();
const blockchainEnvironmentExplorerProvider: BlockchainEnvironmentExplorerProvider = ExtensionUtil.getBlockchainEnvironmentExplorerProvider();
const treeItem: RuntimeTreeItem = await RuntimeTreeItem.newRuntimeTreeItem(blockchainEnvironmentExplorerProvider,
environment.getName(),
localRegistryEntry,
{
command: ExtensionCommands.CONNECT_TO_ENVIRONMENT,
title: '',
arguments: [localRegistryEntry]
},
environment
);
getGatewayRegistryEntryStub.resolves();
getEnvironmentRegistryEntryStub.returns(undefined);
await vscode.commands.executeCommand(ExtensionCommands.RESTART_FABRIC_SHORT, treeItem);
restartStub.should.have.been.called.calledOnceWithExactly(VSCodeBlockchainOutputAdapter.instance());
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.DISCONNECT_GATEWAY);
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.DISCONNECT_ENVIRONMENT);
logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, 'restartFabricRuntime');
});
it('should restart a Fabric runtime, disconnect from gateway and refresh the view', async () => {
const environment: LocalMicroEnvironment = EnvironmentFactory.getEnvironment(localRegistryEntry) as LocalMicroEnvironment;
restartStub = sandbox.stub(environment, 'restart').resolves();
const blockchainEnvironmentExplorerProvider: BlockchainEnvironmentExplorerProvider = ExtensionUtil.getBlockchainEnvironmentExplorerProvider();
const treeItem: RuntimeTreeItem = await RuntimeTreeItem.newRuntimeTreeItem(blockchainEnvironmentExplorerProvider,
environment.getName(),
localRegistryEntry,
{
command: ExtensionCommands.CONNECT_TO_ENVIRONMENT,
title: '',
arguments: [localRegistryEntry]
},
environment
);
getEnvironmentRegistryEntryStub.returns(undefined);
await vscode.commands.executeCommand(ExtensionCommands.RESTART_FABRIC_SHORT, treeItem);
restartStub.should.have.been.called.calledOnceWithExactly(VSCodeBlockchainOutputAdapter.instance());
executeCommandSpy.should.have.been.calledWith(ExtensionCommands.DISCONNECT_GATEWAY);
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.DISCONNECT_ENVIRONMENT);
logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, 'restartFabricRuntime');
});
it('should restart a Fabric runtime, disconnect from environment and refresh the view', async () => {
const environment: LocalMicroEnvironment = EnvironmentFactory.getEnvironment(localRegistryEntry) as LocalMicroEnvironment;
restartStub = sandbox.stub(environment, 'restart').resolves();
const blockchainEnvironmentExplorerProvider: BlockchainEnvironmentExplorerProvider = ExtensionUtil.getBlockchainEnvironmentExplorerProvider();
const treeItem: RuntimeTreeItem = await RuntimeTreeItem.newRuntimeTreeItem(blockchainEnvironmentExplorerProvider,
environment.getName(),
localRegistryEntry,
{
command: ExtensionCommands.CONNECT_TO_ENVIRONMENT,
title: '',
arguments: [localRegistryEntry]
},
environment
);
getGatewayRegistryEntryStub.resolves();
await vscode.commands.executeCommand(ExtensionCommands.RESTART_FABRIC_SHORT, treeItem);
restartStub.should.have.been.called.calledOnceWithExactly(VSCodeBlockchainOutputAdapter.instance());
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.DISCONNECT_GATEWAY);
executeCommandSpy.should.have.been.calledWith(ExtensionCommands.DISCONNECT_ENVIRONMENT);
logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, 'restartFabricRuntime');
});
it('should restart local connected environment (called from three dot menu)', async () => {
getConnectionStub.returns({});
const environment: LocalMicroEnvironment = EnvironmentFactory.getEnvironment(localRegistryEntry) as LocalMicroEnvironment;
restartStub = sandbox.stub(environment, 'restart').resolves();
getGatewayRegistryEntryStub.resolves();
await vscode.commands.executeCommand(ExtensionCommands.RESTART_FABRIC);
showFabricEnvironmentQuickPickBoxStub.should.not.have.been.called;
restartStub.should.have.been.called.calledOnceWithExactly(VSCodeBlockchainOutputAdapter.instance());
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.DISCONNECT_GATEWAY);
executeCommandSpy.should.have.been.calledWith(ExtensionCommands.DISCONNECT_ENVIRONMENT);
logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, 'restartFabricRuntime');
});
it('should ask what environment to restart if connected to non-managed environment', async () => {
getEnvironmentRegistryEntryStub.returns({name: 'otherEnvironment', environmentType: EnvironmentType.ENVIRONMENT} as FabricEnvironmentRegistryEntry);
const environment: LocalMicroEnvironment = EnvironmentFactory.getEnvironment(localRegistryEntry) as LocalMicroEnvironment;
restartStub = sandbox.stub(environment, 'restart').resolves();
getGatewayRegistryEntryStub.resolves();
showFabricEnvironmentQuickPickBoxStub.resolves({label: FabricRuntimeUtil.LOCAL_FABRIC, data: localRegistryEntry} as IBlockchainQuickPickItem<FabricEnvironmentRegistryEntry>);
await vscode.commands.executeCommand(ExtensionCommands.RESTART_FABRIC);
showFabricEnvironmentQuickPickBoxStub.should.have.been.calledOnceWithExactly('Select an environment to restart', false, true, [EnvironmentFlags.LOCAL], [], true);
restartStub.should.have.been.called.calledOnceWithExactly(VSCodeBlockchainOutputAdapter.instance());
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.DISCONNECT_GATEWAY);
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.DISCONNECT_ENVIRONMENT);
logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, 'restartFabricRuntime');
});
it('should display an error if restarting Fabric Runtime fails', async () => {
const error: Error = new Error('what the fabric has happened');
const environment: LocalMicroEnvironment = EnvironmentFactory.getEnvironment(localRegistryEntry) as LocalMicroEnvironment;
restartStub = sandbox.stub(environment, 'restart').throws(error);
const blockchainEnvironmentExplorerProvider: BlockchainEnvironmentExplorerProvider = ExtensionUtil.getBlockchainEnvironmentExplorerProvider();
const treeItem: RuntimeTreeItem = await RuntimeTreeItem.newRuntimeTreeItem(blockchainEnvironmentExplorerProvider,
environment.getName(),
localRegistryEntry,
{
command: ExtensionCommands.CONNECT_TO_ENVIRONMENT,
title: '',
arguments: [localRegistryEntry]
},
environment
);
getGatewayRegistryEntryStub.resolves();
getEnvironmentRegistryEntryStub.returns(undefined);
await vscode.commands.executeCommand(ExtensionCommands.RESTART_FABRIC_SHORT, treeItem);
restartStub.should.have.been.called.calledOnceWithExactly(VSCodeBlockchainOutputAdapter.instance());
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.DISCONNECT_GATEWAY);
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.DISCONNECT_ENVIRONMENT);
popupStub.should.have.been.calledWithExactly(`Failed to restart ${environment.getName()}: ${error.message}`,
`Failed to restart ${environment.getName()}: ${error.toString()}`);
});
it('should be able to restart the an environment from the command', async () => {
showFabricEnvironmentQuickPickBoxStub.resolves({label: FabricRuntimeUtil.LOCAL_FABRIC, data: localRegistryEntry} as IBlockchainQuickPickItem<FabricEnvironmentRegistryEntry>);
const environment: LocalMicroEnvironment = EnvironmentFactory.getEnvironment(localRegistryEntry) as LocalMicroEnvironment;
restartStub = sandbox.stub(environment, 'restart').resolves();
getGatewayRegistryEntryStub.resolves();
getEnvironmentRegistryEntryStub.returns(undefined);
await vscode.commands.executeCommand(ExtensionCommands.RESTART_FABRIC);
showFabricEnvironmentQuickPickBoxStub.should.have.been.calledOnceWithExactly('Select an environment to restart', false, true, [EnvironmentFlags.LOCAL], [], true);
restartStub.should.have.been.called.calledOnceWithExactly(VSCodeBlockchainOutputAdapter.instance());
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.DISCONNECT_GATEWAY);
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.DISCONNECT_ENVIRONMENT);
logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, 'restartFabricRuntime');
});
it('should be able to cancel choosing an environment to restart', async () => {
showFabricEnvironmentQuickPickBoxStub.resolves(undefined);
await vscode.commands.executeCommand(ExtensionCommands.RESTART_FABRIC);
showFabricEnvironmentQuickPickBoxStub.should.have.been.calledOnceWithExactly('Select an environment to restart', false, true, [EnvironmentFlags.LOCAL], [], true);
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.DISCONNECT_GATEWAY);
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.DISCONNECT_ENVIRONMENT);
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.REFRESH_ENVIRONMENTS);
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.REFRESH_GATEWAYS);
logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, 'restartFabricRuntime');
});
it(`shouldn't disconnect from the connected gateway if the environment isn't associated`, async () => {
showFabricEnvironmentQuickPickBoxStub.resolves({label: FabricRuntimeUtil.LOCAL_FABRIC, data: localRegistryEntry});
restartStub = sandbox.stub(LocalMicroEnvironment.prototype, 'restart').resolves();
getEnvironmentRegistryEntryStub.returns(undefined);
const localEnv: LocalMicroEnvironment = EnvironmentFactory.getEnvironment(localRegistryEntry) as LocalMicroEnvironment;
sandbox.stub(EnvironmentFactory, 'getEnvironment').returns(localEnv);
getGatewayRegistryEntryStub.resolves({
name: 'SomeGateway',
fromEnvironment: 'SomeEnvironment'
} as FabricGatewayRegistryEntry);
await vscode.commands.executeCommand(ExtensionCommands.RESTART_FABRIC);
showFabricEnvironmentQuickPickBoxStub.should.have.been.calledOnceWithExactly('Select an environment to restart', false, true, [EnvironmentFlags.LOCAL], [], true);
restartStub.should.have.been.called.calledOnceWithExactly(VSCodeBlockchainOutputAdapter.instance());
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.DISCONNECT_GATEWAY);
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.DISCONNECT_ENVIRONMENT);
logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, 'restartFabricRuntime');
});
}); | the_stack |
import { normalize } from '../ts';
import * as vm from 'vm';
function normalizeEquiv(original: string) {
let compiled = normalize(original);
expect(compiled.trim()).not.toEqual(original.trim());
let originalResult = vm.runInNewContext(original);
let normalizedResult = vm.runInNewContext(compiled);
// Sanity check: a test that produces undefined is unlikely to be useful.
expect(originalResult).not.toBe(undefined);
expect(normalizedResult).toEqual(originalResult);
return compiled;
}
test('simple for loop', () => {
normalizeEquiv(`
let r = 0;
for (let i = 0; i < 3; i++) {
r = r + i;
}
r;
`);
});
test('for loop without block body', () => {
normalizeEquiv(`
let r = 0;
for (let i = 0; i < 3; i++) {
r = r + i;
}
r;
`);
});
test('ternary short-circuit', () => {
let compiled = normalizeEquiv(`
function foo() {
throw 'This should not be called'
}
true ? 1 : foo()
`);
// Sanity check: ? should not be in output.
expect(compiled.indexOf('?')).toBe(-1);
});
test('ternary left method call short-circuit', () => {
normalizeEquiv(`
let x = 0;
let y = 0;
function foo() {
x++;
return {
bar() {
y++;
}
}
}
let r = true ? foo().bar() : false;
({ x: x, y: y });
`);
});
test('conjunction and function call in loop guard', () => {
normalizeEquiv(`
let i = 0;
let j = 6;
function f() {
return (i++ % 2) === 0;
}
while (f() && j++) { }
({ i: i, j: j });
`);
});
test('and should evaluate its LHS just once', () => {
normalizeEquiv(`
var count = 0;
function f() {
count++;
return false;
}
var tmp = f() && true;
({ count: count });
`);
});
test('applications in array literal must be evaluated in order', () => {
normalizeEquiv(`
function foo() {
let counter = 0;
function bar() {
return ++counter;
}
return [
counter,
bar(),
bar(),
];
}
var r = foo();
r;
`);
});
test('simple for .. in loop', () => {
normalizeEquiv(`
const obj = {
a: 0,
b: 1,
c: 2,
};
let r = [ ];
for (const prop in obj) {
r.push(obj[prop]);
}
r;
`);
});
test('using var like let*', () => {
normalizeEquiv(`
var a = { x: 100 }, y = a.x;
y === 100;
`);
});
test('left-to-right evaluation of +: application on LHS', () => {
normalizeEquiv(`
let x = 1;
function a() {
x += 1;
return 1;
}
a() + x;
`);
});
test.skip('left-to-right evaluation of +: application on RHS', () => {
normalizeEquiv(`
let x = 1;
function a() {
x += 1;
return 1;
}
x + a();
`);
});
test('left-to-right evaluation of +: application on both sides', () => {
normalizeEquiv(`
let x = 1;
function a() { x += 1; return 1; }
function b() { x *= 10; return 2; }
a() + b();
`);
});
test('and short-circuiting: method call on RHS', () => {
normalizeEquiv(`
let x = 0;
let y = 0;
function foo() {
x++;
return {
bar() {
y++;
}
}
}
false && foo().bar();
({ x: x, y: y });
`);
});
test('and not short-circuiting: method call on RHS', () => {
normalizeEquiv(`
let x = 0;
let y = 0;
function foo() {
x++;
return {
bar() {
y++;
}
}
}
true && foo().bar();
({ x: x, y: y });
`);
});
test('assignments in sequence expression', () => {
normalizeEquiv(`
function g() {
return 1;
}
function f(x) {
var y = x;
var dummy = g(), z = y;
return z;
};
var r = f(100);
r;
`);
});
test('break in for loop', () => {
normalizeEquiv(`
let sum = 0;
for(let i = 0; i < 5; i++) {
sum += i;
if (i === 3) break;
}
sum;
`);
});
test('function declaration hoisting (based on code generated by Dart2js)', () => {
// TODO(arjun): This test should produce something.
normalizeEquiv(`
let r = (function () {
function Isolate() {
}
init();
function init() {
Isolate.$isolateProperties = Object.create(null);
Isolate.$finishIsolateConstructor = function (oldIsolate) {
var isolateProperties = oldIsolate.$isolateProperties;
function Isolate() {
}
Isolate.$isolateProperties = isolateProperties;
return Isolate;
};
}
Isolate = Isolate.$finishIsolateConstructor(Isolate);
})();
true;
`);
});
test('function declaration hoisting (also based on code generated by Dart2js)', () => {
normalizeEquiv(`
function Isolate() {
}
var init = function() {
Date.now();
Isolate.method = function (oldIsolate) {
return 50;
};
}
init();
Isolate = Isolate.method(Isolate);
Isolate;
`);
});
test('nested ternary expressions', () => {
normalizeEquiv(`
function Foo() {}
function Bar() {}
function Baz() {}
function foo() {
const o = {};
return (o.left instanceof Foo) ? new Baz(o.left.error) :
((o.right instanceof Bar) ? new Baz(o.right.error) : 7);
}
var r = foo();
r;
`);
});
test('short-circuiting with && and ||', () => {
normalizeEquiv(`
const f = false;
let x = 0;
f && (x++ === 7);
f || (x++ === 7);
x;
`);
});
test('left-to-right evaluation: application in second argument assigns to variable referenced in first argument', () => {
normalizeEquiv(`
function foo() {
let counter = 0;
function bar(c1, c2) {
++counter;
return c1;
}
return bar(counter, bar(counter));
}
let r = foo();
r;
`);
});
test('computed method call', () => {
normalizeEquiv(`
function foo() { return 7; }
let r = foo['call']({});
r;
`);
});
test('switch fallthrough test', () => {
normalizeEquiv(`
let test = 'test';
let test2;
switch (test) {
case 'baz':
test = 'baz';
case 'test':
case 'foo':
case 'bar':
test2 = test;
default:
test = 'baz';
}
({ test: test, test2: test2 });
`);
});
test('local variable with the same name as the enclosing function', () => {
normalizeEquiv(`
var BAR = function BAR2() {
while(false);
}
var x = function FOO() {
var FOO = 100;
BAR();
return FOO;
}
let r = x();
r;
`);
});
test('pointless: calling increment', () => {
normalizeEquiv(`
function inc(x) { return x + 1; }
const a = (function (x, y) { return inc(x) + inc(y) })(1, 2)
a;
`);
});
test('continue to a label in a for loop', () => {
normalizeEquiv(`
let i = 0;
l: for (let j = 0; j < 10; j++) {
if (j % 2 === 0) {
i++;
do {
continue l;
} while (0);
i++;
}
}
i;
`);
});
test('continue to a label in a nested loop', () => {
normalizeEquiv(`
var i = 0;
var j = 8;
checkiandj: while (i < 4) {
i += 1;
checkj: while (j > 4) {
j -= 1;
if ((j % 2) === 0) {
i = 5;
continue checkj;
}
}
}
({i: i, j: j});
`);
});
test('continue to a label in a nested loop', () => {
normalizeEquiv(`
var i = 0;
var j = 8;
checkiandj: while (i < 4) {
i += 1;
checkj: while (j > 4) {
j -= 1;
if ((j % 2) === 0) {
i = 5;
continue checkiandj;
}
}
}
({i: i, j: j});
`);
});
test('applications in object literal', () => {
normalizeEquiv(`
function foo() {
let counter = 0;
function bar() {
return ++counter;
}
return {
a: counter,
b: bar(),
c: bar()
};
}
const o = foo();
o;
`);
});
test('|| short-circuiting: method call on RHS with true on LHS', () => {
// TODO(arjun): Ensure we don't trivially simplify true || X to true.
normalizeEquiv(`
function foo() {
throw 'bad';
return {
bar() {
throw 'very bad';
}
};
}
true || foo().bar();
true;
`);
});
test('|| short-circuiting: method call on RHS with false on LHS', () => {
// TODO(arjun): Ensure we don't trivially simplify false || X to X.
normalizeEquiv(`
let x = 0;
let y = 0;
function foo() {
x++;
return {
bar() {
y++;
}
}
}
false || foo().bar();
({ x: x, y: y });
`);
});
test('sequencing expression in loop guard', () => {
normalizeEquiv(`
var i = 0;
var j = 0;
var loop = true;
while(i = i + 1, loop) {
j = j + 1;
loop = j < 2;
}
i;
`);
});
test('sequencing with application in loop guard', () => {
normalizeEquiv(`
var x = 0;
var r;
function AFUNCTION() {
x++;
r = x < 2;
}
while(AFUNCTION(), r) { }
x;
`);
});
test('sequencing: applications occur in order', () => {
normalizeEquiv(`
var i = 0;
let j = 0;
let k = 0;
function f() {
j = i;
i = 1;
}
function g() {
k = i;
i = 2;
}
function h() {
return f(), g(), i;
}
h();
({ i: i, j: j, k: k });
`);
});
test('switch in a while loop', () => {
normalizeEquiv(`
const tst = 'foo';
let x = 0;
let i = 0;
while (i++ < 10) {
switch (tst) {
case 'bar':
throw 'A';
break;
case 'foo': {
x++;
break;
}
default:
throw 'B';
}
if (i !== x) {
throw 'C';
}
}
x;
`);
});
test('break out of while(true)', () => {
normalizeEquiv(`
let i = 0;
while (true) {
i++;
if (i === 10)
break;
}
i;
`);
});
test('return statement in while(true)', () => {
normalizeEquiv(`
function foo() {
let i = 0;
while (true) {
if (++i > 9) {
return i;
}
}
}
let r = foo();
r;
`);
});
test('uninitialized variable', () => {
normalizeEquiv(`
let t;
t = 1;
t;
`);
});
test('compound conditional', () => {
normalizeEquiv(`
function F(x) {
return x;
}
let i = 0;
if(F(true) && F(true) || F(false)) {
i++;
}
`);
}); | the_stack |
module Inknote {
export class NoteControlService {
private static _instance: NoteControlService;
static get Instance() {
if (!NoteControlService._instance) {
NoteControlService._instance = new NoteControlService();
}
return NoteControlService._instance;
}
piano: Drawing.Piano = new Drawing.Piano();
private background: Drawing.NoteControlBackground = new Drawing.NoteControlBackground();
lengthControl: Drawing.LengthControlBar = new Drawing.LengthControlBar();
minimise: Drawing.Minimise = new Drawing.Minimise();
restControl: Drawing.RestControl = new Drawing.RestControl();
deleteNoteControl: Drawing.DeleteNoteControl = new Drawing.DeleteNoteControl();
x = 0;
y: number;
width: number;
height: number;
hidden: boolean = TempDataService.Instance.currentData.noteControlsHidden;
hiddenY: number = 0;
firstOpen: boolean = true;
hide() {
this.hidden = true;
TempDataService.Instance.currentData.noteControlsHidden = true;
TempDataService.Instance.update();
}
show() {
this.hidden = false;
TempDataService.Instance.currentData.noteControlsHidden = false;
TempDataService.Instance.update();
}
ID: string = "note_control";
getItems(drawer: DrawService): IDrawable[] {
if (this.hidden) {
if (this.hiddenY > drawer.canvas.height / 2 || this.firstOpen) {
this.hiddenY = drawer.canvas.height / 2;
}
else if (this.hiddenY < drawer.canvas.height / 2) {
this.hiddenY += 10;
}
}
else {
if (this.hiddenY > 0) {
this.hiddenY -= 10;
}
else {
this.hiddenY = 0;
}
}
this.y = drawer.canvas.height / 2 + this.hiddenY;
this.width = Math.min(drawer.canvas.width, 800);
this.height = drawer.canvas.height / 2;
//if (Managers.MachineManager.Instance.machineType == Managers.MachineType.Desktop) {
// this.y = drawer.canvas.height - 220; + this.hiddenY;
// this.width = 360;
// this.height = 220;
//}
var noteControls = [];
this.background.width = this.width;
this.background.height = this.height;
this.background.y = this.y;
noteControls.push(this.background);
this.restControl.y = this.y;
this.restControl.width = this.width / 8;
this.restControl.height = this.height / 4;
noteControls.push(this.restControl);
this.deleteNoteControl.y = this.y;
this.deleteNoteControl.x = this.x + this.width * 7 / 8;
this.deleteNoteControl.width = this.width / 8;
this.deleteNoteControl.height = this.height / 4;
noteControls.push(this.deleteNoteControl);
this.lengthControl.y = this.y + this.height / 4;
this.lengthControl.width = this.width;
this.lengthControl.height = this.height / 4;
noteControls.push(this.lengthControl);
this.piano.width = this.width;
this.piano.height = this.height / 2;
this.piano.y = this.y + this.height / 2;
noteControls.push(this.piano);
this.minimise.width = 40;
this.minimise.height = 20;
this.minimise.x = this.x;
this.minimise.y = this.y - this.minimise.height;
noteControls.push(this.minimise);
this.firstOpen = false;
return noteControls;
}
addInstrument(name: string): void {
UndoService.Instance.store();
var project = Managers.ProjectManager.Instance.currentProject;
var barsCount = project.instruments[0].bars.length;
var newInstrument = new Model.Instrument(name);
for (var i = 0; i < barsCount; i++) {
this.addBarToInstrument(newInstrument);
}
project.instruments.push(newInstrument);
ScoringService.Instance.refresh();
}
addBarToInstrument(instrument: Model.Instrument): void {
var newBar = new Model.Bar();
if (instrument.bars.length == 0) {
newBar.items.push(new Model.TrebleClef());
newBar.items.push(new Model.TimeSignature(4, 4));
}
instrument.bars.push(newBar);
}
addBar(): void {
var project = Managers.ProjectManager.Instance.currentProject;
for (var i = 0; i < project.instruments.length; i++) {
this.addBarToInstrument(project.instruments[i]);
}
}
addNoteToBar(heightFromTopLine: number, barID: string): void {
UndoService.Instance.store();
// due to top line starting at 0;
heightFromTopLine += 5;
var project = Managers.ProjectManager.Instance.currentProject;
for (var i = 0; i < project.instruments.length; i++) {
var clef = new Model.TrebleClef();
for (var j = 0; j < project.instruments[i].bars.length; j++) {
// loop through items looking for clef
for (var k = 0; k < project.instruments[i].bars[j].items.length; k++) {
var barItem = project.instruments[i].bars[j].items[k];
if (barItem instanceof Model.Clef) {
clef = barItem;
}
}
if (project.instruments[i].bars[j].ID == barID) {
var dif = clef.positionFromTreble;
var distRound5 = Math.round(heightFromTopLine / 5);
var topNoteOnTreble = new Model.Note(Model.NoteValue.F, 5, this.lengthControl.selectedLength);
var note = getNoteFromStaveDifference(topNoteOnTreble, dif - distRound5);
project.instruments[i].bars[j].items.push(note);
}
}
}
ScoringService.Instance.refresh();
}
addNote(note: Model.Note): void {
UndoService.Instance.store();
var project = Managers.ProjectManager.Instance.currentProject;
if (Audio.AudioService) {
var playInstrument = project.instruments[0];
if (ScoringService.Instance.SelectedItem instanceof Drawing.Bar) {
for (var i = 0; i < project.instruments.length; i++) {
for (var j = 0; j < project.instruments[i].bars.length; j++) {
if (project.instruments[i].bars[j].ID == ScoringService.Instance.selectID) {
playInstrument = project.instruments[i];
break;
}
}
}
}
var synth = playInstrument.synthID ? Audio.SynthManager.Instance.getSynth(playInstrument.synthID, playInstrument.synthName) : null;
Audio.AudioService.Instance.playNote(note, synth);
}
if (ScoringService.Instance.SelectedItem instanceof Drawing.Bar) {
for (var i = 0; i < project.instruments.length; i++) {
for (var j = 0; j < project.instruments[i].bars.length; j++) {
var currentBar = project.instruments[i].bars[j];
if (currentBar.ID == ScoringService.Instance.selectID) {
if (TimeSignatureService.Instance.barIsFull(currentBar, project.instruments[i])) {
if (project.instruments[i].bars[j + 1]) {
if (project.instruments[i].bars[j + 1].items.length == 0) {
currentBar = project.instruments[i].bars[j + 1];
}
else {
return;
}
}
else {
this.addBar();
currentBar = project.instruments[i].bars[j + 1];
}
}
currentBar.items.push(note);
ScoringService.Instance.selectID = currentBar.ID;
ScoringService.Instance.refresh();
return;
}
}
}
}
var instrument = project.instruments[0];
if (instrument.bars.length == 0) {
this.addBar();
}
var bar = instrument.bars[instrument.bars.length - 1];
if (TimeSignatureService.Instance.barIsFull(bar, instrument)) {
this.addBar();
bar = instrument.bars[instrument.bars.length - 1];
}
if(!TempDataService.Instance.currentData.allowBarOverflow){
// if dontAllowOverflow setting is on, do the following.
var testFutureBar = new Model.Bar();
testFutureBar.items = bar.items.map((item) => {return item});
testFutureBar.items.push(note);
if(TimeSignatureService.Instance.barIsOverflowing(testFutureBar, instrument)){
log("this note would make this bar too long!", MessageType.Warning);
ScoringService.Instance.refresh();
return;
}
}
bar.items.push(note);
ScoringService.Instance.refresh();
}
addRest(): void {
UndoService.Instance.store();
var project = Managers.ProjectManager.Instance.currentProject;
var rest = new Model.Rest(this.lengthControl.selectedLength);
if (ScoringService.Instance.SelectedItem instanceof Drawing.Bar) {
for (var i = 0; i < project.instruments.length; i++) {
for (var j = 0; j < project.instruments[i].bars.length; j++) {
var currentBar = project.instruments[i].bars[j];
if (currentBar.ID == ScoringService.Instance.selectID) {
if (TimeSignatureService.Instance.barIsFull(currentBar, project.instruments[i])) {
if (project.instruments[i].bars[j + 1]) {
if (project.instruments[i].bars[j + 1].items.length == 0) {
currentBar = project.instruments[i].bars[j + 1];
}
else {
return;
}
}
else {
this.addBar();
currentBar = project.instruments[i].bars[j + 1];
}
}
currentBar.items.push(rest);
ScoringService.Instance.selectID = currentBar.ID;
ScoringService.Instance.refresh();
return;
}
}
}
}
var instrument = project.instruments[0];
if (instrument.bars.length == 0) {
this.addBar();
}
var bar = instrument.bars[instrument.bars.length - 1];
if (TimeSignatureService.Instance.barIsFull(bar, instrument)) {
this.addBar();
bar = instrument.bars[instrument.bars.length - 1];
}
if(!TempDataService.Instance.currentData.allowBarOverflow){
// if dontAllowOverflow setting is on, do the following.
var testFutureBar = new Model.Bar();
testFutureBar.items = bar.items.map((item) => {return item});
testFutureBar.items.push(rest);
if(TimeSignatureService.Instance.barIsOverflowing(testFutureBar, instrument)){
log("this rest would make this bar too long!", MessageType.Warning);
ScoringService.Instance.refresh();
return;
}
}
bar.items.push(rest);
ScoringService.Instance.refresh();
}
editNoteLength() {
UndoService.Instance.store();
var project = Managers.ProjectManager.Instance.currentProject;
for (var i = 0; i < project.instruments.length; i++) {
for (var j = 0; j < project.instruments[i].bars.length; j++) {
var bar = project.instruments[i].bars[j];
for (var k = 0; k < bar.items.length; k++) {
var item = bar.items[k];
if (item.ID == ScoringService.Instance.selectID) {
if (item instanceof Model.Note) {
item.length = this.lengthControl.selectedLength;
}
else if (item instanceof Model.Rest) {
item.length = this.lengthControl.selectedLength;
}
else if (item instanceof Model.Chord) {
for (var l = 0; l < item.notes.length; l++) {
item.notes[l].length = this.lengthControl.selectedLength;
}
}
}
}
}
}
ScoringService.Instance.refresh();
}
editCurrentClef(goUp: boolean) {
UndoService.Instance.store();
var project = Managers.ProjectManager.Instance.currentProject;
for (var i = 0; i < project.instruments.length; i++) {
for (var j = 0; j < project.instruments[i].bars.length; j++) {
var bar = project.instruments[i].bars[j];
for (var k = 0; k < bar.items.length; k++) {
var item = bar.items[k];
if (item.ID == ScoringService.Instance.selectID) {
if (item instanceof Model.Clef) {
bar.items[k] = getNextClef(<Model.Clef>item, goUp);
}
}
}
}
}
ScoringService.Instance.refresh();
}
deleteSelected() {
UndoService.Instance.store();
if (ScoringService.Instance.SelectedItem instanceof Drawing.Note
|| ScoringService.Instance.SelectedItem instanceof Drawing.Rest
|| ScoringService.Instance.SelectedItem instanceof Drawing.DrawText
|| ScoringService.Instance.SelectedItem instanceof Drawing.TimeSignature
|| ScoringService.Instance.SelectedItem instanceof Drawing.Clef) {
NoteControlService.Instance.deleteItem();
}
else if (ScoringService.Instance.SelectedItem instanceof Drawing.Bar) {
BarService.Instance.deleteSelectedBar();
}
}
deleteItem() {
var project = Managers.ProjectManager.Instance.currentProject;
for (var i = 0; i < project.instruments.length; i++) {
var previousItem: Model.Rest | Model.Note | Model.Chord | Model.Clef | Model.TimeSignature | Model.Text = null;
for (var j = 0; j < project.instruments[i].bars.length; j++) {
var bar = project.instruments[i].bars[j];
var newItems = [];
for (var k = 0; k < bar.items.length; k++) {
var item = bar.items[k];
if (item.ID == ScoringService.Instance.selectID) {
// have it......... dealt with
if (previousItem) {
ScoringService.Instance.selectID = previousItem.ID;
}
else {
ScoringService.Instance.selectID = null;
}
}
else {
newItems.push(item);
}
previousItem = item;
}
bar.items = newItems;
}
}
ScoringService.Instance.refresh();
}
editNoteValueAndOctave(value: Model.NoteValue, octave: number) {
UndoService.Instance.store();
var project = Managers.ProjectManager.Instance.currentProject;
var playInstrument = project.instruments[0];
var playedNotes: Model.Note[] = [];
for (var i = 0; i < project.instruments.length; i++) {
for (var j = 0; j < project.instruments[i].bars.length; j++) {
var bar = project.instruments[i].bars[j];
for (var k = 0; k < bar.items.length; k++) {
var item = bar.items[k];
if (item.ID == ScoringService.Instance.selectID) {
playInstrument = project.instruments[i];
if (item instanceof Model.Note) {
item.value = value;
item.octave = octave;
item.length = this.lengthControl.selectedLength;
playedNotes.push(item);
}
else if (item instanceof Model.Rest) {
}
else if (item instanceof Model.Chord) {
for (var ci = 0; ci < item.notes.length; ci++) {
playedNotes.push(item.notes[ci]);
}
}
}
}
}
}
if (Audio.AudioService) {
var synth = playInstrument.synthID ? Audio.SynthManager.Instance.getSynth(playInstrument.synthID, playInstrument.synthName) : null;
for (var i = 0; i < playedNotes.length; i++) {
Audio.AudioService.Instance.playNote(playedNotes[i], synth);
}
}
ScoringService.Instance.refresh();
}
noteValueUp() {
UndoService.Instance.store();
var project = Managers.ProjectManager.Instance.currentProject;
for (var i = 0; i < project.instruments.length; i++) {
for (var j = 0; j < project.instruments[i].bars.length; j++) {
var bar = project.instruments[i].bars[j];
for (var k = 0; k < bar.items.length; k++) {
var item = bar.items[k];
if (item.ID == ScoringService.Instance.selectID || ScoringService.Instance.selectID == bar.ID) {
if (item instanceof Model.Note) {
var newVal = item.value + 1;
item.value = newVal % 12;
item.octave = newVal % 12 == Model.NoteValue.C ? item.octave + 1 : item.octave;
}
else if (item instanceof Model.Rest) {
}
else if (item instanceof Model.Chord) {
for (var l = 0; l < item.notes.length; l++) {
var newVal = item.notes[l].value + 1;
item.notes[l].value = newVal % 12;
item.notes[l].octave = newVal % 12 == Model.NoteValue.C ? item.notes[l].octave + 1 : item.notes[l].octave;
}
}
}
}
}
}
ScoringService.Instance.refresh();
}
noteValueDown() {
UndoService.Instance.store();
var project = Managers.ProjectManager.Instance.currentProject;
for (var i = 0; i < project.instruments.length; i++) {
for (var j = 0; j < project.instruments[i].bars.length; j++) {
var bar = project.instruments[i].bars[j];
for (var k = 0; k < bar.items.length; k++) {
var item = bar.items[k];
if (item.ID == ScoringService.Instance.selectID || ScoringService.Instance.selectID == bar.ID) {
if (item instanceof Model.Note) {
var newVal = item.value + 11;
item.value = newVal % 12;
item.octave = newVal % 12 == Model.NoteValue.B ? item.octave - 1 : item.octave;
}
else if (item instanceof Model.Rest) {
}
else if (item instanceof Model.Chord) {
for (var l = 0; l < item.notes.length; l++) {
var newVal = item.notes[l].value + 11;
item.notes[l].value = newVal % 12;
item.notes[l].octave = newVal % 12 == Model.NoteValue.B ? item.notes[l].octave - 1 : item.notes[l].octave;
}
}
}
}
}
}
ScoringService.Instance.refresh();
}
constructor() {
this.piano.ID = this.ID;
this.background.ID = this.ID;
this.lengthControl.ID = this.ID;
this.minimise.ID = this.ID;
}
}
} | the_stack |
// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://manufacturers.googleapis.com/$discovery/rest?version=v1
/// <reference types="gapi.client" />
declare namespace gapi.client {
/** Load Manufacturer Center API v1 */
function load(name: "manufacturers", version: "v1"): PromiseLike<void>;
function load(name: "manufacturers", version: "v1", callback: () => any): void;
const accounts: manufacturers.AccountsResource;
namespace manufacturers {
interface Attributes {
/**
* The additional images of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#addlimage.
*/
additionalImageLink?: Image[];
/**
* The target age group of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#agegroup.
*/
ageGroup?: string;
/**
* The brand name of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#brand.
*/
brand?: string;
/**
* The capacity of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#capacity.
*/
capacity?: Capacity;
/**
* The color of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#color.
*/
color?: string;
/**
* The count of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#count.
*/
count?: Count;
/**
* The description of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#description.
*/
description?: string;
/**
* The disclosure date of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#disclosure.
*/
disclosureDate?: string;
/**
* The rich format description of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#featuredesc.
*/
featureDescription?: FeatureDescription[];
/**
* The flavor of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#flavor.
*/
flavor?: string;
/**
* The format of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#format.
*/
format?: string;
/**
* The target gender of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#gender.
*/
gender?: string;
/**
* The Global Trade Item Number (GTIN) of the product. For more information,
* see https://support.google.com/manufacturers/answer/6124116#gtin.
*/
gtin?: string[];
/**
* The image of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#image.
*/
imageLink?: Image;
/**
* The item group id of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#itemgroupid.
*/
itemGroupId?: string;
/**
* The material of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#material.
*/
material?: string;
/**
* The Manufacturer Part Number (MPN) of the product. For more information,
* see https://support.google.com/manufacturers/answer/6124116#mpn.
*/
mpn?: string;
/**
* The pattern of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#pattern.
*/
pattern?: string;
/**
* The details of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#productdetail.
*/
productDetail?: ProductDetail[];
/**
* The name of the group of products related to the product. For more
* information, see
* https://support.google.com/manufacturers/answer/6124116#productline.
*/
productLine?: string;
/**
* The canonical name of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#productname.
*/
productName?: string;
/**
* The URL of the detail page of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#productpage.
*/
productPageUrl?: string;
/**
* The category of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#producttype.
*/
productType?: string[];
/**
* The release date of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#release.
*/
releaseDate?: string;
/**
* The scent of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#scent.
*/
scent?: string;
/**
* The size of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#size.
*/
size?: string;
/**
* The size system of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#sizesystem.
*/
sizeSystem?: string;
/**
* The size type of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#sizetype.
*/
sizeType?: string;
/**
* The suggested retail price (MSRP) of the product. For more information,
* see https://support.google.com/manufacturers/answer/6124116#price.
*/
suggestedRetailPrice?: Price;
/**
* The target account id. Should only be used in the accounts of the data
* partners.
*/
targetAccountId?: string;
/**
* The theme of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#theme.
*/
theme?: string;
/**
* The title of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#title.
*/
title?: string;
/**
* The videos of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#video.
*/
videoLink?: string[];
}
interface Capacity {
/** The unit of the capacity, i.e., MB, GB, or TB. */
unit?: string;
/** The numeric value of the capacity. */
value?: string;
}
interface Count {
/** The unit in which these products are counted. */
unit?: string;
/** The numeric value of the number of products in a package. */
value?: string;
}
interface FeatureDescription {
/** A short description of the feature. */
headline?: string;
/** An optional image describing the feature. */
image?: Image;
/** A detailed description of the feature. */
text?: string;
}
interface Image {
/**
* The URL of the image. For crawled images, this is the provided URL. For
* uploaded images, this is a serving URL from Google if the image has been
* processed successfully.
*/
imageUrl?: string;
/**
* The status of the image.
* @OutputOnly
*/
status?: string;
/**
* The type of the image, i.e., crawled or uploaded.
* @OutputOnly
*/
type?: string;
}
interface Issue {
/**
* If present, the attribute that triggered the issue. For more information
* about attributes, see
* https://support.google.com/manufacturers/answer/6124116.
*/
attribute?: string;
/** Description of the issue. */
description?: string;
/** The severity of the issue. */
severity?: string;
/** The timestamp when this issue appeared. */
timestamp?: string;
/**
* The server-generated type of the issue, for example,
* “INCORRECT_TEXT_FORMATTING”, “IMAGE_NOT_SERVEABLE”, etc.
*/
type?: string;
}
interface ListProductsResponse {
/** The token for the retrieval of the next page of product statuses. */
nextPageToken?: string;
/** List of the products. */
products?: Product[];
}
interface Price {
/** The numeric value of the price. */
amount?: string;
/** The currency in which the price is denoted. */
currency?: string;
}
interface Product {
/**
* The content language of the product as a two-letter ISO 639-1 language code
* (for example, en).
* @OutputOnly
*/
contentLanguage?: string;
/**
* Final attributes of the product. The final attributes are obtained by
* overriding the uploaded attributes with the manually provided and deleted
* attributes. Google systems only process, evaluate, review, and/or use final
* attributes.
* @OutputOnly
*/
finalAttributes?: Attributes;
/**
* A server-generated list of issues associated with the product.
* @OutputOnly
*/
issues?: Issue[];
/**
* Names of the attributes of the product deleted manually via the
* Manufacturer Center UI.
* @OutputOnly
*/
manuallyDeletedAttributes?: string[];
/**
* Attributes of the product provided manually via the Manufacturer Center UI.
* @OutputOnly
*/
manuallyProvidedAttributes?: Attributes;
/**
* Name in the format `{target_country}:{content_language}:{product_id}`.
*
* `target_country` - The target country of the product as a CLDR territory
* code (for example, US).
*
* `content_language` - The content language of the product as a two-letter
* ISO 639-1 language code (for example, en).
*
* `product_id` - The ID of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#id.
* @OutputOnly
*/
name?: string;
/**
* Parent ID in the format `accounts/{account_id}`.
*
* `account_id` - The ID of the Manufacturer Center account.
* @OutputOnly
*/
parent?: string;
/**
* The ID of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#id.
* @OutputOnly
*/
productId?: string;
/**
* The target country of the product as a CLDR territory code (for example,
* US).
* @OutputOnly
*/
targetCountry?: string;
/**
* Attributes of the product uploaded via the Manufacturer Center API or via
* feeds.
*/
uploadedAttributes?: Attributes;
}
interface ProductDetail {
/** The name of the attribute. */
attributeName?: string;
/** The value of the attribute. */
attributeValue?: string;
/** A short section name that can be reused between multiple product details. */
sectionName?: string;
}
interface ProductsResource {
/** Deletes the product from a Manufacturer Center account. */
delete(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: 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;
/**
* Name in the format `{target_country}:{content_language}:{product_id}`.
*
* `target_country` - The target country of the product as a CLDR territory
* code (for example, US).
*
* `content_language` - The content language of the product as a two-letter
* ISO 639-1 language code (for example, en).
*
* `product_id` - The ID of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#id.
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Parent ID in the format `accounts/{account_id}`.
*
* `account_id` - The ID of the Manufacturer Center account.
*/
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** 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;
}): Request<{}>;
/**
* Gets the product from a Manufacturer Center account, including product
* issues.
*
* A recently updated product takes around 15 minutes to process. Changes are
* only visible after it has been processed. While some issues may be
* available once the product has been processed, other issues may take days
* to appear.
*/
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: 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;
/**
* Name in the format `{target_country}:{content_language}:{product_id}`.
*
* `target_country` - The target country of the product as a CLDR territory
* code (for example, US).
*
* `content_language` - The content language of the product as a two-letter
* ISO 639-1 language code (for example, en).
*
* `product_id` - The ID of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#id.
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Parent ID in the format `accounts/{account_id}`.
*
* `account_id` - The ID of the Manufacturer Center account.
*/
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** 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;
}): Request<Product>;
/** Lists all the products in a Manufacturer Center account. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: 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;
/**
* Maximum number of product statuses to return in the response, used for
* paging.
*/
pageSize?: number;
/** The token returned by the previous request. */
pageToken?: string;
/**
* Parent ID in the format `accounts/{account_id}`.
*
* `account_id` - The ID of the Manufacturer Center account.
*/
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** 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;
}): Request<ListProductsResponse>;
/**
* Inserts or updates the product in a Manufacturer Center account.
*
* The checks at upload time are minimal. All required attributes need to be
* present for a product to be valid. Issues may show up later
* after the API has accepted an update for a product and it is possible to
* overwrite an existing valid product with an invalid product. To detect
* this, you should retrieve the product and check it for issues once the
* updated version is available.
*
* Inserted or updated products first need to be processed before they can be
* retrieved. Until then, new products will be unavailable, and retrieval
* of updated products will return the original state of the product.
*/
update(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: 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;
/**
* Name in the format `{target_country}:{content_language}:{product_id}`.
*
* `target_country` - The target country of the product as a CLDR territory
* code (for example, US).
*
* `content_language` - The content language of the product as a two-letter
* ISO 639-1 language code (for example, en).
*
* `product_id` - The ID of the product. For more information, see
* https://support.google.com/manufacturers/answer/6124116#id.
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Parent ID in the format `accounts/{account_id}`.
*
* `account_id` - The ID of the Manufacturer Center account.
*/
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** 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;
}): Request<Product>;
}
interface AccountsResource {
products: ProductsResource;
}
}
} | the_stack |
import { Octokit } from "@octokit/core";
import * as OctokitTypes from "@octokit/types";
export { EndpointOptions, RequestInterface, OctokitResponse, RequestParameters, Route, } from "@octokit/types";
import { PaginatingEndpoints } from "./generated/paginating-endpoints";
declare type KnownKeys<T> = Extract<{
[K in keyof T]: string extends K ? never : number extends K ? never : K;
} extends {
[_ in keyof T]: infer U;
} ? U : never, keyof T>;
declare type KeysMatching<T, V> = {
[K in keyof T]: T[K] extends V ? K : never;
}[keyof T];
declare type KnownKeysMatching<T, V> = KeysMatching<Pick<T, KnownKeys<T>>, V>;
declare type GetResultsType<T> = T extends {
data: any[];
} ? T["data"] : T extends {
data: object;
} ? T["data"][KnownKeysMatching<T["data"], any[]>] : never;
declare type NormalizeResponse<T> = T & {
data: GetResultsType<T>;
};
declare type DataType<T> = "data" extends keyof T ? T["data"] : unknown;
export interface MapFunction<T = unknown, R = unknown> {
(response: OctokitTypes.OctokitResponse<PaginationResults<T>>, done: () => void): R[];
}
export declare type PaginationResults<T = unknown> = T[];
export interface PaginateInterface {
/**
* Paginate a request using endpoint options and map each response to a custom array
*
* @param {object} endpoint Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {function} mapFn Optional method to map each response to a custom array
*/
<T, R>(options: OctokitTypes.EndpointOptions, mapFn: MapFunction<T, R>): Promise<PaginationResults<R>>;
/**
* Paginate a request using endpoint options
*
* @param {object} endpoint Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<T>(options: OctokitTypes.EndpointOptions): Promise<PaginationResults<T>>;
/**
* Paginate a request using a known endpoint route string and map each response to a custom array
*
* @param {string} route Request method + URL. Example: `'GET /orgs/{org}'`
* @param {function} mapFn Optional method to map each response to a custom array
*/
<R extends keyof PaginatingEndpoints, MR extends unknown[]>(route: R, mapFn: (response: PaginatingEndpoints[R]["response"], done: () => void) => MR): Promise<MR>;
/**
* Paginate a request using a known endpoint route string and parameters, and map each response to a custom array
*
* @param {string} route Request method + URL. Example: `'GET /orgs/{org}'`
* @param {object} parameters URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {function} mapFn Optional method to map each response to a custom array
*/
<R extends keyof PaginatingEndpoints, MR extends unknown[]>(route: R, parameters: PaginatingEndpoints[R]["parameters"], mapFn: (response: PaginatingEndpoints[R]["response"], done: () => void) => MR): Promise<MR>;
/**
* Paginate a request using an known endpoint route string
*
* @param {string} route Request method + URL. Example: `'GET /orgs/{org}'`
* @param {object} parameters? URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<R extends keyof PaginatingEndpoints>(route: R, parameters?: PaginatingEndpoints[R]["parameters"]): Promise<DataType<PaginatingEndpoints[R]["response"]>>;
/**
* Paginate a request using an unknown endpoint route string
*
* @param {string} route Request method + URL. Example: `'GET /orgs/{org}'`
* @param {object} parameters? URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<T, R extends OctokitTypes.Route = OctokitTypes.Route>(route: R, parameters?: R extends keyof PaginatingEndpoints ? PaginatingEndpoints[R]["parameters"] : OctokitTypes.RequestParameters): Promise<T[]>;
/**
* Paginate a request using an endpoint method and a map function
*
* @param {string} request Request method (`octokit.request` or `@octokit/request`)
* @param {function} mapFn? Optional method to map each response to a custom array
*/
<R extends OctokitTypes.RequestInterface, MR extends unknown[]>(request: R, mapFn: (response: NormalizeResponse<OctokitTypes.GetResponseTypeFromEndpointMethod<R>>, done: () => void) => MR): Promise<MR>;
/**
* Paginate a request using an endpoint method, parameters, and a map function
*
* @param {string} request Request method (`octokit.request` or `@octokit/request`)
* @param {object} parameters URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {function} mapFn? Optional method to map each response to a custom array
*/
<R extends OctokitTypes.RequestInterface, MR extends unknown[]>(request: R, parameters: Parameters<R>[0], mapFn: (response: NormalizeResponse<OctokitTypes.GetResponseTypeFromEndpointMethod<R>>, done: () => void) => MR): Promise<MR>;
/**
* Paginate a request using an endpoint method and parameters
*
* @param {string} request Request method (`octokit.request` or `@octokit/request`)
* @param {object} parameters? URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<R extends OctokitTypes.RequestInterface>(request: R, parameters?: Parameters<R>[0]): Promise<NormalizeResponse<OctokitTypes.GetResponseTypeFromEndpointMethod<R>>["data"]>;
iterator: {
/**
* Get an async iterator to paginate a request using endpoint options
*
* @see {link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of} for await...of
* @param {object} endpoint Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<T>(EndpointOptions: OctokitTypes.EndpointOptions): AsyncIterableIterator<OctokitTypes.OctokitResponse<PaginationResults<T>>>;
/**
* Get an async iterator to paginate a request using a known endpoint route string and optional parameters
*
* @see {link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of} for await...of
* @param {string} route Request method + URL. Example: `'GET /orgs/{org}'`
* @param {object} [parameters] URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<R extends keyof PaginatingEndpoints>(route: R, parameters?: PaginatingEndpoints[R]["parameters"]): AsyncIterableIterator<OctokitTypes.OctokitResponse<DataType<PaginatingEndpoints[R]["response"]>>>;
/**
* Get an async iterator to paginate a request using an unknown endpoint route string and optional parameters
*
* @see {link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of} for await...of
* @param {string} route Request method + URL. Example: `'GET /orgs/{org}'`
* @param {object} [parameters] URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<T, R extends OctokitTypes.Route = OctokitTypes.Route>(route: R, parameters?: R extends keyof PaginatingEndpoints ? PaginatingEndpoints[R]["parameters"] : OctokitTypes.RequestParameters): AsyncIterableIterator<OctokitTypes.OctokitResponse<PaginationResults<T>>>;
/**
* Get an async iterator to paginate a request using a request method and optional parameters
*
* @see {link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of} for await...of
* @param {string} request `@octokit/request` or `octokit.request` method
* @param {object} [parameters] URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<R extends OctokitTypes.RequestInterface>(request: R, parameters?: Parameters<R>[0]): AsyncIterableIterator<NormalizeResponse<OctokitTypes.GetResponseTypeFromEndpointMethod<R>>>;
};
}
export interface ComposePaginateInterface {
/**
* Paginate a request using endpoint options and map each response to a custom array
*
* @param {object} octokit Octokit instance
* @param {object} endpoint Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {function} mapFn Optional method to map each response to a custom array
*/
<T, R>(octokit: Octokit, options: OctokitTypes.EndpointOptions, mapFn: MapFunction<T, R>): Promise<PaginationResults<R>>;
/**
* Paginate a request using endpoint options
*
* @param {object} octokit Octokit instance
* @param {object} endpoint Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<T>(octokit: Octokit, options: OctokitTypes.EndpointOptions): Promise<PaginationResults<T>>;
/**
* Paginate a request using a known endpoint route string and map each response to a custom array
*
* @param {object} octokit Octokit instance
* @param {string} route Request method + URL. Example: `'GET /orgs/{org}'`
* @param {function} mapFn Optional method to map each response to a custom array
*/
<R extends keyof PaginatingEndpoints, MR extends unknown[]>(octokit: Octokit, route: R, mapFn: (response: PaginatingEndpoints[R]["response"], done: () => void) => MR): Promise<MR>;
/**
* Paginate a request using a known endpoint route string and parameters, and map each response to a custom array
*
* @param {object} octokit Octokit instance
* @param {string} route Request method + URL. Example: `'GET /orgs/{org}'`
* @param {object} parameters URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {function} mapFn Optional method to map each response to a custom array
*/
<R extends keyof PaginatingEndpoints, MR extends unknown[]>(octokit: Octokit, route: R, parameters: PaginatingEndpoints[R]["parameters"], mapFn: (response: PaginatingEndpoints[R]["response"], done: () => void) => MR): Promise<MR>;
/**
* Paginate a request using an known endpoint route string
*
* @param {object} octokit Octokit instance
* @param {string} route Request method + URL. Example: `'GET /orgs/{org}'`
* @param {object} parameters? URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<R extends keyof PaginatingEndpoints>(octokit: Octokit, route: R, parameters?: PaginatingEndpoints[R]["parameters"]): Promise<DataType<PaginatingEndpoints[R]["response"]>>;
/**
* Paginate a request using an unknown endpoint route string
*
* @param {object} octokit Octokit instance
* @param {string} route Request method + URL. Example: `'GET /orgs/{org}'`
* @param {object} parameters? URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<T, R extends OctokitTypes.Route = OctokitTypes.Route>(octokit: Octokit, route: R, parameters?: R extends keyof PaginatingEndpoints ? PaginatingEndpoints[R]["parameters"] : OctokitTypes.RequestParameters): Promise<T[]>;
/**
* Paginate a request using an endpoint method and a map function
*
* @param {object} octokit Octokit instance
* @param {string} request Request method (`octokit.request` or `@octokit/request`)
* @param {function} mapFn? Optional method to map each response to a custom array
*/
<R extends OctokitTypes.RequestInterface, MR extends unknown[]>(octokit: Octokit, request: R, mapFn: (response: NormalizeResponse<OctokitTypes.GetResponseTypeFromEndpointMethod<R>>, done: () => void) => MR): Promise<MR>;
/**
* Paginate a request using an endpoint method, parameters, and a map function
*
* @param {object} octokit Octokit instance
* @param {string} request Request method (`octokit.request` or `@octokit/request`)
* @param {object} parameters URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
* @param {function} mapFn? Optional method to map each response to a custom array
*/
<R extends OctokitTypes.RequestInterface, MR extends unknown[]>(octokit: Octokit, request: R, parameters: Parameters<R>[0], mapFn: (response: NormalizeResponse<OctokitTypes.GetResponseTypeFromEndpointMethod<R>>, done: () => void) => MR): Promise<MR>;
/**
* Paginate a request using an endpoint method and parameters
*
* @param {object} octokit Octokit instance
* @param {string} request Request method (`octokit.request` or `@octokit/request`)
* @param {object} parameters? URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<R extends OctokitTypes.RequestInterface>(octokit: Octokit, request: R, parameters?: Parameters<R>[0]): Promise<NormalizeResponse<OctokitTypes.GetResponseTypeFromEndpointMethod<R>>["data"]>;
iterator: {
/**
* Get an async iterator to paginate a request using endpoint options
*
* @see {link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of} for await...of
*
* @param {object} octokit Octokit instance
* @param {object} endpoint Must set `method` and `url`. Plus URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<T>(octokit: Octokit, EndpointOptions: OctokitTypes.EndpointOptions): AsyncIterableIterator<OctokitTypes.OctokitResponse<PaginationResults<T>>>;
/**
* Get an async iterator to paginate a request using a known endpoint route string and optional parameters
*
* @see {link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of} for await...of
*
* @param {object} octokit Octokit instance
* @param {string} route Request method + URL. Example: `'GET /orgs/{org}'`
* @param {object} [parameters] URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<R extends keyof PaginatingEndpoints>(octokit: Octokit, route: R, parameters?: PaginatingEndpoints[R]["parameters"]): AsyncIterableIterator<OctokitTypes.OctokitResponse<DataType<PaginatingEndpoints[R]["response"]>>>;
/**
* Get an async iterator to paginate a request using an unknown endpoint route string and optional parameters
*
* @see {link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of} for await...of
*
* @param {object} octokit Octokit instance
* @param {string} route Request method + URL. Example: `'GET /orgs/{org}'`
* @param {object} [parameters] URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<T, R extends OctokitTypes.Route = OctokitTypes.Route>(octokit: Octokit, route: R, parameters?: R extends keyof PaginatingEndpoints ? PaginatingEndpoints[R]["parameters"] : OctokitTypes.RequestParameters): AsyncIterableIterator<OctokitTypes.OctokitResponse<PaginationResults<T>>>;
/**
* Get an async iterator to paginate a request using a request method and optional parameters
*
* @see {link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of} for await...of
*
* @param {object} octokit Octokit instance
* @param {string} request `@octokit/request` or `octokit.request` method
* @param {object} [parameters] URL, query or body parameters, as well as `headers`, `mediaType.{format|previews}`, `request`, or `baseUrl`.
*/
<R extends OctokitTypes.RequestInterface>(octokit: Octokit, request: R, parameters?: Parameters<R>[0]): AsyncIterableIterator<NormalizeResponse<OctokitTypes.GetResponseTypeFromEndpointMethod<R>>>;
};
} | the_stack |
import i18next from "i18next";
import { runInAction } from "mobx";
import Cartesian3 from "terriajs-cesium/Source/Core/Cartesian3";
import Cartographic from "terriajs-cesium/Source/Core/Cartographic";
import Ellipsoid from "terriajs-cesium/Source/Core/Ellipsoid";
import CesiumMath from "terriajs-cesium/Source/Core/Math";
import Rectangle from "terriajs-cesium/Source/Core/Rectangle";
import Entity from "terriajs-cesium/Source/DataSources/Entity";
import makeRealPromise from "../../lib/Core/makeRealPromise";
import pollToPromise from "../../lib/Core/pollToPromise";
import supportsWebGL from "../../lib/Core/supportsWebGL";
import PickedFeatures from "../../lib/Map/PickedFeatures";
import Terria from "../../lib/Models/Terria";
import UserDrawing from "../../lib/Models/UserDrawing";
const describeIfSupported = supportsWebGL() ? describe : xdescribe;
describeIfSupported("UserDrawing that requires WebGL", function() {
it("changes cursor to crosshair when entering drawing mode", function(done) {
const terria = new Terria();
const container = document.createElement("div");
document.body.appendChild(container);
terria.mainViewer.attach(container);
const userDrawing = new UserDrawing({ terria });
makeRealPromise(
pollToPromise(() => {
return userDrawing.terria.cesium !== undefined;
})
)
.then(() => {
const cesium = userDrawing.terria.cesium;
expect(cesium).toBeDefined();
if (cesium) {
expect(cesium.cesiumWidget.canvas.style.cursor).toEqual("");
userDrawing.enterDrawMode();
expect(cesium.cesiumWidget.canvas.style.cursor).toEqual("crosshair");
(<any>userDrawing).cleanUp();
expect(cesium.cesiumWidget.canvas.style.cursor).toEqual("auto");
}
})
.then(done)
.catch(done.fail);
});
});
describe("UserDrawing", function() {
let terria: Terria;
beforeEach(function() {
terria = new Terria();
});
it("will use default options if options are not specified", function() {
var options = { terria: terria };
var userDrawing = new UserDrawing(options);
expect(userDrawing.getDialogMessage()).toEqual(
`<div><strong>${i18next.t(
"models.userDrawing.messageHeader"
)}</strong></br><i>${i18next.t(
"models.userDrawing.clickToAddFirstPoint"
)}</i></div>`
);
});
it("getDialogMessage contains callback message if callback is specified", function() {
var options = {
terria: terria,
onMakeDialogMessage: function() {
return "HELLO";
}
};
var userDrawing = new UserDrawing(options);
expect(userDrawing.getDialogMessage()).toEqual(
`<div><strong>${i18next.t(
"models.userDrawing.messageHeader"
)}</strong></br>HELLO</br><i>${i18next.t(
"models.userDrawing.clickToAddFirstPoint"
)}</i></div>`
);
});
it("listens for user picks on map after entering drawing mode", function() {
var userDrawing = new UserDrawing({ terria });
expect(userDrawing.terria.mapInteractionModeStack.length).toEqual(0);
userDrawing.enterDrawMode();
expect(userDrawing.terria.mapInteractionModeStack.length).toEqual(1);
});
it("disables feature info requests when in drawing mode", function() {
var options = { terria: terria };
var userDrawing = new UserDrawing(options);
expect(userDrawing.terria.allowFeatureInfoRequests).toEqual(true);
userDrawing.enterDrawMode();
expect(userDrawing.terria.allowFeatureInfoRequests).toEqual(false);
});
it("re-enables feature info requests on cleanup", function() {
var options = { terria: terria };
var userDrawing = new UserDrawing(options);
userDrawing.enterDrawMode();
expect(userDrawing.terria.allowFeatureInfoRequests).toEqual(false);
userDrawing.cleanUp();
expect(userDrawing.terria.allowFeatureInfoRequests).toEqual(true);
});
it("ensures onPointClicked callback is called when point is picked by user", function() {
const onPointClicked = jasmine.createSpy();
const userDrawing = new UserDrawing({ terria, onPointClicked });
userDrawing.enterDrawMode();
const pickedFeatures = new PickedFeatures();
// Auckland, in case you're wondering
pickedFeatures.pickPosition = new Cartesian3(
-5088454.576893678,
465233.10329933715,
-3804299.6786334896
);
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
const pointEntities = onPointClicked.calls.mostRecent().args[0];
expect(pointEntities.entities.values.length).toEqual(1);
});
it("ensures graphics are added when point is picked by user", async function() {
const userDrawing = new UserDrawing({ terria });
expect(userDrawing.pointEntities.entities.values.length).toEqual(0);
expect(userDrawing.otherEntities.entities.values.length).toEqual(0);
userDrawing.enterDrawMode();
const pickedFeatures = new PickedFeatures();
// Auckland, in case you're wondering
pickedFeatures.pickPosition = new Cartesian3(
-5088454.576893678,
465233.10329933715,
-3804299.6786334896
);
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
expect(userDrawing.pointEntities.entities.values.length).toEqual(1);
expect(userDrawing.otherEntities.entities.values.length).toEqual(1);
});
it("ensures graphics are updated when points change", function() {
const options = { terria: terria };
const userDrawing = new UserDrawing(options);
expect(userDrawing.pointEntities.entities.values.length).toEqual(0);
expect(userDrawing.otherEntities.entities.values.length).toEqual(0);
userDrawing.enterDrawMode();
const pickedFeatures = new PickedFeatures();
// Auckland, in case you're wondering
const x = -5088454.576893678;
const y = 465233.10329933715;
const z = -3804299.6786334896;
pickedFeatures.pickPosition = new Cartesian3(x, y, z);
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
// Check point
const currentPoint = userDrawing.pointEntities.entities.values[0];
expect(currentPoint.position).toBeDefined();
if (currentPoint.position !== undefined) {
let currentPointPos = currentPoint.position.getValue(
terria.timelineClock.currentTime
);
expect(currentPointPos.x).toEqual(x);
expect(currentPointPos.y).toEqual(y);
expect(currentPointPos.z).toEqual(z);
}
// Check line as well
let lineEntity = userDrawing.otherEntities.entities.values[0];
expect(lineEntity.polyline).toBeDefined();
if (lineEntity.polyline !== undefined) {
expect(lineEntity.polyline.positions).toBeDefined();
if (lineEntity.polyline.positions !== undefined) {
let currentPointPos = lineEntity.polyline.positions.getValue(
terria.timelineClock.currentTime
)[0];
expect(currentPointPos.x).toEqual(x);
expect(currentPointPos.y).toEqual(y);
expect(currentPointPos.z).toEqual(z);
}
}
// Okay, now change points. LA.
const newPickedFeatures = new PickedFeatures();
const newX = -2503231.890682526;
const newY = -4660863.528418564;
const newZ = 3551306.84427321;
newPickedFeatures.pickPosition = new Cartesian3(newX, newY, newZ);
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = newPickedFeatures;
});
// Check point
const newPoint = userDrawing.pointEntities.entities.values[1];
expect(newPoint.position).toBeDefined();
if (newPoint.position !== undefined) {
let newPointPos = newPoint.position.getValue(
terria.timelineClock.currentTime
);
expect(newPointPos.x).toEqual(newX);
expect(newPointPos.y).toEqual(newY);
expect(newPointPos.z).toEqual(newZ);
}
// Check line as well
lineEntity = userDrawing.otherEntities.entities.values[0];
expect(lineEntity.polyline).toBeDefined();
if (lineEntity.polyline !== undefined) {
expect(lineEntity.polyline.positions).toBeDefined();
if (lineEntity.polyline.positions !== undefined) {
let newPointPos = lineEntity.polyline.positions.getValue(
terria.timelineClock.currentTime
)[1];
expect(newPointPos.x).toEqual(newX);
expect(newPointPos.y).toEqual(newY);
expect(newPointPos.z).toEqual(newZ);
}
}
});
it("returns correct button text for any given number of points on map", function() {
const options = { terria: terria };
const userDrawing = new UserDrawing(options);
expect(userDrawing.getButtonText()).toEqual(
i18next.t("models.userDrawing.btnCancel")
);
userDrawing.pointEntities.entities.values.push(new Entity());
expect(userDrawing.getButtonText()).toEqual(
i18next.t("models.userDrawing.btnCancel")
);
userDrawing.pointEntities.entities.values.push(new Entity());
expect(userDrawing.getButtonText()).toEqual(
i18next.t("models.userDrawing.btnDone")
);
});
it("cleans up when cleanup is called", function() {
const options = { terria: terria };
const userDrawing = new UserDrawing(options);
expect(userDrawing.pointEntities.entities.values.length).toEqual(0);
expect(userDrawing.otherEntities.entities.values.length).toEqual(0);
userDrawing.enterDrawMode();
let pickedFeatures = new PickedFeatures();
// Auckland, in case you're wondering
pickedFeatures.pickPosition = new Cartesian3(
-5088454.576893678,
465233.10329933715,
-3804299.6786334896
);
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
expect(userDrawing.pointEntities.entities.values.length).toEqual(1);
expect(userDrawing.otherEntities.entities.values.length).toEqual(1);
(<any>userDrawing).cleanUp();
expect(userDrawing.pointEntities.entities.values.length).toEqual(0);
expect(userDrawing.otherEntities.entities.values.length).toEqual(0);
expect((<any>userDrawing).inDrawMode).toBeFalsy();
expect((<any>userDrawing).closeLoop).toBeFalsy();
});
it("ensures onCleanUp callback is called when clean up occurs", function() {
const onCleanUp = jasmine.createSpy();
const userDrawing = new UserDrawing({ terria, onCleanUp });
userDrawing.enterDrawMode();
expect(onCleanUp).not.toHaveBeenCalled();
(<any>userDrawing).cleanUp();
expect(onCleanUp).toHaveBeenCalled();
});
it("function clickedExistingPoint detects and handles if existing point is clicked", function() {
const userDrawing = new UserDrawing({ terria });
userDrawing.enterDrawMode();
const pickedFeatures = new PickedFeatures();
// First point
// Points around Parliament house
const pt1Position = new Cartographic(
CesiumMath.toRadians(149.121),
CesiumMath.toRadians(-35.309),
CesiumMath.toRadians(0)
);
const pt1CartesianPosition = Ellipsoid.WGS84.cartographicToCartesian(
pt1Position
);
pickedFeatures.pickPosition = pt1CartesianPosition;
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
// Second point
const pt2Position = new Cartographic(
CesiumMath.toRadians(149.124),
CesiumMath.toRadians(-35.311),
CesiumMath.toRadians(0)
);
const pt2CartesianPosition = Ellipsoid.WGS84.cartographicToCartesian(
pt2Position
);
pickedFeatures.pickPosition = pt2CartesianPosition;
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
// Third point
const pt3Position = new Cartographic(
CesiumMath.toRadians(149.127),
CesiumMath.toRadians(-35.308),
CesiumMath.toRadians(0)
);
const pt3CartesianPosition = Ellipsoid.WGS84.cartographicToCartesian(
pt3Position
);
pickedFeatures.pickPosition = pt3CartesianPosition;
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
expect((<any>userDrawing).closeLoop).toBeFalsy();
// Now pick the first point
pickedFeatures.pickPosition = pt1CartesianPosition;
// If in the UI the user clicks on a point, it returns that entity, so we're pulling it out of userDrawing and
// pretending the user actually clicked on it.
const pt1Entity = userDrawing.pointEntities.entities.values[0];
pickedFeatures.features = [pt1Entity];
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
expect((<any>userDrawing).closeLoop).toBeTruthy();
expect(userDrawing.pointEntities.entities.values.length).toEqual(3);
});
it("loop does not close if polygon is not allowed", function() {
const options = { terria: terria, allowPolygon: false };
const userDrawing = new UserDrawing(options);
userDrawing.enterDrawMode();
const pickedFeatures = new PickedFeatures();
// First point
// Points around Parliament house
const pt1Position = new Cartographic(
CesiumMath.toRadians(149.121),
CesiumMath.toRadians(-35.309),
CesiumMath.toRadians(0)
);
const pt1CartesianPosition = Ellipsoid.WGS84.cartographicToCartesian(
pt1Position
);
pickedFeatures.pickPosition = pt1CartesianPosition;
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
// Second point
const pt2Position = new Cartographic(
CesiumMath.toRadians(149.124),
CesiumMath.toRadians(-35.311),
CesiumMath.toRadians(0)
);
const pt2CartesianPosition = Ellipsoid.WGS84.cartographicToCartesian(
pt2Position
);
pickedFeatures.pickPosition = pt2CartesianPosition;
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
// Third point
const pt3Position = new Cartographic(
CesiumMath.toRadians(149.127),
CesiumMath.toRadians(-35.308),
CesiumMath.toRadians(0)
);
const pt3CartesianPosition = Ellipsoid.WGS84.cartographicToCartesian(
pt3Position
);
pickedFeatures.pickPosition = pt3CartesianPosition;
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
expect((<any>userDrawing).closeLoop).toBeFalsy();
// Now pick the first point
pickedFeatures.pickPosition = pt1CartesianPosition;
// If in the UI the user clicks on a point, it returns that entity, so we're pulling it out of userDrawing and
// pretending the user actually clicked on it.
const pt1Entity = userDrawing.pointEntities.entities.values[0];
pickedFeatures.features = [pt1Entity];
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
expect((<any>userDrawing).closeLoop).toBeFalsy();
expect(userDrawing.pointEntities.entities.values.length).toEqual(2);
});
it("polygon is only drawn once", function() {
const userDrawing = new UserDrawing({ terria });
userDrawing.enterDrawMode();
const pickedFeatures = new PickedFeatures();
// First point
// Points around Parliament house
const pt1Position = new Cartographic(
CesiumMath.toRadians(149.121),
CesiumMath.toRadians(-35.309),
CesiumMath.toRadians(0)
);
const pt1CartesianPosition = Ellipsoid.WGS84.cartographicToCartesian(
pt1Position
);
pickedFeatures.pickPosition = pt1CartesianPosition;
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
// Second point
const pt2Position = new Cartographic(
CesiumMath.toRadians(149.124),
CesiumMath.toRadians(-35.311),
CesiumMath.toRadians(0)
);
const pt2CartesianPosition = Ellipsoid.WGS84.cartographicToCartesian(
pt2Position
);
pickedFeatures.pickPosition = pt2CartesianPosition;
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
// Third point
const pt3Position = new Cartographic(
CesiumMath.toRadians(149.127),
CesiumMath.toRadians(-35.308),
CesiumMath.toRadians(0)
);
const pt3CartesianPosition = Ellipsoid.WGS84.cartographicToCartesian(
pt3Position
);
pickedFeatures.pickPosition = pt3CartesianPosition;
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
expect((<any>userDrawing).closeLoop).toBeFalsy();
expect(userDrawing.otherEntities.entities.values.length).toEqual(1);
// Now pick the first point
pickedFeatures.pickPosition = pt1CartesianPosition;
// If in the UI the user clicks on a point, it returns that entity, so we're pulling it out of userDrawing and
// pretending the user actually clicked on it.
const pt1Entity = userDrawing.pointEntities.entities.values[0];
pickedFeatures.features = [pt1Entity];
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
expect((<any>userDrawing).closeLoop).toBeTruthy();
expect(userDrawing.otherEntities.entities.values.length).toEqual(2);
// Another point. Polygon is still closed.
const newPtPosition = new Cartographic(
CesiumMath.toRadians(149.0),
CesiumMath.toRadians(-35.0),
CesiumMath.toRadians(0)
);
const newPtCartesianPosition = Ellipsoid.WGS84.cartographicToCartesian(
newPtPosition
);
pickedFeatures.pickPosition = newPtCartesianPosition;
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
expect((<any>userDrawing).closeLoop).toBeTruthy();
expect(userDrawing.otherEntities.entities.values.length).toEqual(2);
});
it("point is removed if it is clicked on and it is not the first point", function() {
const options = { terria: terria };
const userDrawing = new UserDrawing(options);
userDrawing.enterDrawMode();
const pickedFeatures = new PickedFeatures();
// First point
// Points around Parliament house
const pt1Position = new Cartographic(
CesiumMath.toRadians(149.121),
CesiumMath.toRadians(-35.309),
CesiumMath.toRadians(0)
);
const pt1CartesianPosition = Ellipsoid.WGS84.cartographicToCartesian(
pt1Position
);
pickedFeatures.pickPosition = pt1CartesianPosition;
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
// Second point
const pt2Position = new Cartographic(
CesiumMath.toRadians(149.124),
CesiumMath.toRadians(-35.311),
CesiumMath.toRadians(0)
);
const pt2CartesianPosition = Ellipsoid.WGS84.cartographicToCartesian(
pt2Position
);
pickedFeatures.pickPosition = pt2CartesianPosition;
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
// Third point
const pt3Position = new Cartographic(
CesiumMath.toRadians(149.127),
CesiumMath.toRadians(-35.308),
CesiumMath.toRadians(0)
);
const pt3CartesianPosition = Ellipsoid.WGS84.cartographicToCartesian(
pt3Position
);
pickedFeatures.pickPosition = pt3CartesianPosition;
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
expect((<any>userDrawing).closeLoop).toBeFalsy();
// Now pick the second point
pickedFeatures.pickPosition = pt2CartesianPosition;
// If in the UI the user clicks on a point, it returns that entity, so we're pulling it out of userDrawing and
// pretending the user actually clicked on it.
const pt2Entity = userDrawing.pointEntities.entities.values[1];
pickedFeatures.features = [pt2Entity];
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
expect(userDrawing.pointEntities.entities.values.length).toEqual(2);
expect(userDrawing.mapItems.length).toBe(2);
});
it("draws rectangle", function() {
const userDrawing = new UserDrawing({
terria,
allowPolygon: false,
drawRectangle: true
});
userDrawing.enterDrawMode();
const pickedFeatures = new PickedFeatures();
// First point
// Points around Parliament house
const pt1Position = new Cartographic(
CesiumMath.toRadians(149.121),
CesiumMath.toRadians(-35.309),
CesiumMath.toRadians(0)
);
const pt1CartesianPosition = Ellipsoid.WGS84.cartographicToCartesian(
pt1Position
);
pickedFeatures.pickPosition = pt1CartesianPosition;
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
expect(userDrawing.pointEntities.entities.values.length).toEqual(1);
expect(userDrawing.otherEntities.entities.values.length).toEqual(1);
let rectangle: Rectangle = userDrawing.otherEntities.entities
.getById("rectangle")
?.rectangle?.coordinates?.getValue(terria.timelineClock.currentTime);
expect(rectangle).toBeUndefined();
// Second point
const pt2Position = new Cartographic(
CesiumMath.toRadians(149.124),
CesiumMath.toRadians(-35.311),
CesiumMath.toRadians(0)
);
const pt2CartesianPosition = Ellipsoid.WGS84.cartographicToCartesian(
pt2Position
);
pickedFeatures.pickPosition = pt2CartesianPosition;
runInAction(() => {
userDrawing.terria.mapInteractionModeStack[0].pickedFeatures = pickedFeatures;
});
expect(userDrawing.pointEntities.entities.values.length).toEqual(2);
expect(userDrawing.otherEntities.entities.values.length).toEqual(1);
rectangle = userDrawing.otherEntities.entities
.getById("rectangle")
?.rectangle?.coordinates?.getValue(terria.timelineClock.currentTime);
expect(rectangle.east).toBeCloseTo(CesiumMath.toRadians(149.124));
expect(rectangle.west).toBeCloseTo(CesiumMath.toRadians(149.121));
expect(rectangle.north).toBeCloseTo(CesiumMath.toRadians(-35.309));
expect(rectangle.south).toBeCloseTo(CesiumMath.toRadians(-35.311));
expect(userDrawing.mapItems.length).toBe(1);
});
}); | the_stack |
'use strict';
import * as cpp from 'child-process-promise';
import * as fs from 'fs';
import * as path from 'path';
import * as component from '../../../common/component';
import { getExperimentId } from '../../../common/experimentStartupInfo';
import {
NNIManagerIpConfig, TrialJobApplicationForm, TrialJobDetail, TrialJobStatus
} from '../../../common/trainingService';
import { delay, generateParamFileName, getExperimentRootDir, uniqueString } from '../../../common/utils';
import { CONTAINER_INSTALL_NNI_SHELL_FORMAT } from '../../common/containerJobData';
import { TrialConfigMetadataKey } from '../../common/trialConfigMetadataKey';
import { validateCodeDir } from '../../common/util';
import { NFSConfig } from '../kubernetesConfig';
import { KubernetesTrialJobDetail } from '../kubernetesData';
import { KubernetesTrainingService } from '../kubernetesTrainingService';
import { FrameworkControllerClientFactory } from './frameworkcontrollerApiClient';
import { FrameworkControllerClusterConfig, FrameworkControllerClusterConfigAzure, FrameworkControllerClusterConfigFactory,
FrameworkControllerClusterConfigNFS, FrameworkControllerTrialConfig} from './frameworkcontrollerConfig';
import { FrameworkControllerJobInfoCollector } from './frameworkcontrollerJobInfoCollector';
import { FrameworkControllerJobRestServer } from './frameworkcontrollerJobRestServer';
/**
* Training Service implementation for frameworkcontroller
*/
@component.Singleton
class FrameworkControllerTrainingService extends KubernetesTrainingService implements KubernetesTrainingService {
private fcTrialConfig?: FrameworkControllerTrialConfig; // frameworkcontroller trial configuration
private readonly fcJobInfoCollector: FrameworkControllerJobInfoCollector; // frameworkcontroller job info collector
private readonly fcContainerPortMap: Map<string, number> = new Map<string, number>(); // store frameworkcontroller container port
private fcClusterConfig?: FrameworkControllerClusterConfig;
constructor() {
super();
this.fcJobInfoCollector = new FrameworkControllerJobInfoCollector(this.trialJobsMap);
this.experimentId = getExperimentId();
}
public async run(): Promise<void> {
this.kubernetesJobRestServer = component.get(FrameworkControllerJobRestServer);
if (this.kubernetesJobRestServer === undefined) {
throw new Error('kubernetesJobRestServer not initialized!');
}
await this.kubernetesJobRestServer.start();
this.kubernetesJobRestServer.setEnableVersionCheck = this.versionCheck;
this.log.info(`frameworkcontroller Training service rest server listening on: ${this.kubernetesJobRestServer.endPoint}`);
while (!this.stopping) {
// collect metrics for frameworkcontroller jobs by interacting with Kubernetes API server
await delay(3000);
await this.fcJobInfoCollector.retrieveTrialStatus(this.kubernetesCRDClient);
if (this.kubernetesJobRestServer.getErrorMessage !== undefined) {
throw new Error(this.kubernetesJobRestServer.getErrorMessage);
this.stopping = true;
}
}
}
public async submitTrialJob(form: TrialJobApplicationForm): Promise<TrialJobDetail> {
if (this.fcClusterConfig === undefined) {
throw new Error('frameworkcontrollerClusterConfig is not initialized');
}
if (this.kubernetesCRDClient === undefined) {
throw new Error('kubernetesCRDClient is undefined');
}
if (this.kubernetesRestServerPort === undefined) {
const restServer: FrameworkControllerJobRestServer = component.get(FrameworkControllerJobRestServer);
this.kubernetesRestServerPort = restServer.clusterRestServerPort;
}
const trialJobId: string = uniqueString(5);
// Set trial's NFS working folder
const trialWorkingFolder: string = path.join(this.CONTAINER_MOUNT_PATH, 'nni', getExperimentId(), trialJobId);
const trialLocalTempFolder: string = path.join(getExperimentRootDir(), 'trials-local', trialJobId);
const frameworkcontrollerJobName: string = `nniexp${this.experimentId}trial${trialJobId}`.toLowerCase();
//Generate the port used for taskRole
this.generateContainerPort();
await this.prepareRunScript(trialLocalTempFolder, trialJobId, trialWorkingFolder, form);
//upload code files
const trialJobOutputUrl: string = await this.uploadCodeFiles(trialJobId, trialLocalTempFolder);
let initStatus: TrialJobStatus = 'WAITING';
if (!trialJobOutputUrl) {
initStatus = 'FAILED';
}
const trialJobDetail: KubernetesTrialJobDetail = new KubernetesTrialJobDetail(
trialJobId,
initStatus,
Date.now(),
trialWorkingFolder,
form,
frameworkcontrollerJobName,
trialJobOutputUrl
);
// Set trial job detail until create frameworkcontroller job successfully
this.trialJobsMap.set(trialJobId, trialJobDetail);
// Create frameworkcontroller job based on generated frameworkcontroller job resource config
const frameworkcontrollerJobConfig: any = await this.prepareFrameworkControllerConfig(
trialJobId, trialWorkingFolder, frameworkcontrollerJobName);
await this.kubernetesCRDClient.createKubernetesJob(frameworkcontrollerJobConfig);
// Set trial job detail until create frameworkcontroller job successfully
this.trialJobsMap.set(trialJobId, trialJobDetail);
return Promise.resolve(trialJobDetail);
}
public async setClusterMetadata(key: string, value: string): Promise<void> {
switch (key) {
case TrialConfigMetadataKey.NNI_MANAGER_IP:
this.nniManagerIpConfig = <NNIManagerIpConfig>JSON.parse(value);
break;
case TrialConfigMetadataKey.FRAMEWORKCONTROLLER_CLUSTER_CONFIG: {
const frameworkcontrollerClusterJsonObject: any = JSON.parse(value);
this.fcClusterConfig = FrameworkControllerClusterConfigFactory
.generateFrameworkControllerClusterConfig(frameworkcontrollerClusterJsonObject);
if (this.fcClusterConfig.storageType === 'azureStorage') {
const azureFrameworkControllerClusterConfig: FrameworkControllerClusterConfigAzure =
<FrameworkControllerClusterConfigAzure>this.fcClusterConfig;
this.azureStorageAccountName = azureFrameworkControllerClusterConfig.azureStorage.accountName;
this.azureStorageShare = azureFrameworkControllerClusterConfig.azureStorage.azureShare;
await this.createAzureStorage(
azureFrameworkControllerClusterConfig.keyVault.vaultName,
azureFrameworkControllerClusterConfig.keyVault.name
);
} else if (this.fcClusterConfig.storageType === 'nfs') {
const nfsFrameworkControllerClusterConfig: FrameworkControllerClusterConfigNFS =
<FrameworkControllerClusterConfigNFS>this.fcClusterConfig;
await this.createNFSStorage(
nfsFrameworkControllerClusterConfig.nfs.server,
nfsFrameworkControllerClusterConfig.nfs.path
);
}
this.kubernetesCRDClient = FrameworkControllerClientFactory.createClient();
break;
}
case TrialConfigMetadataKey.TRIAL_CONFIG: {
const frameworkcontrollerTrialJsonObjsect: any = JSON.parse(value);
this.fcTrialConfig = new FrameworkControllerTrialConfig(
frameworkcontrollerTrialJsonObjsect.codeDir,
frameworkcontrollerTrialJsonObjsect.taskRoles
);
// Validate to make sure codeDir doesn't have too many files
try {
await validateCodeDir(this.fcTrialConfig.codeDir);
} catch (error) {
this.log.error(error);
return Promise.reject(new Error(error));
}
break;
}
case TrialConfigMetadataKey.VERSION_CHECK:
this.versionCheck = (value === 'true' || value === 'True');
break;
case TrialConfigMetadataKey.LOG_COLLECTION:
this.logCollection = value;
break;
default:
}
return Promise.resolve();
}
/**
* upload code files to nfs or azureStroage
* @param trialJobId
* @param trialLocalTempFolder
* return: trialJobOutputUrl
*/
private async uploadCodeFiles(trialJobId: string, trialLocalTempFolder: string): Promise<string> {
if (this.fcClusterConfig === undefined) {
throw new Error('Kubeflow Cluster config is not initialized');
}
if (this.fcTrialConfig === undefined) {
throw new Error('Kubeflow trial config is not initialized');
}
let trialJobOutputUrl: string = '';
if (this.fcClusterConfig.storageType === 'azureStorage') {
const azureFrameworkControllerClusterConfig: FrameworkControllerClusterConfigAzure =
<FrameworkControllerClusterConfigAzure>this.fcClusterConfig;
trialJobOutputUrl = await this.uploadFilesToAzureStorage(trialJobId, trialLocalTempFolder, this.fcTrialConfig.codeDir,
azureFrameworkControllerClusterConfig.uploadRetryCount);
} else if (this.fcClusterConfig.storageType === 'nfs') {
const nfsFrameworkControllerClusterConfig: FrameworkControllerClusterConfigNFS =
<FrameworkControllerClusterConfigNFS>this.fcClusterConfig;
// Creat work dir for current trial in NFS directory
await cpp.exec(`mkdir -p ${this.trialLocalNFSTempFolder}/nni/${getExperimentId()}/${trialJobId}`);
// Copy code files from local dir to NFS mounted dir
await cpp.exec(`cp -r ${trialLocalTempFolder}/* ${this.trialLocalNFSTempFolder}/nni/${getExperimentId()}/${trialJobId}/.`);
// Copy codeDir to NFS mounted dir
await cpp.exec(`cp -r ${this.fcTrialConfig.codeDir}/* ${this.trialLocalNFSTempFolder}/nni/${getExperimentId()}/${trialJobId}/.`);
const nfsConfig: NFSConfig = nfsFrameworkControllerClusterConfig.nfs;
trialJobOutputUrl = `nfs://${nfsConfig.server}:${path.join(nfsConfig.path, 'nni', getExperimentId(), trialJobId, 'output')}`;
}
return Promise.resolve(trialJobOutputUrl);
}
/**
* generate trial's command for frameworkcontroller
* expose port and execute injector.sh before executing user's command
* @param command
*/
private generateCommandScript(command: string): string {
let portScript: string = '';
if (this.fcTrialConfig === undefined) {
throw new Error('frameworkcontroller trial config is not initialized');
}
for (const taskRole of this.fcTrialConfig.taskRoles) {
portScript += `FB_${taskRole.name.toUpperCase()}_PORT=${this.fcContainerPortMap.get(taskRole.name)} `;
}
return `${portScript} . /mnt/frameworkbarrier/injector.sh && ${command}`;
}
private async prepareRunScript(trialLocalTempFolder: string, trialJobId: string,
trialWorkingFolder: string, form: TrialJobApplicationForm): Promise<void> {
if (this.fcTrialConfig === undefined) {
throw new Error('frameworkcontroller trial config is not initialized');
}
await cpp.exec(`mkdir -p ${trialLocalTempFolder}`);
const installScriptContent: string = CONTAINER_INSTALL_NNI_SHELL_FORMAT;
// Write NNI installation file to local tmp files
await fs.promises.writeFile(path.join(trialLocalTempFolder, 'install_nni.sh'), installScriptContent, { encoding: 'utf8' });
// Create tmp trial working folder locally.
for (const taskRole of this.fcTrialConfig.taskRoles) {
const runScriptContent: string =
await this.generateRunScript('frameworkcontroller', trialJobId, trialWorkingFolder,
this.generateCommandScript(taskRole.command), form.sequenceId.toString(),
taskRole.name, taskRole.gpuNum);
await fs.promises.writeFile(path.join(trialLocalTempFolder, `run_${taskRole.name}.sh`), runScriptContent, { encoding: 'utf8' });
}
// Write file content ( parameter.cfg ) to local tmp folders
if (form !== undefined) {
await fs.promises.writeFile(path.join(trialLocalTempFolder, generateParamFileName(form.hyperParameters)),
form.hyperParameters.value, { encoding: 'utf8' });
}
}
private async prepareFrameworkControllerConfig(trialJobId: string, trialWorkingFolder: string, frameworkcontrollerJobName: string):
Promise<any> {
if (this.fcTrialConfig === undefined) {
throw new Error('frameworkcontroller trial config is not initialized');
}
const podResources: any = [];
for (const taskRole of this.fcTrialConfig.taskRoles) {
const resource: any = {};
resource.requests = this.generatePodResource(taskRole.memoryMB, taskRole.cpuNum, taskRole.gpuNum);
resource.limits = {...resource.requests};
podResources.push(resource);
}
// Generate frameworkcontroller job resource config object
const frameworkcontrollerJobConfig: any =
await this.generateFrameworkControllerJobConfig(trialJobId, trialWorkingFolder, frameworkcontrollerJobName, podResources);
return Promise.resolve(frameworkcontrollerJobConfig);
}
private generateContainerPort(): void {
if (this.fcTrialConfig === undefined) {
throw new Error('frameworkcontroller trial config is not initialized');
}
let port: number = 4000; //The default port used in container
for (const index of this.fcTrialConfig.taskRoles.keys()) {
this.fcContainerPortMap.set(this.fcTrialConfig.taskRoles[index].name, port);
port += 1;
}
}
/**
* Generate frameworkcontroller resource config file
* @param trialJobId trial job id
* @param trialWorkingFolder working folder
* @param frameworkcontrollerJobName job name
* @param podResources pod template
*/
private async generateFrameworkControllerJobConfig(trialJobId: string, trialWorkingFolder: string,
frameworkcontrollerJobName: string, podResources: any): Promise<any> {
if (this.fcClusterConfig === undefined) {
throw new Error('frameworkcontroller Cluster config is not initialized');
}
if (this.fcTrialConfig === undefined) {
throw new Error('frameworkcontroller trial config is not initialized');
}
const taskRoles: any = [];
for (const index of this.fcTrialConfig.taskRoles.keys()) {
const containerPort: number | undefined = this.fcContainerPortMap.get(this.fcTrialConfig.taskRoles[index].name);
if (containerPort === undefined) {
throw new Error('Container port is not initialized');
}
const taskRole: any = this.generateTaskRoleConfig(
trialWorkingFolder,
this.fcTrialConfig.taskRoles[index].image,
`run_${this.fcTrialConfig.taskRoles[index].name}.sh`,
podResources[index],
containerPort,
await this.createRegistrySecret(this.fcTrialConfig.taskRoles[index].privateRegistryAuthPath)
);
taskRoles.push({
name: this.fcTrialConfig.taskRoles[index].name,
taskNumber: this.fcTrialConfig.taskRoles[index].taskNum,
frameworkAttemptCompletionPolicy: {
minFailedTaskCount: this.fcTrialConfig.taskRoles[index].frameworkAttemptCompletionPolicy.minFailedTaskCount,
minSucceededTaskCount: this.fcTrialConfig.taskRoles[index].frameworkAttemptCompletionPolicy.minSucceededTaskCount
},
task: taskRole
});
}
return Promise.resolve({
apiVersion: `frameworkcontroller.microsoft.com/v1`,
kind: 'Framework',
metadata: {
name: frameworkcontrollerJobName,
namespace: 'default',
labels: {
app: this.NNI_KUBERNETES_TRIAL_LABEL,
expId: getExperimentId(),
trialId: trialJobId
}
},
spec: {
executionType: 'Start',
taskRoles: taskRoles
}
});
}
private generateTaskRoleConfig(trialWorkingFolder: string, replicaImage: string, runScriptFile: string,
podResources: any, containerPort: number, privateRegistrySecretName: string | undefined): any {
if (this.fcClusterConfig === undefined) {
throw new Error('frameworkcontroller Cluster config is not initialized');
}
if (this.fcTrialConfig === undefined) {
throw new Error('frameworkcontroller trial config is not initialized');
}
const volumeSpecMap: Map<string, object> = new Map<string, object>();
if (this.fcClusterConfig.storageType === 'azureStorage') {
volumeSpecMap.set('nniVolumes', [
{
name: 'nni-vol',
azureFile: {
secretName: `${this.azureStorageSecretName}`,
shareName: `${this.azureStorageShare}`,
readonly: false
}
}, {
name: 'frameworkbarrier-volume',
emptyDir: {}
}]);
} else {
const frameworkcontrollerClusterConfigNFS: FrameworkControllerClusterConfigNFS =
<FrameworkControllerClusterConfigNFS> this.fcClusterConfig;
volumeSpecMap.set('nniVolumes', [
{
name: 'nni-vol',
nfs: {
server: `${frameworkcontrollerClusterConfigNFS.nfs.server}`,
path: `${frameworkcontrollerClusterConfigNFS.nfs.path}`
}
}, {
name: 'frameworkbarrier-volume',
emptyDir: {}
}]);
}
const containers: any = [
{
name: 'framework',
image: replicaImage,
command: ['sh', `${path.join(trialWorkingFolder, runScriptFile)}`],
volumeMounts: [
{
name: 'nni-vol',
mountPath: this.CONTAINER_MOUNT_PATH
}, {
name: 'frameworkbarrier-volume',
mountPath: '/mnt/frameworkbarrier'
}],
resources: podResources,
ports: [{
containerPort: containerPort
}]
}];
const initContainers: any = [
{
name: 'frameworkbarrier',
image: 'frameworkcontroller/frameworkbarrier',
volumeMounts: [
{
name: 'frameworkbarrier-volume',
mountPath: '/mnt/frameworkbarrier'
}]
}];
const spec: any = {
containers: containers,
initContainers: initContainers,
restartPolicy: 'OnFailure',
volumes: volumeSpecMap.get('nniVolumes'),
hostNetwork: false
};
if(privateRegistrySecretName) {
spec.imagePullSecrets = [
{
name: privateRegistrySecretName
}
]
}
if (this.fcClusterConfig.serviceAccountName !== undefined) {
spec.serviceAccountName = this.fcClusterConfig.serviceAccountName;
}
return {
pod: {
spec: spec
}
};
}
}
export { FrameworkControllerTrainingService }; | the_stack |
import { Buffer } from '@stacks/common';
import { AppConfig } from './appConfig';
import { SessionOptions } from './sessionData';
import { InstanceDataStore, LocalStorageStore, SessionDataStore } from './sessionStore';
import { decodeToken } from 'jsontokens';
import { verifyAuthResponse } from './verification';
import * as authMessages from './messages';
import {
decryptContent,
encryptContent,
EncryptContentOptions,
hexStringToECPair,
} from '@stacks/encryption';
import { getAddressFromDID } from './dids';
import {
BLOCKSTACK_DEFAULT_GAIA_HUB_URL,
fetchPrivate,
getGlobalObject,
InvalidStateError,
isLaterVersion,
Logger,
LoginFailedError,
MissingParameterError,
nextHour,
} from '@stacks/common';
import { extractProfile } from '@stacks/profile';
import { AuthScope, DEFAULT_PROFILE, NAME_LOOKUP_PATH } from './constants';
import * as queryString from 'query-string';
import { UserData } from './userData';
import { StacksMainnet } from '@stacks/network';
import { protocolEchoReplyDetection } from './protocolEchoDetection';
/**
*
* Represents an instance of a signed in user for a particular app.
*
* A signed in user has access to two major pieces of information
* about the user, the user's private key for that app and the location
* of the user's gaia storage bucket for the app.
*
* A user can be signed in either directly through the interactive
* sign in process or by directly providing the app private key.
*
*
*/
export class UserSession {
appConfig: AppConfig;
store: SessionDataStore;
/**
* Creates a UserSession object
*
* @param options
*/
constructor(options?: {
appConfig?: AppConfig;
sessionStore?: SessionDataStore;
sessionOptions?: SessionOptions;
}) {
let runningInBrowser = true;
if (typeof window === 'undefined' && typeof self === 'undefined') {
// Logger.debug('UserSession: not running in browser')
runningInBrowser = false;
}
if (options && options.appConfig) {
this.appConfig = options.appConfig;
} else if (runningInBrowser) {
this.appConfig = new AppConfig();
} else {
throw new MissingParameterError('You need to specify options.appConfig');
}
if (options && options.sessionStore) {
this.store = options.sessionStore;
} else if (runningInBrowser) {
if (options) {
this.store = new LocalStorageStore(options.sessionOptions);
} else {
this.store = new LocalStorageStore();
}
} else if (options) {
this.store = new InstanceDataStore(options.sessionOptions);
} else {
this.store = new InstanceDataStore();
}
}
/**
* Generates an authentication request that can be sent to the Blockstack
* browser for the user to approve sign in. This authentication request can
* then be used for sign in by passing it to the [[redirectToSignInWithAuthRequest]]
* method.
*
* *Note*: This method should only be used if you want to use a customized authentication
* flow. Typically, you'd use [[redirectToSignIn]] which is the default sign in method.
*
* @param transitKey A HEX encoded transit private key.
* @param redirectURI Location to redirect the user to after sign in approval.
* @param manifestURI Location of this app's manifest file.
* @param scopes The permissions this app is requesting. The default is `store_write`.
* @param appDomain The origin of the app.
* @param expiresAt The time at which this request is no longer valid.
* @param extraParams Any extra parameters to pass to the authenticator. Use this to
* pass options that aren't part of the Blockstack authentication specification,
* but might be supported by special authenticators.
*
* @returns {String} the authentication request
*/
makeAuthRequest(
transitKey?: string,
redirectURI?: string,
manifestURI?: string,
scopes?: (AuthScope | string)[],
appDomain?: string,
expiresAt: number = nextHour().getTime(),
extraParams: any = {}
): string {
const appConfig = this.appConfig;
if (!appConfig) {
throw new InvalidStateError('Missing AppConfig');
}
transitKey = transitKey || this.generateAndStoreTransitKey();
redirectURI = redirectURI || appConfig.redirectURI();
manifestURI = manifestURI || appConfig.manifestURI();
scopes = scopes || appConfig.scopes;
appDomain = appDomain || appConfig.appDomain;
return authMessages.makeAuthRequest(
transitKey,
redirectURI,
manifestURI,
scopes,
appDomain,
expiresAt,
extraParams
);
}
/**
* Generates a ECDSA keypair to
* use as the ephemeral app transit private key
* and store in the session.
*
* @returns {String} the hex encoded private key
*
*/
generateAndStoreTransitKey(): string {
const sessionData = this.store.getSessionData();
const transitKey = authMessages.generateTransitKey();
sessionData.transitKey = transitKey;
this.store.setSessionData(sessionData);
return transitKey;
}
/**
* Retrieve the authentication token from the URL query
* @return {String} the authentication token if it exists otherwise `null`
*/
getAuthResponseToken(): string {
const search = getGlobalObject('location', {
throwIfUnavailable: true,
usageDesc: 'getAuthResponseToken',
})?.search;
if (search) {
const queryDict = queryString.parse(search);
return queryDict.authResponse ? (queryDict.authResponse as string) : '';
}
return '';
}
/**
* Check if there is a authentication request that hasn't been handled.
*
* Also checks for a protocol echo reply (which if detected then the page
* will be automatically redirected after this call).
*
* @return {Boolean} `true` if there is a pending sign in, otherwise `false`
*/
isSignInPending() {
try {
const isProtocolEcho = protocolEchoReplyDetection();
if (isProtocolEcho) {
Logger.info(
'protocolEchoReply detected from isSignInPending call, the page is about to redirect.'
);
return true;
}
} catch (error) {
Logger.error(`Error checking for protocol echo reply isSignInPending: ${error}`);
}
return !!this.getAuthResponseToken();
}
/**
* Check if a user is currently signed in.
*
* @returns {Boolean} `true` if the user is signed in, `false` if not.
*/
isUserSignedIn() {
return !!this.store.getSessionData().userData;
}
/**
* Try to process any pending sign in request by returning a `Promise` that resolves
* to the user data object if the sign in succeeds.
*
* @param {String} authResponseToken - the signed authentication response token
* @returns {Promise} that resolves to the user data object if successful and rejects
* if handling the sign in request fails or there was no pending sign in request.
*/
async handlePendingSignIn(
authResponseToken: string = this.getAuthResponseToken()
): Promise<UserData> {
const sessionData = this.store.getSessionData();
if (sessionData.userData) {
throw new LoginFailedError('Existing user session found.');
}
const transitKey = this.store.getSessionData().transitKey;
// let nameLookupURL;
let coreNode = this.appConfig && this.appConfig.coreNode;
if (!coreNode) {
const network = new StacksMainnet();
coreNode = network.bnsLookupUrl;
}
const tokenPayload = decodeToken(authResponseToken).payload;
if (typeof tokenPayload === 'string') {
throw new Error('Unexpected token payload type of string');
}
// Section below is removed since the config was never persisted and therefore useless
// if (isLaterVersion(tokenPayload.version as string, '1.3.0')
// && tokenPayload.blockstackAPIUrl !== null && tokenPayload.blockstackAPIUrl !== undefined) {
// // override globally
// Logger.info(`Overriding ${config.network.blockstackAPIUrl} `
// + `with ${tokenPayload.blockstackAPIUrl}`)
// // TODO: this config is never saved so the user node preference
// // is not respected in later sessions..
// config.network.blockstackAPIUrl = tokenPayload.blockstackAPIUrl as string
// coreNode = tokenPayload.blockstackAPIUrl as string
// }
const nameLookupURL = `${coreNode}${NAME_LOOKUP_PATH}`;
const fallbackLookupURLs = [
`https://stacks-node-api.stacks.co${NAME_LOOKUP_PATH}`,
`https://registrar.stacks.co${NAME_LOOKUP_PATH}`,
].filter(url => url !== nameLookupURL);
const isValid = await verifyAuthResponse(authResponseToken, nameLookupURL, fallbackLookupURLs);
if (!isValid) {
throw new LoginFailedError('Invalid authentication response.');
}
// TODO: real version handling
let appPrivateKey: string = tokenPayload.private_key as string;
let coreSessionToken: string = tokenPayload.core_token as string;
if (isLaterVersion(tokenPayload.version as string, '1.1.0')) {
if (transitKey !== undefined && transitKey != null) {
if (tokenPayload.private_key !== undefined && tokenPayload.private_key !== null) {
try {
appPrivateKey = (await authMessages.decryptPrivateKey(
transitKey,
tokenPayload.private_key as string
)) as string;
} catch (e) {
Logger.warn('Failed decryption of appPrivateKey, will try to use as given');
try {
hexStringToECPair(tokenPayload.private_key as string);
} catch (ecPairError) {
throw new LoginFailedError(
'Failed decrypting appPrivateKey. Usually means' +
' that the transit key has changed during login.'
);
}
}
}
if (coreSessionToken !== undefined && coreSessionToken !== null) {
try {
coreSessionToken = (await authMessages.decryptPrivateKey(
transitKey,
coreSessionToken
)) as string;
} catch (e) {
Logger.info('Failed decryption of coreSessionToken, will try to use as given');
}
}
} else {
throw new LoginFailedError(
'Authenticating with protocol > 1.1.0 requires transit' + ' key, and none found.'
);
}
}
let hubUrl = BLOCKSTACK_DEFAULT_GAIA_HUB_URL;
let gaiaAssociationToken: string;
if (
isLaterVersion(tokenPayload.version as string, '1.2.0') &&
tokenPayload.hubUrl !== null &&
tokenPayload.hubUrl !== undefined
) {
hubUrl = tokenPayload.hubUrl as string;
}
if (
isLaterVersion(tokenPayload.version as string, '1.3.0') &&
tokenPayload.associationToken !== null &&
tokenPayload.associationToken !== undefined
) {
gaiaAssociationToken = tokenPayload.associationToken as string;
}
const userData: UserData = {
username: tokenPayload.username as string,
profile: tokenPayload.profile,
email: tokenPayload.email as string,
decentralizedID: tokenPayload.iss,
identityAddress: getAddressFromDID(tokenPayload.iss),
appPrivateKey,
coreSessionToken,
authResponseToken,
hubUrl,
coreNode: tokenPayload.blockstackAPIUrl as string,
// @ts-expect-error
gaiaAssociationToken,
};
const profileURL = tokenPayload.profile_url as string;
if (!userData.profile && profileURL) {
const response = await fetchPrivate(profileURL);
if (!response.ok) {
// return blank profile if we fail to fetch
userData.profile = Object.assign({}, DEFAULT_PROFILE);
} else {
const responseText = await response.text();
const wrappedProfile = JSON.parse(responseText);
userData.profile = extractProfile(wrappedProfile[0].token);
}
} else {
userData.profile = tokenPayload.profile;
}
sessionData.userData = userData;
this.store.setSessionData(sessionData);
return userData;
}
/**
* Retrieves the user data object. The user's profile is stored in the key [[Profile]].
*
* @returns {Object} User data object.
*/
loadUserData() {
const userData = this.store.getSessionData().userData;
if (!userData) {
throw new InvalidStateError('No user data found. Did the user sign in?');
}
return userData;
}
/**
* Encrypts the data provided with the app public key.
* @param {String|Buffer} content the data to encrypt
* @param options
* @param {String} options.publicKey the hex string of the ECDSA public
* key to use for encryption. If not provided, will use user's appPrivateKey.
*
* @returns {String} Stringified ciphertext object
*/
encryptContent(content: string | Buffer, options?: EncryptContentOptions): Promise<string> {
const opts = Object.assign({}, options);
if (!opts.privateKey) {
opts.privateKey = this.loadUserData().appPrivateKey;
}
return encryptContent(content, opts);
}
/**
* Decrypts data encrypted with `encryptContent` with the
* transit private key.
* @param {String|Buffer} content - encrypted content.
* @param options
* @param {String} options.privateKey - The hex string of the ECDSA private
* key to use for decryption. If not provided, will use user's appPrivateKey.
* @returns {String|Buffer} decrypted content.
*/
decryptContent(content: string, options?: { privateKey?: string }): Promise<Buffer | string> {
const opts = Object.assign({}, options);
if (!opts.privateKey) {
opts.privateKey = this.loadUserData().appPrivateKey;
}
return decryptContent(content, opts);
}
/**
* Sign the user out and optionally redirect to given location.
* @param redirectURL
* Location to redirect user to after sign out.
* Only used in environments with `window` available
*/
signUserOut(
redirectURL?: string
// TODO: this is not used?
// caller?: UserSession
) {
this.store.deleteSessionData();
if (redirectURL) {
if (typeof location !== 'undefined' && location.href) {
location.href = redirectURL;
}
// TODO: Invalid left-hand side in assignment expression
// // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// // @ts-ignore
// getGlobalObject('location', {
// throwIfUnavailable: true,
// usageDesc: 'signUserOut',
// })?.href = redirectURL;
}
}
} | the_stack |
import { Component, OnInit, Input, OnDestroy, ChangeDetectorRef, AfterViewChecked } from "@angular/core";
import { GlobalVarsService } from "../global-vars.service";
import { BackendApiService } from "../backend-api.service";
import { ActivatedRoute, Router } from "@angular/router";
import { Subscription } from "rxjs";
import { tap, finalize, first } from "rxjs/operators";
import * as _ from "lodash";
import PullToRefresh from "pulltorefreshjs";
import { Title } from "@angular/platform-browser";
import { NftPostComponent } from "../nft-post-page/nft-post/nft-post.component";
import { environment } from "src/environments/environment";
@Component({
selector: "feed",
templateUrl: "./feed.component.html",
styleUrls: ["./feed.component.sass"],
})
export class FeedComponent implements OnInit, OnDestroy, AfterViewChecked {
static GLOBAL_TAB = "Global";
static FOLLOWING_TAB = "Following";
static SHOWCASE_TAB = "⚡ NFT Showcase ⚡";
static TABS = [FeedComponent.GLOBAL_TAB, FeedComponent.FOLLOWING_TAB, FeedComponent.SHOWCASE_TAB];
static NUM_TO_FETCH = 50;
static MIN_FOLLOWING_TO_SHOW_FOLLOW_FEED_BY_DEFAULT = 10;
static PULL_TO_REFRESH_MARKER_ID = "pull-to-refresh-marker";
@Input() activeTab: string;
@Input() isMobile = false;
loggedInUserSubscription: Subscription;
followChangeSubscription: Subscription;
FeedComponent = FeedComponent;
switchingTabs = false;
nextNFTShowcaseTime;
followedPublicKeyToProfileEntry = {};
// We load the first batch of follow feed posts on page load and whenever the user follows someone
loadingFirstBatchOfFollowFeedPosts = false;
// We load the first batch of global feed posts on page load
loadingFirstBatchOfGlobalFeedPosts = false;
// We load the user's following on page load. This boolean tracks whether we're currently loading
// or whether we've finished.
isLoadingFollowingOnPageLoad;
globalVars: GlobalVarsService;
serverHasMoreFollowFeedPosts = true;
serverHasMoreGlobalFeedPosts = true;
loadingMoreFollowFeedPosts = false;
loadingMoreGlobalFeedPosts = false;
pullToRefreshHandler;
// This is [Following, Global, Market] if the user is following anybody. Otherwise,
// it's [Global, Following, Market].
//
// TODO: if you switch between accounts while viewing the feed, we don't recompute this.
// So if user1 is following folks, and we switch to user2 who isn't following anyone,
// the empty follow feed will be the first tab (which is incorrect) and
feedTabs = [];
constructor(
private appData: GlobalVarsService,
private router: Router,
private route: ActivatedRoute,
private cdr: ChangeDetectorRef,
private backendApi: BackendApiService,
private titleService: Title
) {
this.globalVars = appData;
this.route.queryParams.subscribe((queryParams) => {
if (queryParams.feedTab) {
if (queryParams.feedTab === "Showcase") {
this.activeTab = FeedComponent.SHOWCASE_TAB;
} else {
this.activeTab = queryParams.feedTab;
}
} else {
// A default activeTab will be set after we load the follow feed (based on whether
// the user is following anybody)
this.activeTab = null;
}
});
// Reload the follow feed any time the user follows / unfollows somebody
this.followChangeSubscription = this.appData.followChangeObservable.subscribe((followChangeObservableResult) => {
this._reloadFollowFeed();
});
this.loggedInUserSubscription = this.appData.loggedInUserObservable.subscribe((loggedInUserObservableResult) => {
// Reload the follow feed if the logged in user changed
if (!loggedInUserObservableResult.isSameUserAsBefore) {
// Set activeTab to null so that a sensible default tab is selected
this.activeTab = null;
this._initializeFeeds();
}
});
// Go see if there is an upcoming NFT showcase that should be advertised.
this.backendApi
.GetNextNFTShowcase(this.globalVars.localNode, this.globalVars.loggedInUser?.PublicKeyBase58Check)
.subscribe((res: any) => {
if (res.NextNFTShowcaseTstamp) {
this.nextNFTShowcaseTime = new Date(res.NextNFTShowcaseTstamp / 1e6);
}
});
}
ngOnInit() {
this._initializeFeeds();
this.titleService.setTitle(`Feed - ${environment.node.name}`);
}
ngAfterViewChecked() {
// if the marker was removed for some reason,
// then clear out the handler to allow it to be recreated later
if (!document.getElementById(this.getPullToRefreshMarkerId())) {
this.pullToRefreshHandler?.destroy();
this.pullToRefreshHandler = undefined;
} else if (!this.pullToRefreshHandler) {
// initialize the handler only once when the
// marker is first created
this.pullToRefreshHandler = PullToRefresh.init({
mainElement: `#${this.getPullToRefreshMarkerId()}`,
onRefresh: () => {
const globalPostsPromise = this._loadPosts(true);
const followPostsPromise = this._loadFollowFeedPosts(true);
return this.activeTab === FeedComponent.FOLLOWING_TAB ? followPostsPromise : globalPostsPromise;
},
});
}
}
ngOnDestroy() {
this.pullToRefreshHandler?.destroy();
this.loggedInUserSubscription.unsubscribe();
}
_reloadFollowFeed() {
// Reload the follow feed from scratch
this.globalVars.followFeedPosts = [];
this.loadingFirstBatchOfFollowFeedPosts = true;
return this._loadFollowFeedPosts();
}
_initializeFeeds() {
if (this.globalVars.postsToShow.length === 0) {
// Get some posts to show the user.
this.loadingFirstBatchOfGlobalFeedPosts = true;
this._loadPosts();
} else {
// If we already have posts to show, delay rendering the posts for a hot second so nav is fast.
// this._onTabSwitch()
}
// Request the follow feed (so we have it ready for display if needed)
if (this.globalVars.followFeedPosts.length === 0) {
this.loadingFirstBatchOfFollowFeedPosts = true;
this._reloadFollowFeed();
}
// The activeTab is set after we load the following based on whether the user is
// already following anybody
if (this.appData.loggedInUser) {
this._loadFollowing();
} else {
// If there's no user, consider the following to be loaded (it's empty)
this._afterLoadingFollowingOnPageLoad();
}
}
getPullToRefreshMarkerId() {
return FeedComponent.PULL_TO_REFRESH_MARKER_ID;
}
prependPostToFeed(postEntryResponse) {
FeedComponent.prependPostToFeed(this.postsToShow(), postEntryResponse);
}
onPostHidden(postEntryResponse) {
const parentPostIndex = FeedComponent.findParentPostIndex(this.postsToShow(), postEntryResponse);
const parentPost = this.postsToShow()[parentPostIndex];
FeedComponent.onPostHidden(
this.postsToShow(),
postEntryResponse,
parentPost,
null /*grandparentPost... don't worry about them on the feed*/
);
// Remove / re-add the parentPost from postsToShow, to force
// angular to re-render now that we've updated the comment count
this.postsToShow()[parentPostIndex] = _.cloneDeep(parentPost);
}
userBlocked() {
this.cdr.detectChanges();
}
appendCommentAfterParentPost(postEntryResponse) {
FeedComponent.appendCommentAfterParentPost(this.postsToShow(), postEntryResponse);
}
hideFollowLink() {
return this.activeTab === FeedComponent.FOLLOWING_TAB;
}
postsToShow() {
if (this.activeTab === FeedComponent.FOLLOWING_TAB) {
// No need to delay on the Following tab. It handles the "slow switching" issue itself.
return this.globalVars.followFeedPosts;
} else {
return this.globalVars.postsToShow;
}
}
activeTabReadyForDisplay() {
// If we don't have the following yet, we don't even know which tab to display
if (this.isLoadingFollowingOnPageLoad) {
return false;
}
if (this.activeTab === FeedComponent.FOLLOWING_TAB) {
// No need to delay on the Following tab. It handles the "slow switching" issue itself.
return this.loadingMoreFollowFeedPosts;
} else {
return this.loadingMoreGlobalFeedPosts;
}
}
showLoadingSpinner() {
return (
this.activeTab !== FeedComponent.SHOWCASE_TAB && (this.loadingFirstBatchOfActiveTabPosts() || this.switchingTabs)
);
}
// controls whether we show the loading spinner
loadingFirstBatchOfActiveTabPosts() {
if (this.activeTab === FeedComponent.FOLLOWING_TAB) {
return this.loadingFirstBatchOfFollowFeedPosts;
} else {
return this.loadingFirstBatchOfGlobalFeedPosts;
}
}
showGlobalOrFollowingPosts() {
return (
this.postsToShow().length > 0 &&
(this.activeTab === FeedComponent.GLOBAL_TAB || this.activeTab === FeedComponent.FOLLOWING_TAB)
);
}
showNoPostsFound() {
// activeTab == FeedComponent.GLOBAL_TAB && globalVars.postsToShow.length == 0 && !loadingPosts
return (
this.postsToShow().length === 0 &&
(this.activeTab === FeedComponent.GLOBAL_TAB || this.activeTab === FeedComponent.FOLLOWING_TAB) &&
!this.loadingFirstBatchOfActiveTabPosts()
);
}
loadMorePosts() {
if (this.activeTab === FeedComponent.FOLLOWING_TAB) {
this._loadFollowFeedPosts();
} else {
this._loadPosts();
}
}
showMoreButton() {
if (this.loadingFirstBatchOfActiveTabPosts()) {
return false;
}
if (this.activeTab === FeedComponent.FOLLOWING_TAB) {
return this.serverHasMoreFollowFeedPosts;
} else {
return this.serverHasMoreGlobalFeedPosts;
}
}
_onTabSwitch() {
// Delay rendering the posts for a hot second so nav is fast.
this.switchingTabs = true;
setTimeout(() => {
this.switchingTabs = false;
}, 0);
}
_loadPosts(reload: boolean = false) {
this.loadingMoreGlobalFeedPosts = true;
// Get the reader's public key for the request.
let readerPubKey = "";
if (this.globalVars.loggedInUser) {
readerPubKey = this.globalVars.loggedInUser.PublicKeyBase58Check;
}
// Get the last post hash in case this is a "load more" request.
let lastPostHash = "";
if (this.globalVars.postsToShow.length > 0 && !reload) {
lastPostHash = this.globalVars.postsToShow[this.globalVars.postsToShow.length - 1].PostHashHex;
}
return this.backendApi
.GetPostsStateless(
this.globalVars.localNode,
lastPostHash /*PostHash*/,
readerPubKey /*ReaderPublicKeyBase58Check*/,
"", // Blank orderBy so we don't sort twice
parseInt(this.globalVars.filterType) /*StartTstampSecs*/,
"",
FeedComponent.NUM_TO_FETCH /*NumToFetch*/,
false /*FetchSubcomments*/,
false /*GetPostsForFollowFeed*/,
true /*GetPostsForGlobalWhitelist*/,
false,
false /*MediaRequired*/,
0,
this.globalVars.showAdminTools() /*AddGlobalFeedBool*/
)
.pipe(
tap(
(res) => {
if (lastPostHash !== "") {
this.globalVars.postsToShow = this.globalVars.postsToShow.concat(res.PostsFound);
} else {
this.globalVars.postsToShow = res.PostsFound;
}
if (res.PostsFound.length < FeedComponent.NUM_TO_FETCH - 1) {
// I'm not sure what the expected behavior is for the global feed. It may sometimes
// return less than NUM_TO_FETCH while there are still posts available (e.g. if posts
// are deleted. I'm not sure so just commenting out for now.
// We'll move to infinite scroll soon, so not sure this is worth fixing rn.
// this.serverHasMoreGlobalFeedPosts = true
}
},
(err) => {
console.error(err);
this.globalVars._alertError("Error loading posts: " + this.backendApi.stringifyError(err));
}
),
finalize(() => {
this.loadingFirstBatchOfGlobalFeedPosts = false;
this.loadingMoreGlobalFeedPosts = false;
}),
first()
)
.toPromise();
}
_loadFollowing() {
this.isLoadingFollowingOnPageLoad = true;
this.backendApi
.GetFollows(
this.appData.localNode,
"" /* username */,
this.appData.loggedInUser.PublicKeyBase58Check,
false /* getEntriesFollowingPublicKey */
)
.subscribe(
(response) => {
this.followedPublicKeyToProfileEntry = response.PublicKeyToProfileEntry;
},
(error) => {}
)
.add(() => {
this._afterLoadingFollowingOnPageLoad();
});
}
_loadFollowFeedPosts(reload: boolean = false) {
this.loadingMoreFollowFeedPosts = true;
// Get the reader's public key for the request.
let readerPubKey = "";
if (this.globalVars.loggedInUser) {
readerPubKey = this.globalVars.loggedInUser.PublicKeyBase58Check;
}
// Get the last post hash in case this is a "load more" request.
let lastPostHash = "";
if (this.globalVars.followFeedPosts.length > 0 && !reload) {
lastPostHash = this.globalVars.followFeedPosts[this.globalVars.followFeedPosts.length - 1].PostHashHex;
}
return this.backendApi
.GetPostsStateless(
this.globalVars.localNode,
lastPostHash /*PostHash*/,
readerPubKey /*ReaderPublicKeyBase58Check*/,
"newest" /*OrderBy*/,
parseInt(this.globalVars.filterType) /*StartTstampSecs*/,
"",
FeedComponent.NUM_TO_FETCH /*NumToFetch*/,
false /*FetchSubcomments*/,
true /*GetPostsForFollowFeed*/,
false /*GetPostsForGlobalWhitelist*/,
false,
false /*MediaRequired*/,
0,
this.globalVars.showAdminTools() /*AddGlobalFeedBool*/
)
.pipe(
tap(
(res) => {
if (lastPostHash !== "") {
this.globalVars.followFeedPosts = this.globalVars.followFeedPosts.concat(res.PostsFound);
} else {
this.globalVars.followFeedPosts = res.PostsFound;
}
if (res.PostsFound.length < FeedComponent.NUM_TO_FETCH) {
this.serverHasMoreFollowFeedPosts = false;
// Note: the server may be out of posts even if res.PostsFond == NUM_TO_FETCH.
// This can happen if the server returns the last NUM_TO_FETCH posts exactly.
// In that case, the user will click the load more button one more time, and then
// the server will return 0. Obviously this isn't great behavior, but hopefully
// we'll swap out the load more button for infinite scroll soon anyway.
}
this.loadingFirstBatchOfFollowFeedPosts = false;
this.loadingMoreFollowFeedPosts = false;
},
(err) => {
console.error(err);
this.globalVars._alertError("Error loading posts: " + this.backendApi.stringifyError(err));
}
),
finalize(() => {
this.loadingFirstBatchOfFollowFeedPosts = false;
this.loadingMoreFollowFeedPosts = false;
}),
first()
)
.toPromise();
}
_afterLoadingFollowingOnPageLoad() {
this.isLoadingFollowingOnPageLoad = false;
// defaultActiveTab is "Following" if the user is following anybody. Otherwise
// the default is global.
let defaultActiveTab;
const numFollowing = Object.keys(this.followedPublicKeyToProfileEntry).length;
if (numFollowing >= FeedComponent.MIN_FOLLOWING_TO_SHOW_FOLLOW_FEED_BY_DEFAULT) {
defaultActiveTab = FeedComponent.FOLLOWING_TAB;
} else {
defaultActiveTab = FeedComponent.GLOBAL_TAB;
}
this.feedTabs = [FeedComponent.GLOBAL_TAB, FeedComponent.FOLLOWING_TAB, FeedComponent.SHOWCASE_TAB];
if (!this.activeTab) {
this.activeTab = defaultActiveTab;
}
this._handleTabClick(this.activeTab);
}
_handleTabClick(tab: string) {
this.activeTab = tab;
this.router.navigate([], {
relativeTo: this.route,
queryParams: { feedTab: this.activeTab },
queryParamsHandling: "merge",
});
this._onTabSwitch();
}
static prependPostToFeed(postsToShow, postEntryResponse) {
postsToShow.unshift(postEntryResponse);
}
// Note: the caller of this function may need to re-render the parentPost and grandparentPost,
// since we update their CommentCounts
static onPostHidden(postsToShow, postEntryResponse, parentPost, grandparentPost) {
const postIndex = postsToShow.findIndex((post) => {
return post.PostHashHex === postEntryResponse.PostHashHex;
});
if (postIndex === -1) {
console.error(`Problem finding postEntryResponse in postsToShow in onPostHidden`, {
postEntryResponse,
postsToShow,
});
}
// the current post (1) + the CommentCount comments/subcomments were hidden
const decrementAmount = 1 + postEntryResponse.CommentCount;
if (parentPost != null) {
parentPost.CommentCount -= decrementAmount;
}
if (grandparentPost != null) {
grandparentPost.CommentCount -= decrementAmount;
}
postsToShow.splice(postIndex, 1);
}
static findParentPostIndex(postsToShow, postEntryResponse) {
return postsToShow.findIndex((post) => {
return post.PostHashHex === postEntryResponse.ParentStakeID;
});
}
static appendCommentAfterParentPost(postsToShow, postEntryResponse) {
const parentPostIndex = FeedComponent.findParentPostIndex(postsToShow, postEntryResponse);
const parentPost = postsToShow[parentPostIndex];
// Note: we don't worry about updating the grandparent posts' commentCount in the feed
parentPost.CommentCount += 1;
// This is a hack to make it so that the new comment shows up in the
// feed with the "replying to @[parentPost.Username]" content displayed.
postEntryResponse.parentPost = parentPost;
// Insert the new comment in the correct place in the postsToShow list.
// TODO: This doesn't work properly for comments on subcomments (they appear in the wrong
// place in the list), but whatever, we can try to fix this edge case later
postsToShow.splice(parentPostIndex + 1, 0, postEntryResponse);
// Add the post to the parent's list of comments so that the comment count gets updated
parentPost.Comments = parentPost.Comments || [];
parentPost.Comments.unshift(postEntryResponse);
}
} | the_stack |
import binding, {
CppConnection,
CppLogFunc,
CppError,
CppTracer,
CppMeter,
} from './binding'
import { translateCppError } from './bindingutilities'
import { ConnSpec } from './connspec'
import { ConnectionClosedError } from './errors'
import { LogFunc } from './logging'
import { NoopMeter, LoggingMeter, Meter } from './metrics'
import { NoopTracer, ThresholdLoggingTracer, RequestTracer } from './tracing'
function getClientString() {
// Grab the various versions. Note that we need to trim them
// off as some Node.js versions insert strange characters into
// the version identifiers (mainly newlines and such).
/* eslint-disable-next-line @typescript-eslint/no-var-requires */
const couchnodeVer = require('../package.json').version.trim()
const nodeVer = process.versions.node.trim()
const v8Ver = process.versions.v8.trim()
const sslVer = process.versions.openssl.trim()
return `couchnode/${couchnodeVer} (node/${nodeVer}; v8/${v8Ver}; ssl/${sslVer})`
}
export interface ConnectionOptions {
connStr: string
username?: string
password?: string
trustStorePath?: string
certificatePath?: string
keyPath?: string
bucketName?: string
kvConnectTimeout?: number
kvTimeout?: number
kvDurableTimeout?: number
viewTimeout?: number
queryTimeout?: number
analyticsTimeout?: number
searchTimeout?: number
managementTimeout?: number
tracer?: RequestTracer
meter?: Meter
logFunc?: LogFunc
}
type ErrCallback = (err: Error | null) => void
// We need this small type-utility to ensure that the labels on the parameter
// tuple actually get transferred during the merge (typescript bug).
type MergeArgs<A, B> = A extends [...infer Params]
? [...Params, ...(B extends [...infer Params2] ? Params2 : [])]
: never
// This type takes a function as input from the CppConnection and then adjusts
// the callback to be of type (Error | null) as opposed to (CppError | null).
// It is used to adjust the return types of Connection to reflect that the error
// has already been translated from a CppError to CouchbaseError.
type CppCbToNew<T extends (...fargs: any[]) => void> = T extends (
...fargs: [
...infer FArgs,
(err: CppError | null, ...cbArgs: infer CbArgs) => void
]
) => void
? [
...fargs: MergeArgs<
FArgs,
[callback: (err: Error | null, ...cbArgs: CbArgs) => void]
>
]
: never
// BUG(JSCBC-901): We cannot defer HTTP operations inside of libcouchbase and thus
// need to perform that deferral at the binding level.
type ConnectWaitFunc = () => void
export class Connection {
private _inst: CppConnection
private _connected: boolean
private _opened: boolean
private _closed: boolean
private _closedErr: Error | null
// BUG(JSCBC-901)
private _connectWaiters: ConnectWaitFunc[]
constructor(options: ConnectionOptions) {
this._closed = false
this._closedErr = null
this._connected = false
this._opened = false
this._connectWaiters = []
const lcbDsnObj = ConnSpec.parse(options.connStr)
// This function converts a timeout value expressed in milliseconds into
// a string for the connection string, represented in seconds.
const fmtTmt = (value: number) => {
return (value / 1000).toString()
}
if (options.trustStorePath) {
lcbDsnObj.options.truststorepath = options.trustStorePath
}
if (options.certificatePath) {
lcbDsnObj.options.certpath = options.certificatePath
}
if (options.keyPath) {
lcbDsnObj.options.keypath = options.keyPath
}
if (options.bucketName) {
lcbDsnObj.bucket = options.bucketName
}
if (options.kvConnectTimeout) {
lcbDsnObj.options.config_total_timeout = fmtTmt(options.kvConnectTimeout)
}
if (options.kvTimeout) {
lcbDsnObj.options.timeout = fmtTmt(options.kvTimeout)
}
if (options.kvDurableTimeout) {
lcbDsnObj.options.durability_timeout = fmtTmt(options.kvDurableTimeout)
}
if (options.viewTimeout) {
lcbDsnObj.options.views_timeout = fmtTmt(options.viewTimeout)
}
if (options.queryTimeout) {
lcbDsnObj.options.query_timeout = fmtTmt(options.queryTimeout)
}
if (options.analyticsTimeout) {
lcbDsnObj.options.analytics_timeout = fmtTmt(options.analyticsTimeout)
}
if (options.searchTimeout) {
lcbDsnObj.options.search_timeout = fmtTmt(options.searchTimeout)
}
if (options.managementTimeout) {
lcbDsnObj.options.http_timeout = fmtTmt(options.managementTimeout)
}
let lcbTracer: CppTracer | undefined = undefined
if (options.tracer) {
if (options.tracer instanceof NoopTracer) {
lcbDsnObj.options.enable_tracing = 'off'
} else if (options.tracer instanceof ThresholdLoggingTracer) {
const tracerOpts = options.tracer._options
lcbDsnObj.options.enable_tracing = 'on'
if (tracerOpts.emitInterval) {
lcbDsnObj.options.tracing_threshold_queue_flush_interval = fmtTmt(
tracerOpts.emitInterval
)
}
if (tracerOpts.sampleSize) {
lcbDsnObj.options.tracing_threshold_queue_size =
tracerOpts.sampleSize.toString()
}
if (tracerOpts.kvThreshold) {
lcbDsnObj.options.tracing_threshold_kv = fmtTmt(
tracerOpts.kvThreshold
)
}
if (tracerOpts.queryThreshold) {
lcbDsnObj.options.tracing_threshold_query = fmtTmt(
tracerOpts.queryThreshold
)
}
if (tracerOpts.viewsThreshold) {
lcbDsnObj.options.tracing_threshold_view = fmtTmt(
tracerOpts.viewsThreshold
)
}
if (tracerOpts.searchThreshold) {
lcbDsnObj.options.tracing_threshold_search = fmtTmt(
tracerOpts.searchThreshold
)
}
if (tracerOpts.analyticsThreshold) {
lcbDsnObj.options.tracing_threshold_analytics = fmtTmt(
tracerOpts.analyticsThreshold
)
}
} else {
lcbDsnObj.options.enable_tracing = 'on'
lcbTracer = options.tracer
}
}
let lcbMeter: CppMeter | undefined = undefined
if (options.meter) {
if (options.meter instanceof NoopMeter) {
lcbDsnObj.options.enable_operation_metrics = 'off'
} else if (options.meter instanceof LoggingMeter) {
const meterOpts = options.meter._options
lcbDsnObj.options.enable_operation_metrics = 'on'
if (meterOpts.emitInterval) {
lcbDsnObj.options.operation_metrics_flush_interval = fmtTmt(
meterOpts.emitInterval
)
}
} else {
lcbDsnObj.options.enable_operation_metrics = 'on'
lcbMeter = options.meter
}
}
lcbDsnObj.options.client_string = getClientString()
const lcbConnStr = lcbDsnObj.toString()
let lcbConnType = binding.LCB_TYPE_CLUSTER
if (lcbDsnObj.bucket) {
lcbConnType = binding.LCB_TYPE_BUCKET
}
// This conversion relies on the LogSeverity and CppLogSeverity enumerations
// always being in sync. There is a test that ensures this.
const lcbLogFunc = options.logFunc as any as CppLogFunc
this._inst = new binding.Connection(
lcbConnType,
lcbConnStr,
options.username,
options.password,
lcbLogFunc,
lcbTracer,
lcbMeter
)
// If a bucket name is specified, this connection is immediately marked as
// opened, with the assumption that the binding is doing this implicitly.
if (lcbDsnObj.bucket) {
this._opened = true
}
}
connect(callback: (err: Error | null) => void): void {
this._inst.connect((err) => {
if (err) {
this._closed = true
this._closedErr = translateCppError(err)
callback(this._closedErr)
this._connectWaiters.forEach((waitFn) => waitFn())
this._connectWaiters = []
return
}
this._connected = true
callback(null)
this._connectWaiters.forEach((waitFn) => waitFn())
this._connectWaiters = []
})
}
selectBucket(
bucketName: string,
callback: (err: Error | null) => void
): void {
this._inst.selectBucket(bucketName, (err) => {
if (err) {
return callback(translateCppError(err))
}
this._opened = true
callback(null)
})
}
close(callback: (err: Error | null) => void): void {
if (this._closed) {
return
}
this._closed = true
this._closedErr = new ConnectionClosedError()
this._inst.shutdown()
callback(null)
}
get(
...args: CppCbToNew<CppConnection['get']>
): ReturnType<CppConnection['get']> {
return this._proxyToConn(this._inst, this._inst.get, ...args)
}
exists(
...args: CppCbToNew<CppConnection['exists']>
): ReturnType<CppConnection['exists']> {
return this._proxyToConn(this._inst, this._inst.exists, ...args)
}
getReplica(
...args: CppCbToNew<CppConnection['getReplica']>
): ReturnType<CppConnection['getReplica']> {
return this._proxyToConn(this._inst, this._inst.getReplica, ...args)
}
store(
...args: CppCbToNew<CppConnection['store']>
): ReturnType<CppConnection['store']> {
return this._proxyToConn(this._inst, this._inst.store, ...args)
}
remove(
...args: CppCbToNew<CppConnection['remove']>
): ReturnType<CppConnection['remove']> {
return this._proxyToConn(this._inst, this._inst.remove, ...args)
}
touch(
...args: CppCbToNew<CppConnection['touch']>
): ReturnType<CppConnection['touch']> {
return this._proxyToConn(this._inst, this._inst.touch, ...args)
}
unlock(
...args: CppCbToNew<CppConnection['unlock']>
): ReturnType<CppConnection['unlock']> {
return this._proxyToConn(this._inst, this._inst.unlock, ...args)
}
counter(
...args: CppCbToNew<CppConnection['counter']>
): ReturnType<CppConnection['counter']> {
return this._proxyToConn(this._inst, this._inst.counter, ...args)
}
lookupIn(
...args: CppCbToNew<CppConnection['lookupIn']>
): ReturnType<CppConnection['lookupIn']> {
return this._proxyToConn(this._inst, this._inst.lookupIn, ...args)
}
mutateIn(
...args: CppCbToNew<CppConnection['mutateIn']>
): ReturnType<CppConnection['mutateIn']> {
return this._proxyToConn(this._inst, this._inst.mutateIn, ...args)
}
viewQuery(
...args: CppCbToNew<CppConnection['viewQuery']>
): ReturnType<CppConnection['viewQuery']> {
return this._proxyToConn(this._inst, this._inst.viewQuery, ...args)
}
query(
...args: CppCbToNew<CppConnection['query']>
): ReturnType<CppConnection['query']> {
return this._proxyToConn(this._inst, this._inst.query, ...args)
}
analyticsQuery(
...args: CppCbToNew<CppConnection['analyticsQuery']>
): ReturnType<CppConnection['analyticsQuery']> {
return this._proxyToConn(this._inst, this._inst.analyticsQuery, ...args)
}
searchQuery(
...args: CppCbToNew<CppConnection['searchQuery']>
): ReturnType<CppConnection['searchQuery']> {
return this._proxyToConn(this._inst, this._inst.searchQuery, ...args)
}
httpRequest(
...args: CppCbToNew<CppConnection['httpRequest']>
): ReturnType<CppConnection['httpRequest']> {
return this._proxyOnBootstrap(this._inst, this._inst.httpRequest, ...args)
}
ping(
...args: CppCbToNew<CppConnection['ping']>
): ReturnType<CppConnection['ping']> {
return this._proxyOnBootstrap(this._inst, this._inst.ping, ...args)
}
diag(
...args: CppCbToNew<CppConnection['diag']>
): ReturnType<CppConnection['diag']> {
return this._proxyToConn(this._inst, this._inst.diag, ...args)
}
private _proxyOnBootstrap<FArgs extends any[], CbArgs extends any[]>(
thisArg: CppConnection,
fn: (
...cppArgs: [
...FArgs,
(...cppCbArgs: [CppError | null, ...CbArgs]) => void
]
) => void,
...newArgs: [...FArgs, (...newCbArgs: [Error | null, ...CbArgs]) => void]
) {
if (this._closed || this._connected) {
return this._proxyToConn(thisArg, fn, ...newArgs)
} else {
this._connectWaiters.push(() => {
return this._proxyToConn(thisArg, fn, ...newArgs)
})
}
}
private _proxyToConn<FArgs extends any[], CbArgs extends any[]>(
thisArg: CppConnection,
fn: (
...cppArgs: [
...FArgs,
(...cppCbArgs: [CppError | null, ...CbArgs]) => void
]
) => void,
...newArgs: [...FArgs, (...newCbArgs: [Error | null, ...CbArgs]) => void]
) {
const wrappedArgs = newArgs
const callback = wrappedArgs.pop() as (
...cbArgs: [Error | null, ...CbArgs]
) => void
if (this._closed) {
return (callback as any as ErrCallback)(this._closedErr)
}
wrappedArgs.push((err: CppError | null, ...cbArgs: CbArgs) => {
const translatedErr = translateCppError(err)
callback.apply(undefined, [translatedErr, ...cbArgs])
})
fn.apply(thisArg, wrappedArgs)
}
} | the_stack |
import { ApiClient, token } from '..'
import BigNumber from 'bignumber.js'
/**
* Loan RPCs for DeFi Blockchain
*/
export class Loan {
private readonly client: ApiClient
constructor (client: ApiClient) {
this.client = client
}
/**
* Creates a loan scheme transaction.
*
* @param {CreateLoanScheme} scheme
* @param {number} scheme.minColRatio Minimum collateralization ratio
* @param {BigNumber} scheme.interestRate Interest rate
* @param {string} scheme.id Unique identifier of the loan scheme, max 8 chars
* @param {UTXO[]} [utxos = []] Specific UTXOs to spend
* @param {string} utxos.txid Transaction Id
* @param {number} utxos.vout Output number
* @return {Promise<string>} LoanSchemeId, also the txn id for txn created to create loan scheme
*/
async createLoanScheme (scheme: CreateLoanScheme, utxos: UTXO[] = []): Promise<string> {
return await this.client.call('createloanscheme', [scheme.minColRatio, scheme.interestRate, scheme.id, utxos], 'number')
}
/**
* Updates an existing loan scheme.
*
* @param {UpdateLoanScheme} scheme
* @param {number} scheme.minColRatio Minimum collateralization ratio
* @param {BigNumber} scheme.interestRate Interest rate
* @param {string} scheme.id Unique identifier of the loan scheme, max 8 chars
* @param {number} [scheme.activateAfterBlock] Block height at which new changes take effect
* @param {UTXO[]} [utxos = []] Specific UTXOs to spend
* @param {string} utxos.txid Transaction Id
* @param {number} utxos.vout Output number
* @return {Promise<string>} Hex string of the transaction
*/
async updateLoanScheme (scheme: UpdateLoanScheme, utxos: UTXO[] = []): Promise<string> {
return await this.client.call('updateloanscheme', [scheme.minColRatio, scheme.interestRate, scheme.id, scheme.activateAfterBlock, utxos], 'number')
}
/**
* Destroys a loan scheme.
*
* @param {DestroyLoanScheme} scheme
* @param {string} scheme.id Unique identifier of the loan scheme, max 8 chars
* @param {number} [scheme.activateAfterBlock] Block height at which new changes take effect
* @param {UTXO[]} [utxos = []] Specific UTXOs to spend
* @param {string} utxos.txid Transaction Id
* @param {number} utxos.vout Output number
* @return {Promise<string>} Hex string of the transaction
*/
async destroyLoanScheme (scheme: DestroyLoanScheme, utxos: UTXO[] = []): Promise<string> {
return await this.client.call('destroyloanscheme', [scheme.id, scheme.activateAfterBlock, utxos], 'number')
}
/**
* List all available loan schemes.
*
* @return {Promise<LoanSchemeResult[]>}
*/
async listLoanSchemes (): Promise<LoanSchemeResult[]> {
return await this.client.call('listloanschemes', [], 'bignumber')
}
/**
* Get loan scheme.
*
* @param {string} id Unique identifier of the loan scheme, max 8 chars.
* @return {Promise<GetLoanSchemeResult>}
*/
async getLoanScheme (id: string): Promise<GetLoanSchemeResult> {
return await this.client.call('getloanscheme', [id], 'bignumber')
}
/**
* Sets the default loan scheme.
*
* @param {string} id Unique identifier of the loan scheme, max 8 chars
* @param {UTXO[]} [utxos = []] Specific UTXOs to spend
* @param {string} utxos.txid Transaction Id
* @param {number} utxos.vout Output number
* @return {Promise<string>} Hex string of the transaction
*/
async setDefaultLoanScheme (id: string, utxos: UTXO[] = []): Promise<string> {
return await this.client.call('setdefaultloanscheme', [id, utxos], 'number')
}
/**
* Set a collateral token transaction.
*
* @param {SetCollateralToken} collateralToken
* @param {string} collateralToken.token Symbol or id of collateral token
* @param {BigNumber} collateralToken.factor Collateralization factor
* @param {string} collateralToken.fixedIntervalPriceId token/currency pair to use for price of token
* @param {number} [collateralToken.activateAfterBlock] changes will be active after the block height
* @param {UTXO[]} [utxos = []] Specific UTXOs to spend
* @param {string} utxos.txid Transaction Id
* @param {number} utxos.vout Output number
* @return {Promise<string>} collateralTokenId, also the txn id for txn created to set collateral token
*/
async setCollateralToken (collateralToken: SetCollateralToken, utxos: UTXO[] = []): Promise<string> {
return await this.client.call('setcollateraltoken', [collateralToken, utxos], 'number')
}
/**
* List collateral tokens.
*
* @param {ListCollateralTokens} [collateralToken = {}]
* @param {number} [collateralToken.height = CurrentBlockheight] Valid at specified height
* @param {boolean} [collateralToken.all] True = All transactions, false = Activated transactions
* @return {Promise<CollateralTokenDetail[]>} Get all collateral tokens
*/
async listCollateralTokens (collateralToken: ListCollateralTokens = {}): Promise<CollateralTokenDetail[]> {
return await this.client.call('listcollateraltokens', [collateralToken], 'bignumber')
}
/**
* Get collateral token.
*
* @param {string} token symbol or id
* @return {Promise<CollateralTokenDetail>} Collateral token result
*/
async getCollateralToken (token: string): Promise<CollateralTokenDetail> {
return await this.client.call('getcollateraltoken', [token], 'bignumber')
}
/**
* Creates (and submits to local node and network) a token for a price feed set in collateral token.
*
* @param {SetLoanToken} loanToken
* @param {string} loanToken.symbol Token's symbol (unique), no longer than 8
* @param {string} [loanToken.name] Token's name, no longer than 128
* @param {string} loanToken.fixedIntervalPriceId token/currency pair to use for price of token
* @param {boolean} [loanToken.mintable = true] Token's 'Mintable' property
* @param {BigNumber} [loanToken.interest = 0] Interest rate
* @param {UTXO[]} [utxos = []] Specific UTXOs to spend
* @param {string} utxos.txid Transaction Id
* @param {number} utxos.vout Output number
* @return {Promise<string>} LoanTokenId, also the txn id for txn created to set loan token
*/
async setLoanToken (loanToken: SetLoanToken, utxos: UTXO[] = []): Promise<string> {
const payload = {
mintable: true,
interest: 0,
...loanToken
}
return await this.client.call('setloantoken', [payload, utxos], 'number')
}
/**
* Quick access to multiple API with consolidated total collateral and loan value.
* @see {@link listCollateralTokens}
* @see {@link listLoanTokens}
* @see {@link listLoanSchemes}
*
* @returns {Promise<GetLoanInfoResult>}
*/
async getLoanInfo (): Promise<GetLoanInfoResult> {
return await this.client.call('getloaninfo', [], 'bignumber')
}
/**
* Updates an existing loan token.
*
* @param {string} oldToken Previous tokens's symbol, id or creation tx (unique)
* @param {UpdateLoanToken} newTokenDetails
* @param {string} [newTokenDetails.symbol] New token's symbol (unique), no longer than 8
* @param {string} [newTokenDetails.name] Token's name, no longer than 128
* @param {string} [newTokenDetails.fixedIntervalPriceId] token/currency pair to use for price of token
* @param {boolean} [newTokenDetails.mintable] Token's 'Mintable' property
* @param {BigNumber} [newTokenDetails.interest] Interest rate
* @param {UTXO[]} [utxos = []] Specific UTXOs to spend
* @param {string} utxos.txid Transaction Id
* @param {number} utxos.vout Output number
* @return {Promise<string>} LoanTokenId, also the txn id for txn created to update loan token
*/
async updateLoanToken (oldToken: string, newTokenDetails: UpdateLoanToken, utxos: UTXO[] = []): Promise<string> {
return await this.client.call('updateloantoken', [oldToken, newTokenDetails, utxos], 'number')
}
/**
* Get interest info
*
* @param {string} id Loan scheme id
* @param {string} [token] Specified by loan token id, loan token name and loan toekn creation tx
* @return {Promise<Interest[]>}
*/
async getInterest (id: string, token?: string): Promise<Interest[]> {
return await this.client.call('getinterest', [id, token], 'bignumber')
}
/**
* Get loan token.
*
* @param {string} token Symbol or id of loan token
* @return {Promise<LoanTokenResult>} Loan token details
*/
async getLoanToken (token: string): Promise<LoanTokenResult> {
return await this.client.call('getloantoken', [token], 'bignumber')
}
/**
* List all created loan tokens.
*
* @return {Promise<LoanTokenResult[]>}
*/
async listLoanTokens (): Promise<LoanTokenResult[]> {
return await this.client.call('listloantokens', [], 'bignumber')
}
/**
* Creates a vault transaction.
*
* @param {CreateVault} vault
* @param {string} vault.ownerAddress Any valid address or "" to generate a new address
* @param {number} [vault.loanSchemeId] Unique identifier of the loan scheme (8 chars max). If empty, the default loan scheme will be selected
* @param {UTXO[]} [utxos = []] Specific UTXOs to spend
* @param {string} utxos.txid Transaction Id
* @param {number} utxos.vout Output number
* @return {Promise<string>} Transaction id of the transaction
*/
async createVault (vault: CreateVault, utxos: UTXO[] = []): Promise<string> {
return await this.client.call('createvault', [vault.ownerAddress, vault.loanSchemeId, utxos], 'number')
}
/**
* Create update vault transaction.
*
* @param {string} vaultId
* @param {UpdateVault} vault
* @param {string} [vault.ownerAddress] Any valid address
* @param {string} [vault.loanSchemeId] Unique identifier of the loan scheme (8 chars max)
* @param {UTXO[]} [utxos = []] Specific UTXOs to spend
* @param {string} utxos.txid Transaction Id
* @param {number} utxos.vout Output number
* @return {Promise<string>} Transaction id of the transaction
*/
async updateVault (vaultId: string, vault: UpdateVault, utxos: UTXO[] = []): Promise<string> {
return await this.client.call('updatevault', [vaultId, vault, utxos], 'number')
}
/**
* Returns information about vault.
*
* @param {string} vaultId vault hex id
* @return {Promise<VaultActive | VaultLiquidation>}
*/
async getVault (vaultId: string): Promise<VaultActive | VaultLiquidation> {
return await this.client.call(
'getvault',
[vaultId],
{
collateralValue: 'bignumber',
loanValue: 'bignumber',
interestValue: 'bignumber',
informativeRatio: 'bignumber'
}
)
}
/**
* List all available vaults.
*
* @param {VaultPagination} [pagination]
* @param {string} [pagination.start]
* @param {boolean} [pagination.including_start]
* @param {number} [pagination.limit=100]
* @param {ListVaultOptions} [options]
* @param {string} [options.ownerAddress] Address of the vault owner
* @param {string} [options.loanSchemeId] Vault's loan scheme id
* @param {VaultState} [options.state = VaultState.UNKNOWN] vault's state
* @param {boolean} [options.verbose = false] true to return same information as getVault
* @return {Promise<Vault | VaultActive | VaultLiquidation[]>} Array of objects including details of the vaults.
*/
async listVaults (pagination: VaultPagination = {}, options: ListVaultOptions = {}): Promise<Array<Vault | VaultActive | VaultLiquidation>> {
return await this.client.call(
'listvaults',
[options, pagination],
{
collateralValue: 'bignumber',
loanValue: 'bignumber',
interestValue: 'bignumber',
informativeRatio: 'bignumber'
}
)
}
/**
* Close vault
*
* @param {CloseVault} closeVault
* @param {string} closeVault.vaultId Vault id
* @param {string} closeVault.to Valid address to receive collateral tokens
* @param {UTXO[]} [utxos = []] Specific UTXOs to spend
* @param {string} utxos.txid Transaction Id
* @param {number} utxos.vout Output number
* @return {Promise<string>}
*/
async closeVault (closeVault: CloseVault, utxos: UTXO[] = []): Promise<string> {
return await this.client.call('closevault', [closeVault.vaultId, closeVault.to, utxos], 'number')
}
/**
* Deposit to vault
*
* @param {DepositVault} depositVault
* @param {string} depositVault.vaultId Vault id
* @param {string} depositVault.from Collateral address
* @param {string} depositVault.amount In "amount@symbol" format
* @param {UTXO[]} [utxos = []] Specific UTXOs to spend
* @param {string} utxos.txid Transaction Id
* @param {number} utxos.vout Output number
* @return {Promise<string>}
*/
async depositToVault (depositVault: DepositVault, utxos: UTXO[] = []): Promise<string> {
return await this.client.call('deposittovault', [depositVault.vaultId, depositVault.from, depositVault.amount, utxos], 'number')
}
/**
* Withdraw from vault
*
* @param {WithdrawVault} withdrawVault
* @param {string} withdrawVault.vaultId Vault id
* @param {string} withdrawVault.to Collateral address
* @param {string} withdrawVault.amount In "amount@symbol" format
* @param {UTXO[]} [utxos = []] Specific UTXOs to spend
* @param {string} utxos.txid Transaction Id
* @param {number} utxos.vout Output number
* @return {Promise<string>}
*/
async withdrawFromVault (withdrawVault: WithdrawVault, utxos: UTXO[] = []): Promise<string> {
return await this.client.call('withdrawfromvault', [withdrawVault.vaultId, withdrawVault.to, withdrawVault.amount, utxos], 'number')
}
/**
* Take loan
*
* @param {TakeLoanMetadata} metadata
* @param {string} metadata.vaultId Vault id
* @param {string | string[]} metadata.amounts In "amount@symbol" format
* @param {string} [metadata.to] Address to receive tokens
* @param {UTXO[]} [utxos = []] Specific UTXOs to spend
* @param {string} utxos.txid Transaction Id
* @param {number} utxos.vout Output number
* @return {Promise<string>}
*/
async takeLoan (metadata: TakeLoanMetadata, utxos: UTXO[] = []): Promise<string> {
return await this.client.call('takeloan', [metadata, utxos], 'number')
}
/**
* Return loan in a desired amount.
*
* @param {PaybackLoanMetadata} metadata
* @param {string} metadata.vaultId Vault id
* @param {string| string[]} metadata.amounts In "amount@symbol" format
* @param {string} metadata.from Address from transfer tokens
* @param {UTXO[]} [utxos = []] Specific UTXOs to spend
* @param {string} utxos.txid Transaction Id
* @param {number} utxos.vout Output number
* @return {Promise<string>} txid
*/
async paybackLoan (metadata: PaybackLoanMetadata, utxos: UTXO[] = []): Promise<string> {
return await this.client.call('paybackloan', [metadata, utxos], 'number')
}
/**
* Bid to vault in auction
*
* @param {PlaceAuctionBid} placeAuctionBid
* @param {string} placeAuctionBid.vaultId Vault Id
* @param {index} placeAuctionBid.index Auction index
* @param {from} placeAuctionBid.from Address to get token
* @param {amount} placeAuctionBid.amount in "amount@symbol" format
* @param {UTXO[]} [utxos = []] Specific UTXOs to spend
* @param {string} utxos.txid Transaction Id
* @param {number} utxos.vout Output number
* @return {Promise<string>} The transaction id
*/
async placeAuctionBid (placeAuctionBid: PlaceAuctionBid, utxos: UTXO[] = []): Promise<string> {
return await this.client.call(
'placeauctionbid',
[placeAuctionBid.vaultId, placeAuctionBid.index, placeAuctionBid.from, placeAuctionBid.amount, utxos],
'number'
)
}
/**
* List all available auctions.
*
* @param {AuctionPagination} pagination
* @param {AuctionPaginationStart} [pagination.start]
* @param {string} [pagination.start.vaultId]
* @param {number} [pagination.start.height]
* @param {boolean} [pagination.including_start]
* @param {number} [pagination.limit=100]
* @return {Promise<VaultLiquidation[]>}
*/
async listAuctions (pagination: AuctionPagination = {}): Promise<VaultLiquidation[]> {
const defaultPagination = {
limit: 100
}
return await this.client.call('listauctions', [{ ...defaultPagination, ...pagination }], 'number')
}
/**
* Returns information about auction history.
*
* @param {string} [owner] address or reserved word : mine / all (Default to mine)
* @param {ListAuctionHistoryPagination} pagination
* @param {number} [pagination.maxBlockHeight] Maximum block height
* @param {string} [pagination.vaultId] Vault Id
* @param {number} [pagination.index] Auction index
* @param {number} [pagination.limit = 100]
* @return {Promise<ListAuctionHistoryDetail>}
*/
async listAuctionHistory (owner: string = 'mine', pagination?: ListAuctionHistoryPagination): Promise<ListAuctionHistoryDetail[]> {
const defaultPagination = {
limit: 100
}
return await this.client.call('listauctionhistory', [owner, { ...defaultPagination, ...pagination }], 'number')
}
}
export interface CreateLoanScheme {
minColRatio: number
interestRate: BigNumber
id: string
}
export interface UpdateLoanScheme {
minColRatio: number
interestRate: BigNumber
id: string
activateAfterBlock?: number
}
export interface DestroyLoanScheme {
id: string
activateAfterBlock?: number
}
export interface LoanSchemeResult {
id: string
mincolratio: BigNumber
interestrate: BigNumber
default: boolean
}
export interface SetCollateralToken {
token: string
factor: BigNumber
fixedIntervalPriceId: string
activateAfterBlock?: number
}
export interface GetLoanSchemeResult {
id: string
interestrate: BigNumber
mincolratio: BigNumber
default: boolean
}
export interface ListCollateralTokens {
height?: number
all?: boolean
}
export interface CollateralTokenDetail {
token: string
factor: BigNumber
fixedIntervalPriceId: string
activateAfterBlock: BigNumber
tokenId: string
}
export interface SetLoanToken {
symbol: string
name?: string
fixedIntervalPriceId: string
mintable?: boolean
interest?: BigNumber
}
export interface LoanTokenResult {
token: token.TokenResult
fixedIntervalPriceId: string
interest: BigNumber
}
export interface LoanConfig {
fixedIntervalBlocks: BigNumber
maxPriceDeviationPct: BigNumber
minOraclesPerPrice: BigNumber
scheme: string
}
export interface LoanSummary {
collateralTokens: BigNumber
collateralValue: BigNumber
loanTokens: BigNumber
loanValue: BigNumber
openAuctions: BigNumber
openVaults: BigNumber
schemes: BigNumber
}
export interface GetLoanInfoResult {
currentPriceBlock: BigNumber
nextPriceBlock: BigNumber
defaults: LoanConfig
totals: LoanSummary
}
export interface UpdateLoanToken {
symbol?: string
name?: string
fixedIntervalPriceId?: string
mintable?: boolean
interest?: BigNumber
}
export interface Interest {
token: string
totalInterest: BigNumber
interestPerBlock: BigNumber
}
export interface CreateVault {
ownerAddress: string
loanSchemeId?: string
}
export interface UpdateVault {
ownerAddress?: string
loanSchemeId?: string
}
export enum VaultState {
UNKNOWN = 'unknown',
ACTIVE = 'active',
IN_LIQUIDATION = 'inLiquidation',
FROZEN = 'frozen',
MAY_LIQUIDATE = 'mayLiquidate',
}
export interface Vault {
vaultId: string
loanSchemeId: string
ownerAddress: string
state: VaultState
}
export interface VaultActive extends Vault {
collateralAmounts: string[]
loanAmounts: string[]
interestAmounts: string[]
collateralValue: BigNumber
loanValue: BigNumber
interestValue: BigNumber
collateralRatio: number
informativeRatio: BigNumber
}
export interface VaultLiquidation extends Vault {
liquidationHeight: number
liquidationPenalty: number
batchCount: number
batches: VaultLiquidationBatch[]
}
export interface UTXO {
txid: string
vout: number
}
export interface DepositVault {
vaultId: string
from: string
amount: string // amount@symbol
}
export interface WithdrawVault {
vaultId: string
to: string
amount: string // amount@symbol
}
export interface TakeLoanMetadata {
vaultId: string
amounts: string | string[] // amount@symbol
to?: string
}
export interface PaybackLoanMetadata {
vaultId: string
amounts: string | string[] // amount@symbol
from: string
}
export interface VaultPagination {
start?: string
including_start?: boolean
limit?: number
}
export interface ListVaultOptions {
ownerAddress?: string
loanSchemeId?: string
state?: VaultState
verbose?: boolean
}
export interface CloseVault {
vaultId: string
to: string
}
export interface PlaceAuctionBid {
vaultId: string
index: number
from: string
amount: string // amount@symbol
}
export interface AuctionPagination {
start?: AuctionPaginationStart
including_start?: boolean
limit?: number
}
export interface AuctionPaginationStart {
vaultId?: string
height?: number
}
export interface VaultLiquidationBatch {
index: number
collaterals: string[]
loan: string
highestBid?: HighestBid
}
export interface HighestBid {
amount: string // amount@symbol
owner: string
}
export interface ListAuctionHistoryPagination {
maxBlockHeight?: number
vaultId?: string
index?: number
limit?: number
}
export interface ListAuctionHistoryDetail {
winner: string
blockHeight: number
blockHash: string
blockTime: number
vaultId: string
batchIndex: number
auctionBid: string
auctionWon: string[]
} | the_stack |
import * as path from 'path';
const pluginDirectory = path.join(
path.resolve(__dirname, '..'),
'src',
'plugins'
);
export type CLSMechanism =
| 'async-hooks'
| 'async-listener'
| 'auto'
| 'none'
| 'singular';
export type ContextHeaderBehavior = 'default' | 'ignore' | 'require';
export interface RequestDetails {
/**
* The request timestamp.
*/
timestamp: number;
/**
* The request URL.
*/
url: string;
/**
* The request method.
*/
method: string;
/**
* The parsed trace context, if it exists.
*/
traceContext: {traceId: string; spanId: string; options: number} | null;
/**
* The original options object used to create the root span that corresponds
* to this request.
*/
options: {};
}
export interface TracePolicy {
shouldTrace: (requestDetails: RequestDetails) => boolean;
}
export interface GetHeaderFunction {
getHeader: (key: string) => string[] | string | undefined;
}
export interface SetHeaderFunction {
setHeader: (key: string, value: string) => void;
}
export interface OpenCensusPropagation {
extract: (getHeader: GetHeaderFunction) => {
traceId: string;
spanId: string;
options?: number;
} | null;
inject: (
setHeader: SetHeaderFunction,
traceContext: {
traceId: string;
spanId: string;
options?: number;
}
) => void;
}
/**
* Available configuration options. All fields are optional. See the
* defaultConfig object defined in this file for default assigned values.
*/
export interface Config {
/**
* Log levels: 0=disabled, 1=error, 2=warn, 3=info, 4=debug
* The value of GCLOUD_TRACE_LOGLEVEL takes precedence over this value.
*/
logLevel?: number;
/**
* If set to true, prevents a warning from being emitted if modules are
* required before the Trace Agent.
*/
disableUntracedModulesWarning?: boolean;
/**
* Whether to enable to Trace Agent or not.
* Once enabled, the Trace Agent may not be disabled.
*/
enabled?: boolean;
/**
* If true, additional information about query parameters and results will be
* attached (as labels) to spans representing database operations.
*/
enhancedDatabaseReporting?: boolean;
/**
* A value that can be used to override names of root spans. If specified as
* a string, the string will be used to replace all such span names; if
* specified as a function, the function will be invoked with the request path
* as an argument, and its return value will be used as the span name.
*/
rootSpanNameOverride?: string | ((name: string) => string);
/**
* The trace context propagation mechanism to use. The following options are
* available:
* - 'async-hooks' uses an implementation of CLS on top of the Node core
* `async_hooks` module in Node 8+. This option should not be used if the
* Node binary version requirements are not met.
* - 'async-listener' uses an implementation of CLS on top of the
* `continuation-local-storage` module.
* - 'auto' behaves like 'async-hooks' on Node 8+, and 'async-listener'
* otherwise.
* - 'none' disables CLS completely.
* - 'singular' allows one root span to exist at a time. This option is meant
* to be used internally by Google Cloud Functions, or in any other
* environment where it is guaranteed that only one request is being served
* at a time.
* The 'auto' mechanism is used by default if this configuration option is
* not explicitly set.
*/
clsMechanism?: CLSMechanism;
/**
* The number of local spans per trace to allow before emitting an error log.
* An unexpectedly large number of spans per trace may suggest a memory leak.
* This value should be 1-2x the estimated maximum number of RPCs made on
* behalf of a single incoming request.
*/
spansPerTraceSoftLimit?: number;
/**
* The maximum number of local spans per trace to allow in total. Creating
* more spans in a single trace will cause the agent to log an error, and such
* spans will be dropped. (This limit does not apply when using a RootSpan
* instance to create child spans.)
* This value should be greater than spansPerTraceSoftLimit.
*/
spansPerTraceHardLimit?: number;
/**
* The maximum number of characters reported on a label value. This value
* cannot exceed 16383, the maximum value accepted by the service.
*/
maximumLabelValueSize?: number;
/**
* A list of trace plugins to load. Each field's key in this object is the
* name of the module to trace, and its value is the require-friendly path
* to the plugin. (See the default configuration below for examples.)
* Any user-provided value will be used to extend its default value.
* To disable a plugin in this list, you may override its path with a falsy
* value. Disabling any of the default plugins may cause unwanted behavior,
* so use caution.
*/
plugins?: {[pluginName: string]: string};
/**
* The max number of frames to include on traces; pass a value of 0 to
* disable stack frame limits.
*/
stackTraceLimit?: number;
/**
* URLs that partially match any regex in ignoreUrls will not be traced.
* In addition, URLs that are _exact matches_ of strings in ignoreUrls will
* also not be traced (this is deprecated behavior and will be removed in v3).
* URLs should be expected to be in the form of:
* /componentOne/componentTwo...
* For example, having an ignoreUrls value of ['/'] will ignore all URLs,
* while having an ignoreUrls value of ['^/$'] will ignore only '/' URLs.
* Health checker probe URLs (/_ah/health) are ignored by default.
*/
ignoreUrls?: Array<string | RegExp>;
/**
* Request methods that match any string in ignoreMethods will not be traced.
* matching is *not* case-sensitive (OPTIONS == options == OptiONs)
*
* No methods are ignored by default.
*/
ignoreMethods?: string[];
/**
* An upper bound on the number of traces to gather each second. If set to 0,
* sampling is disabled and all traces are recorded. Sampling rates greater
* than 1000 are not supported and will result in at most 1000 samples per
* second. Some Google Cloud environments may further limit this rate.
*/
samplingRate?: number;
/**
* Specifies whether to trace based on the 'traced' bit specified on incoming
* trace context headers. The following options are available:
* 'default' -- Don't trace incoming requests that have a trace context
* header with its 'traced' bit set to 0.
* 'require' -- Don't trace incoming requests that have a trace context
* header with its 'traced' bit set to 0, or incoming requests without a
* trace context header.
* 'ignore' -- The 'traced' bit will be ignored. In other words, the context
* header isn't used to determine whether a request will be traced at all.
* This might be useful for aggregating traces generated by different cloud
* platform projects.
*/
contextHeaderBehavior?: ContextHeaderBehavior;
/**
* For advanced usage only.
* If specified, overrides the built-in trace policy object.
* Note that if any of ignoreUrls, ignoreMethods, samplingRate, or
* contextHeaderBehavior is specified, an error will be thrown when start()
* is called.
*/
tracePolicy?: TracePolicy;
/**
* If specified, the Trace Agent will use this context header propagation
* implementation instead of @opencensus/propagation-stackdriver, the default
* trace context header format.
*/
propagation?: OpenCensusPropagation;
/**
* Buffer the captured traces for `flushDelaySeconds` seconds before
* publishing to the Stackdriver Trace API, unless the buffer fills up first.
* Also see `bufferSize`.
*/
flushDelaySeconds?: number;
/**
* The number of spans in buffered traces needed to trigger a publish of all
* traces to the Stackdriver Trace API, unless `flushDelaySeconds` seconds
* has elapsed first.
*/
bufferSize?: number;
/**
* Specifies the behavior of the trace agent in the case of an uncaught
* exception. Possible values are:
* `ignore`: Take no action. The process may terminate before all the traces
* currently buffered have been flushed to the network.
* `flush`: Handle the uncaught exception and attempt to publish the traces
* to the API. Note that if you have other uncaught exception
* handlers in your application, they may choose to terminate the
* process before the buffer has been flushed to the network. Also,
* if you have no other terminating uncaught exception handlers in
* your application, the error will get swallowed and the
* application will keep on running. You should use this option if
* you have other uncaught exception handlers that you want to be
* responsible for terminating the application.
* `flushAndExit`: Handle the uncaught exception, make a best effort attempt
* to publish the traces to the API, and then terminate the
* application after a delay. Note that the presence of other
* uncaught exception handlers may choose to terminate the
* application before the buffer has been flushed to the network.
*/
onUncaughtException?: string;
/**
* The ID of the Google Cloud Platform project with which traces should
* be associated. The value of GCLOUD_PROJECT takes precedence over this
* value; if neither are provided, the trace agent will attempt to retrieve
* this information from the GCE metadata service.
*/
projectId?: string;
/**
* The contents of a key file. If this field is set, its contents will be
* used for authentication instead of your application default credentials.
*/
credentials?: {client_email?: string; private_key?: string};
/**
* A path to a key file relative to the current working directory. If this
* field is set, the contents of the pointed file will be used for
* authentication instead of your application default credentials.
* If credentials is also set, the value of keyFilename will be ignored.
*/
keyFilename?: string;
/**
* Specifies the service context with which traces from this application
* will be associated. This may be useful in filtering traces originating
* from a specific service within a project. These fields will automatically
* be set through environment variables on Google App Engine.
*/
serviceContext?: {
service?: string;
version?: string;
minorVersion?: string;
};
}
/**
* Default configuration. For fields with primitive values, any user-provided
* value will override the corresponding default value.
* For fields with non-primitive values (plugins and serviceContext), the
* user-provided value will be used to extend the default value.
*/
export const defaultConfig = {
logLevel: 1,
disableUntracedModulesWarning: false,
enabled: true,
enhancedDatabaseReporting: false,
rootSpanNameOverride: (name: string) => name,
clsMechanism: 'auto' as CLSMechanism,
spansPerTraceSoftLimit: 200,
spansPerTraceHardLimit: 1000,
maximumLabelValueSize: 512,
plugins: {
// enable all by default
bluebird: path.join(pluginDirectory, 'plugin-bluebird.js'),
connect: path.join(pluginDirectory, 'plugin-connect.js'),
express: path.join(pluginDirectory, 'plugin-express.js'),
'generic-pool': path.join(pluginDirectory, 'plugin-generic-pool.js'),
grpc: path.join(pluginDirectory, 'plugin-grpc.js'),
hapi: path.join(pluginDirectory, 'plugin-hapi.js'),
'@hapi/hapi': path.join(pluginDirectory, 'plugin-hapi.js'),
http: path.join(pluginDirectory, 'plugin-http.js'),
http2: path.join(pluginDirectory, 'plugin-http2.js'),
koa: path.join(pluginDirectory, 'plugin-koa.js'),
mongodb: path.join(pluginDirectory, 'plugin-mongodb.js'),
'mongodb-core': path.join(pluginDirectory, 'plugin-mongodb-core.js'),
mongoose: path.join(pluginDirectory, 'plugin-mongoose.js'),
mysql: path.join(pluginDirectory, 'plugin-mysql.js'),
mysql2: path.join(pluginDirectory, 'plugin-mysql2.js'),
pg: path.join(pluginDirectory, 'plugin-pg.js'),
redis: path.join(pluginDirectory, 'plugin-redis.js'),
restify: path.join(pluginDirectory, 'plugin-restify.js'),
},
stackTraceLimit: 10,
flushDelaySeconds: 30,
ignoreUrls: ['/_ah/health'],
ignoreMethods: [],
samplingRate: 10,
contextHeaderBehavior: 'default',
bufferSize: 1000,
onUncaughtException: 'ignore',
serviceContext: {},
}; | the_stack |
export declare function connect(
opts?: ConnectionOptions,
): Promise<NatsConnection>;
export declare const Empty: Uint8Array;
export declare enum Events {
Disconnect = "disconnect",
Reconnect = "reconnect",
Update = "update",
LDM = "ldm",
Error = "error"
}
export interface Status {
type: Events | DebugEvents;
data: string | ServersChanged | number;
}
export declare enum DebugEvents {
Reconnecting = "reconnecting",
PingTimer = "pingTimer",
StaleConnection = "staleConnection"
}
export interface NatsConnection {
info?: ServerInfo;
closed(): Promise<void | Error>;
close(): Promise<void>;
publish(subject: string, data?: Uint8Array, options?: PublishOptions): void;
subscribe(subject: string, opts?: SubscriptionOptions): Subscription;
request(subject: string, data?: Uint8Array, opts?: RequestOptions): Promise<Msg>;
flush(): Promise<void>;
drain(): Promise<void>;
isClosed(): boolean;
isDraining(): boolean;
getServer(): string;
status(): AsyncIterable<Status>;
stats(): Stats;
jetstreamManager(opts?: JetStreamOptions): Promise<JetStreamManager>;
jetstream(opts?: JetStreamOptions): JetStreamClient;
}
export interface ConnectionOptions {
authenticator?: Authenticator;
debug?: boolean;
maxPingOut?: number;
maxReconnectAttempts?: number;
name?: string;
noEcho?: boolean;
noRandomize?: boolean;
pass?: string;
pedantic?: boolean;
pingInterval?: number;
port?: number;
reconnect?: boolean;
reconnectDelayHandler?: () => number;
reconnectJitter?: number;
reconnectJitterTLS?: number;
reconnectTimeWait?: number;
servers?: Array<string> | string;
timeout?: number;
tls?: TlsOptions;
token?: string;
user?: string;
verbose?: boolean;
waitOnFirstConnect?: boolean;
ignoreClusterUpdates?: boolean;
inboxPrefix?: string;
}
export interface TlsOptions {
}
export interface Msg {
subject: string;
sid: number;
reply?: string;
data: Uint8Array;
headers?: MsgHdrs;
respond(data?: Uint8Array, opts?: PublishOptions): boolean;
}
export interface SubOpts<T> {
queue?: string;
max?: number;
timeout?: number;
callback?: (err: NatsError | null, msg: T) => void;
}
export declare type SubscriptionOptions = SubOpts<Msg>;
export interface ServerInfo {
"auth_required"?: boolean;
"client_id": number;
"client_ip"?: string;
cluster?: string;
"connect_urls"?: string[];
"git_commit"?: string;
go: string;
headers?: boolean;
host: string;
jetstream?: boolean;
ldm?: boolean;
"max_payload": number;
nonce?: string;
port: number;
proto: number;
"server_id": string;
"server_name": string;
"tls_available"?: boolean;
"tls_required"?: boolean;
"tls_verify"?: boolean;
version: string;
}
export interface ServersChanged {
readonly added: string[];
readonly deleted: string[];
}
export interface Sub<T> extends AsyncIterable<T> {
closed: Promise<void>;
unsubscribe(max?: number): void;
drain(): Promise<void>;
isDraining(): boolean;
isClosed(): boolean;
callback(err: NatsError | null, msg: Msg): void;
getSubject(): string;
getReceived(): number;
getProcessed(): number;
getPending(): number;
getID(): number;
getMax(): number | undefined;
}
export declare type Subscription = Sub<Msg>;
export interface RequestOptions {
timeout: number;
headers?: MsgHdrs;
noMux?: boolean;
reply?: string;
}
export interface PublishOptions {
reply?: string;
headers?: MsgHdrs;
}
export declare function canonicalMIMEHeaderKey(k: string): string;
export declare enum Match {
Exact = 0,
CanonicalMIME = 1,
IgnoreCase = 2
}
export interface MsgHdrs extends Iterable<[string, string[]]> {
hasError: boolean;
status: string;
code: number;
description: string;
get(k: string, match?: Match): string;
set(k: string, v: string, match?: Match): void;
append(k: string, v: string, match?: Match): void;
has(k: string, match?: Match): boolean;
values(k: string, match?: Match): string[];
delete(k: string, match?: Match): void;
}
export declare function headers(): MsgHdrs;
export declare function createInbox(prefix?: string): string;
export interface Authenticator {
(nonce?: string): Auth;
}
export declare type NoAuth = void;
export interface TokenAuth {
auth_token: string;
}
export interface UserPass {
user: string;
pass?: string;
}
export interface NKeyAuth {
nkey: string;
sig: string;
}
export interface JwtAuth {
jwt: string;
nkey?: string;
sig?: string;
}
declare type Auth = NoAuth | TokenAuth | UserPass | NKeyAuth | JwtAuth;
export declare function noAuthFn(): Authenticator;
export declare function nkeyAuthenticator(
seed?: Uint8Array | (() => Uint8Array),
): Authenticator;
export declare function jwtAuthenticator(
ajwt: string | (() => string),
seed?: Uint8Array | (() => Uint8Array),
): Authenticator;
export declare function credsAuthenticator(creds: Uint8Array): Authenticator;
export declare enum ErrorCode {
ApiError = "BAD API",
BadAuthentication = "BAD_AUTHENTICATION",
BadCreds = "BAD_CREDS",
BadHeader = "BAD_HEADER",
BadJson = "BAD_JSON",
BadPayload = "BAD_PAYLOAD",
BadSubject = "BAD_SUBJECT",
Cancelled = "CANCELLED",
ConnectionClosed = "CONNECTION_CLOSED",
ConnectionDraining = "CONNECTION_DRAINING",
ConnectionRefused = "CONNECTION_REFUSED",
ConnectionTimeout = "CONNECTION_TIMEOUT",
Disconnect = "DISCONNECT",
InvalidOption = "INVALID_OPTION",
InvalidPayload = "INVALID_PAYLOAD",
MaxPayloadExceeded = "MAX_PAYLOAD_EXCEEDED",
NoResponders = "503",
NotFunction = "NOT_FUNC",
RequestError = "REQUEST_ERROR",
ServerOptionNotAvailable = "SERVER_OPT_NA",
SubClosed = "SUB_CLOSED",
SubDraining = "SUB_DRAINING",
Timeout = "TIMEOUT",
Tls = "TLS",
Unknown = "UNKNOWN_ERROR",
WssRequired = "WSS_REQUIRED",
JetStreamInvalidAck = "JESTREAM_INVALID_ACK",
JetStream404NoMessages = "404",
JetStream408RequestTimeout = "408",
JetStream409MaxAckPendingExceeded = "409",
JetStreamNotEnabled = "503",
AuthorizationViolation = "AUTHORIZATION_VIOLATION",
AuthenticationExpired = "AUTHENTICATION_EXPIRED",
ProtocolError = "NATS_PROTOCOL_ERR",
PermissionsViolation = "PERMISSIONS_VIOLATION",
}
export declare interface NatsError extends Error {
name: string;
message: string;
code: string;
chainedError?: Error;
}
export interface Stats {
inBytes: number;
outBytes: number;
inMsgs: number;
outMsgs: number;
}
export interface Codec<T> {
encode(d: T): Uint8Array;
decode(a: Uint8Array): T;
}
export declare function StringCodec(): Codec<string>;
export declare function JSONCodec<T = unknown>(): Codec<T>;
export interface JetStreamOptions {
apiPrefix?: string;
timeout?: number;
domain?: string;
}
export interface JetStreamManager {
consumers: ConsumerAPI;
streams: StreamAPI;
getAccountInfo(): Promise<JetStreamAccountStats>;
advisories(): AsyncIterable<Advisory>;
}
export interface PullOptions {
batch: number;
"no_wait": boolean;
expires: number;
}
export interface PubAck {
stream: string;
domain?: string;
seq: number;
duplicate: boolean;
ack(): void;
}
export interface JetStreamPublishOptions {
msgID: string;
timeout: number;
ackWait: Nanos;
headers: MsgHdrs;
expect: Partial<{
lastMsgID: string;
streamName: string;
lastSequence: number;
lastSubjectSequence: number;
}>;
}
export interface ConsumerInfoable {
consumerInfo(): Promise<ConsumerInfo>;
}
export interface Closed {
closed: Promise<void>;
}
export declare type JetStreamSubscription = Sub<JsMsg> & Destroyable & Closed & ConsumerInfoable;
export declare type JetStreamSubscriptionOptions = TypedSubscriptionOptions<JsMsg>;
export interface Pullable {
pull(opts?: Partial<PullOptions>): void;
}
export interface Destroyable {
destroy(): Promise<void>;
}
export interface Dispatcher<T> {
push(v: T): void;
}
export interface QueuedIterator<T> extends Dispatcher<T> {
[Symbol.asyncIterator](): AsyncIterator<T>;
stop(err?: Error): void;
getProcessed(): number;
getPending(): number;
getReceived(): number;
}
export declare type JetStreamPullSubscription = JetStreamSubscription & Pullable;
export declare type JsMsgCallback = (err: NatsError | null, msg: JsMsg | null) => void;
export interface JetStreamClient {
publish(subj: string, data?: Uint8Array, options?: Partial<JetStreamPublishOptions>): Promise<PubAck>;
pull(stream: string, durable: string): Promise<JsMsg>;
fetch(stream: string, durable: string, opts?: Partial<PullOptions>): QueuedIterator<JsMsg>;
pullSubscribe(subject: string, opts: ConsumerOptsBuilder | Partial<ConsumerOpts>): Promise<JetStreamPullSubscription>;
subscribe(subject: string, opts: ConsumerOptsBuilder | Partial<ConsumerOpts>): Promise<JetStreamSubscription>;
}
export interface ConsumerOpts {
config: Partial<ConsumerConfig>;
mack: boolean;
stream: string;
callbackFn?: JsMsgCallback;
name?: string;
max?: number;
queue?: string;
debug?: boolean;
}
export declare function consumerOpts(opts?: Partial<ConsumerConfig>): ConsumerOptsBuilder;
export interface ConsumerOptsBuilder {
deliverTo(subject: string): void;
manualAck(): void;
durable(name: string): void;
deliverAll(): void;
deliverLast(): void;
deliverLastPerSubject(): void;
deliverNew(): void;
startSequence(seq: number): void;
startTime(time: Date | Nanos): void;
ackNone(): void;
ackAll(): void;
ackExplicit(): void;
maxDeliver(max: number): void;
maxAckPending(max: number): void;
maxWaiting(max: number): void;
maxMessages(max: number): void;
queue(n: string): void;
callback(fn: JsMsgCallback): void;
idleHeartbeat(millis: number): void;
flowControl(): void;
}
export interface Lister<T> {
next(): Promise<T[]>;
}
export interface ConsumerAPI {
info(stream: string, consumer: string): Promise<ConsumerInfo>;
add(stream: string, cfg: Partial<ConsumerConfig>): Promise<ConsumerInfo>;
delete(stream: string, consumer: string): Promise<boolean>;
list(stream: string): Lister<ConsumerInfo>;
}
export declare type StreamInfoRequestOptions = {
"deleted_details": boolean;
};
export interface StreamAPI {
info(stream: string, opts?: StreamInfoRequestOptions): Promise<StreamInfo>;
add(cfg: Partial<StreamConfig>): Promise<StreamInfo>;
update(cfg: StreamConfig): Promise<StreamInfo>;
purge(stream: string, opts?: PurgeOpts): Promise<PurgeResponse>;
delete(stream: string): Promise<boolean>;
list(): Lister<StreamInfo>;
deleteMessage(stream: string, seq: number, erase?: boolean): Promise<boolean>;
getMessage(stream: string, query: MsgRequest): Promise<StoredMsg>;
find(subject: string): Promise<string>;
}
export interface JsMsg {
redelivered: boolean;
info: DeliveryInfo;
seq: number;
headers: MsgHdrs | undefined;
data: Uint8Array;
subject: string;
sid: number;
ack(): void;
nak(): void;
working(): void;
term(): void;
ackAck(): Promise<boolean>;
}
export interface DeliveryInfo {
domain: string;
account_hash?: string;
stream: string;
consumer: string;
redeliveryCount: number;
streamSequence: number;
deliverySequence: number;
timestampNanos: number;
pending: number;
redelivered: boolean;
}
export interface StoredMsg {
subject: string;
seq: number;
header: MsgHdrs;
data: Uint8Array;
time: Date;
}
export interface Advisory {
kind: AdvisoryKind;
data: unknown;
}
export declare enum AdvisoryKind {
API = "api_audit",
StreamAction = "stream_action",
ConsumerAction = "consumer_action",
SnapshotCreate = "snapshot_create",
SnapshotComplete = "snapshot_complete",
RestoreCreate = "restore_create",
RestoreComplete = "restore_complete",
MaxDeliver = "max_deliver",
Terminated = "terminated",
Ack = "consumer_ack",
StreamLeaderElected = "stream_leader_elected",
StreamQuorumLost = "stream_quorum_lost",
ConsumerLeaderElected = "consumer_leader_elected",
ConsumerQuorumLost = "consumer_quorum_lost"
}
export declare type Nanos = number;
export interface ApiError {
code: number;
description: string;
}
export interface ApiResponse {
type: string;
error?: ApiError;
}
export interface ApiPaged {
total: number;
offset: number;
limit: number;
}
export interface ApiPagedRequest {
offset: number;
}
export interface StreamInfo {
config: StreamConfig;
created: number;
state: StreamState;
cluster?: ClusterInfo;
mirror?: StreamSourceInfo;
sources?: StreamSourceInfo[];
}
export interface StreamConfig {
name: string;
subjects?: string[];
retention: RetentionPolicy;
"max_consumers": number;
"max_msgs": number;
"max_bytes": number;
discard?: DiscardPolicy;
"max_age": Nanos;
"max_msg_size"?: number;
storage: StorageType;
"num_replicas": number;
"no_ack"?: boolean;
"template_owner"?: string;
"duplicate_window"?: Nanos;
placement?: Placement;
mirror?: StreamSource;
sources?: StreamSource[];
"max_msgs_per_subject"?: number;
}
export interface StreamSource {
name: string;
"opt_start_seq"?: number;
"opt_start_time"?: string;
"filter_subject"?: string;
}
export interface Placement {
cluster: string;
tags: string[];
}
export declare enum RetentionPolicy {
Limits = "limits",
Interest = "interest",
Workqueue = "workqueue"
}
export declare enum DiscardPolicy {
Old = "old",
New = "new"
}
export declare enum StorageType {
File = "file",
Memory = "memory"
}
export declare enum DeliverPolicy {
All = "all",
Last = "last",
New = "new",
StartSequence = "by_start_sequence",
StartTime = "by_start_time",
LastPerSubject = "last_per_subject"
}
export declare enum AckPolicy {
None = "none",
All = "all",
Explicit = "explicit",
NotSet = ""
}
export declare enum ReplayPolicy {
Instant = "instant",
Original = "original"
}
export interface StreamState {
messages: number;
bytes: number;
"first_seq": number;
"first_ts": number;
"last_seq": number;
"last_ts": string;
"num_deleted": number;
deleted: number[];
lost: LostStreamData;
"consumer_count": number;
}
export interface LostStreamData {
msgs: number;
bytes: number;
}
export interface ClusterInfo {
name?: string;
leader?: string;
replicas?: PeerInfo[];
}
export interface PeerInfo {
name: string;
current: boolean;
offline: boolean;
active: Nanos;
lag: number;
}
export interface StreamSourceInfo {
name: string;
lag: number;
active: Nanos;
error?: ApiError;
}
export declare type PurgeOpts = PurgeBySeq | PurgeTrimOpts | PurgeBySubject;
export declare type PurgeBySeq = {
filter?: string;
seq: number;
};
export declare type PurgeTrimOpts = {
filter?: string;
keep: number;
};
export declare type PurgeBySubject = {
filter: string;
};
export interface PurgeResponse extends Success {
purged: number;
}
export interface CreateConsumerRequest {
"stream_name": string;
config: Partial<ConsumerConfig>;
}
export interface StreamMsgResponse extends ApiResponse {
message: {
subject: string;
seq: number;
data: string;
hdrs: string;
time: string;
};
}
export interface SequenceInfo {
"consumer_seq": number;
"stream_seq": number;
"last_active": Nanos;
}
export interface ConsumerInfo {
"stream_name": string;
name: string;
created: number;
config: ConsumerConfig;
delivered: SequenceInfo;
"ack_floor": SequenceInfo;
"num_ack_pending": number;
"num_redelivered": number;
"num_waiting": number;
"num_pending": number;
cluster?: ClusterInfo;
}
export interface ConsumerListResponse extends ApiResponse, ApiPaged {
consumers: ConsumerInfo[];
}
export interface StreamListResponse extends ApiResponse, ApiPaged {
streams: StreamInfo[];
}
export interface Success {
success: boolean;
}
export declare type SuccessResponse = ApiResponse & Success;
export interface LastForMsgRequest {
"last_by_subj": string;
}
export interface SeqMsgRequest {
seq: number;
}
export declare type MsgRequest = SeqMsgRequest | LastForMsgRequest | number;
export interface MsgDeleteRequest extends SeqMsgRequest {
"no_erase"?: boolean;
}
export interface JetStreamAccountStats {
memory: number;
storage: number;
streams: number;
consumers: number;
api: JetStreamApiStats;
limits: AccountLimits;
domain?: string;
}
export interface JetStreamApiStats {
total: number;
errors: number;
}
export interface AccountInfoResponse extends ApiResponse, JetStreamAccountStats {
}
export interface AccountLimits {
"max_memory": number;
"max_storage": number;
"max_streams": number;
"max_consumers": number;
}
export interface ConsumerConfig {
name: string;
"durable_name"?: string;
"deliver_subject"?: string;
"deliver_group"?: string;
"deliver_policy": DeliverPolicy;
"opt_start_seq"?: number;
"opt_start_time"?: string;
"ack_policy": AckPolicy;
"ack_wait"?: Nanos;
"max_deliver"?: number;
"filter_subject"?: string;
"replay_policy": ReplayPolicy;
"rate_limit_bps"?: number;
"sample_freq"?: string;
"max_waiting"?: number;
"max_ack_pending"?: number;
"idle_heartbeat"?: Nanos;
"flow_control"?: boolean;
description?: string;
}
export interface Consumer {
"stream_name": string;
config: ConsumerConfig;
}
export interface StreamNames {
streams: string[];
}
export interface StreamNameBySubject {
subject: string;
}
export interface NextRequest {
expires: number;
batch: number;
"no_wait": boolean;
}
export declare enum JsHeaders {
StreamSourceHdr = "Nats-Stream-Source",
LastConsumerSeqHdr = "Nats-Last-Consumer",
LastStreamSeqHdr = "Nats-Last-Stream"
}
export declare type MsgAdapter<T> = (
err: NatsError | null,
msg: Msg,
) => [NatsError | null, T | null];
/**
* Callback presented to the user with the converted type
*/
export declare type TypedCallback<T> = (
err: NatsError | null,
msg: T | null,
) => void;
export interface TypedSubscriptionOptions<T> extends SubOpts<T> {
adapter: MsgAdapter<T>;
callback?: TypedCallback<T>;
dispatchedFn?: DispatchedFn<T>;
cleanupFn?: (sub: Subscription, info?: unknown) => void;
}
export declare type DispatchedFn<T> = (data: T | null) => void;
export declare function defaultConsumer(name: string, opts?: Partial<ConsumerConfig>): ConsumerConfig;
export declare function nanos(millis: number): Nanos;
export declare function millis(ns: Nanos): number;
export declare function isFlowControlMsg(msg: Msg): boolean;
export declare function isHeartbeatMsg(msg: Msg): boolean; | the_stack |
import * as React from "react";
import { Logger, LogLevel } from "@pnp/logging";
import isEqual from "lodash/isEqual";
import cloneDeep from "lodash/cloneDeep";
import find from "lodash/find";
import pull from "lodash/pull";
import remove from "lodash/remove";
import findIndex from "lodash/findIndex";
import { MessageBar, MessageBarType, Link } from "office-ui-fabric-react";
import { params } from "../../common/services/Parameters";
import * as strings from "M365LPStrings";
import styles from "../../common/CustomLearningCommon.module.scss";
import { ICacheConfig, IPlaylist, IAsset, ITechnology, ICategory, ICustomizations, ICDN, IMetadataEntry } from "../../common/models/Models";
import { AdminNavigationType, ShimmerView } from "../../common/models/Enums";
import Category from "./Templates/Category";
import Technology from "./Templates/Technology";
import AdminMenu from "./Organizms/AdminMenu";
import ShimmerViewer from "../../common/components/Atoms/ShimmerViewer";
import { reject } from "lodash";
export interface ICustomLearningAdminProps {
validConfig: boolean;
currentWebpart: string;
cacheConfig: ICacheConfig;
customization: ICustomizations;
categoriesAll: ICategory[];
technologiesAll: ITechnology[];
playlistsAll: IPlaylist[];
assetsAll: IAsset[];
levels: IMetadataEntry[];
audiences: IMetadataEntry[];
siteUrl: string;
firstConfig: boolean;
saveConfig: (newConfig: ICacheConfig) => Promise<void>;
upsertCustomizations: (newSubCategories: ICustomizations) => Promise<void>;
upsertPlaylist: (playlist: IPlaylist) => Promise<string>;
deletePlaylist: (playlistId: string) => Promise<void>;
copyPlaylist: (playlist: IPlaylist) => Promise<string>;
upsertAsset: (asset: IAsset) => Promise<string>;
upsertCdn: (cdn: ICDN) => Promise<boolean>;
selectCDN: (cdnId: string) => Promise<boolean>;
removeCdn: (cdnId: string) => Promise<boolean>;
translatePlaylist: (playlist: IPlaylist) => IPlaylist;
translateAsset: (asset: IAsset) => IAsset;
}
export interface ICustomLearningAdminState {
currentCDNId: string;
tabSelected: string;
loadingCdn: boolean;
working: boolean;
}
export class CustomLearningAdminState implements ICustomLearningAdminState {
constructor(
public currentCDNId: string = "Default",
public tabSelected: string = AdminNavigationType.Category,
public loadingCdn: boolean = false,
public working: boolean = false
) { }
}
export default class CustomLearningAdmin extends React.Component<ICustomLearningAdminProps, ICustomLearningAdminState> {
private LOG_SOURCE: string = "CustomLearningAdmin";
private _currentVersion: string;
constructor(props: ICustomLearningAdminProps) {
super(props);
this._currentVersion = (params.latestWebPartVersion) ? params.latestWebPartVersion : "4.0.0";
this.state = new CustomLearningAdminState();
}
public shouldComponentUpdate(nextProps: Readonly<ICustomLearningAdminProps>, nextState: Readonly<ICustomLearningAdminState>) {
if ((isEqual(nextState, this.state) && isEqual(nextProps, this.props)))
return false;
return true;
}
private selectTab = (tab: string): void => {
if (tab != this.state.tabSelected) {
this.setState({
tabSelected: tab
});
}
}
private updateTechnologyVisibility = (techName: string, subTech: string, exists: boolean): void => {
try {
let hiddenTechnology: string[] = cloneDeep(this.props.customization.HiddenTechnology);
let hiddenSubject: string[] = cloneDeep(this.props.customization.HiddenSubject);
if (exists) {
//Add to hidden list
if (!subTech || subTech.length < 1) {
hiddenTechnology.push(techName);
} else {
hiddenSubject.push(subTech);
}
} else {
//Remove from hidden list
if (!subTech || subTech.length < 1) {
pull(hiddenTechnology, techName);
} else {
pull(hiddenSubject, subTech);
}
}
//Save cacheConfig Changes
let newConfig = cloneDeep(this.props.customization);
newConfig.HiddenTechnology = hiddenTechnology;
newConfig.HiddenSubject = hiddenSubject;
this.setState({ working: true });
this.props.upsertCustomizations(newConfig).then(() => { this.setState({ working: false }); });
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (updateTechnologyVisibility) - ${err}`, LogLevel.Error);
}
}
private updateSubCategoryVisibility = (subCategory: string, exists: boolean): void => {
try {
let hiddenSubCategory: string[] = cloneDeep(this.props.customization.HiddenSubCategories);
if (exists) {
//Add to hidden list
hiddenSubCategory.push(subCategory);
} else {
//Remove from hidden list
pull(hiddenSubCategory, subCategory);
}
//Save cacheConfig Changes
let newConfig = cloneDeep(this.props.customization);
newConfig.HiddenSubCategories = hiddenSubCategory;
this.setState({ working: true });
this.props.upsertCustomizations(newConfig).then(() => { this.setState({ working: false }); });
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (updateSubCategoryVisibility) - ${err}`, LogLevel.Error);
}
}
private updatePlaylistVisibility = (playlistId: string, exists: boolean): void => {
try {
let hiddenPlaylistsIds: string[] = cloneDeep(this.props.customization.HiddenPlaylistsIds);
if (exists) {
//Add to hidden list
hiddenPlaylistsIds.push(playlistId);
} else {
//Remove from hidden list
pull(hiddenPlaylistsIds, playlistId);
}
//Save cacheConfig Changes
let newConfig = cloneDeep(this.props.customization);
newConfig.HiddenPlaylistsIds = hiddenPlaylistsIds;
this.setState({ working: true });
this.props.upsertCustomizations(newConfig).then(() => { this.setState({ working: false }); });
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (updatePlaylistVisibility) - ${err}`, LogLevel.Error);
}
}
private upsertSubCategory = (categoryId: string, heading: ICategory): void => {
try {
let customization = cloneDeep(this.props.customization);
if (!customization.CustomSubcategories || customization.CustomSubcategories.length < 1) {
customization.CustomSubcategories = [];
for (let i = 0; i < this.props.cacheConfig.Categories.length; i++) {
let category = cloneDeep(this.props.cacheConfig.Categories[i]);
category.SubCategories = [];
customization.CustomSubcategories.push(category);
}
}
let foundCategory = find(customization.CustomSubcategories, { Id: categoryId });
let subCategoryIndex = findIndex(foundCategory.SubCategories, { Id: heading.Id });
if (subCategoryIndex > -1) {
foundCategory.SubCategories[subCategoryIndex] = heading;
} else {
foundCategory.SubCategories.push(heading);
}
this.setState({ working: true });
this.props.upsertCustomizations(customization).then(() => { this.setState({ working: false }); });
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (upsertSubCategory) - ${err}`, LogLevel.Error);
}
}
private deleteSubCategory = (categoryId: string, subCategoryId: string): void => {
try {
let customization = cloneDeep(this.props.customization);
let foundCategory = find(customization.CustomSubcategories, { Id: categoryId });
remove(foundCategory.SubCategories, { Id: subCategoryId });
this.setState({ working: true });
this.props.upsertCustomizations(customization).then(() => { this.setState({ working: false }); });
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (deleteSubCategory) - ${err}`, LogLevel.Error);
}
}
private getContainer(className: string): any {
let element: any;
try {
switch (this.state.tabSelected) {
case AdminNavigationType.Category:
element = <Category
className={className}
customization={this.props.customization}
technologies={this.props.technologiesAll}
categories={this.props.categoriesAll}
playlists={this.props.playlistsAll}
assets={this.props.assetsAll}
levels={this.props.levels}
audiences={this.props.audiences}
updatePlaylistVisibility={this.updatePlaylistVisibility}
upsertSubCategory={this.upsertSubCategory}
upsertPlaylist={this.props.upsertPlaylist}
upsertAsset={this.props.upsertAsset}
deletePlaylist={this.props.deletePlaylist}
updateSubcategory={this.updateSubCategoryVisibility}
deleteSubcategory={this.deleteSubCategory}
copyPlaylist={this.props.copyPlaylist}
translatePlaylist={this.props.translatePlaylist}
translateAsset={this.props.translateAsset}
/>;
break;
default:
element = <Technology
className={className}
technologies={this.props.technologiesAll}
hiddenTech={this.props.customization.HiddenTechnology}
hiddenSub={this.props.customization.HiddenSubject}
updateTechnology={this.updateTechnologyVisibility}
/>;
}
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (getContainer) - ${err}`, LogLevel.Error);
}
return element;
}
private selectCDN = (cdnId: string): Promise<boolean> => {
return new Promise((response) => {
try {
this.setState({
loadingCdn: true
},
async () => {
let retVal = await this.props.selectCDN(cdnId);
this.setState({
currentCDNId: cdnId,
loadingCdn: false
}, () => {
response(retVal);
});
});
} catch (err) {
response(false);
}
});
}
private upsertCdn = async (cdn: ICDN): Promise<boolean> => {
let retVal: boolean = false;
try {
let upsertCdnResult = await this.props.upsertCdn(cdn);
if (upsertCdnResult) {
retVal = true;
}
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (upsertCdn) - ${err}`, LogLevel.Error);
}
return retVal;
}
public render(): React.ReactElement<ICustomLearningAdminProps> {
try {
let notice = `${strings.AdminVersionUpdateNotice}`;
notice = notice.replace('%0%', this.props.currentWebpart).replace('%1%', this._currentVersion);
let showMultilingualMsg: boolean = (this.props.firstConfig && params.multilingualEnabled && params.configuredLanguages.length > 1);
let showUpgradeMsg: boolean = (this.props.cacheConfig && (this.props.currentWebpart < this._currentVersion));
let className: string = (showMultilingualMsg || showUpgradeMsg) ? "" : "nomsg";
return (
<div data-component={this.LOG_SOURCE} className={`${styles.customLearning} ${(params.appPartPage) ? styles.appPartPage : ""}`}>
<AdminMenu
loadingCdn={this.state.loadingCdn}
placeholderUrl={`${params.baseCdnPath}${params.defaultLanguage}/images/categories/customfeatured.png`}
currentCDNId={this.state.currentCDNId}
selectCDN={this.selectCDN}
selectTab={this.selectTab}
upsertCdn={this.upsertCdn}
removeCdn={this.props.removeCdn}
working={this.state.working}
/>
<div className="adm-header-message">
{showMultilingualMsg &&
<MessageBar
messageBarType={MessageBarType.warning}
isMultiline={true}
dismissButtonAriaLabel={strings.CloseButton}
>
{strings.DataUpgradeMultilingual}
<Link
href={`${this.props.siteUrl}/_layouts/15/muisetng.aspx`}
target="_blank">
{strings.DataUpgradeReview}
</Link>
</MessageBar>
}
{showUpgradeMsg &&
<MessageBar>
{notice}
<Link
href={(params.updateInstructionUrl) ? params.updateInstructionUrl : "https://github.com/pnp/custom-learning-office-365#updating-the-solution"}
target="_blank">
{strings.AdminVersionUpdateInstructions}
</Link>
</MessageBar>
}
</div>
{
this.props.validConfig && this.props.cacheConfig && !this.state.loadingCdn &&
this.getContainer(className)
}
{
!this.props.validConfig && !this.props.cacheConfig && !this.state.loadingCdn &&
<MessageBar messageBarType={MessageBarType.error} className="adm-content">
{strings.AdminConfigIssueMessage}
</MessageBar>
}
{
this.state.loadingCdn &&
<ShimmerViewer shimmerView={ShimmerView.AdminCdn} />
}
</div >
);
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (render) - ${err}`, LogLevel.Error);
return null;
}
}
} | the_stack |
import type { QueryFunctionOptions } from '@apollo/client/react';
import type { TApplicationContext } from '@commercetools-frontend/application-shell-connectors';
import type {
ApplicationWindow,
ApplicationMenuLinksForDevelopmentConfig,
TLocalizedField,
} from '@commercetools-frontend/constants';
import type {
TNavbarMenu,
TFetchApplicationsMenuQuery,
TFetchApplicationsMenuQueryVariables,
} from '../../types/generated/proxy';
import { useEffect } from 'react';
import { useApolloClient } from '@apollo/client';
import { useApplicationContext } from '@commercetools-frontend/application-shell-connectors';
import { useMcLazyQuery } from '../../hooks/apollo-hooks';
import FetchApplicationsMenu from './fetch-applications-menu.proxy.graphql';
const supportedLocales = ['en', 'de', 'es', 'fr-FR', 'zh-CN', 'ja'];
export type MenuKey = 'appBar' | 'navBar';
export type MenuLoaderResult<Key extends MenuKey> = Key extends 'appBar'
? TFetchApplicationsMenuQuery['applicationsMenu']['appBar']
: Key extends 'navBar'
? TFetchApplicationsMenuQuery['applicationsMenu']['navBar']
: never;
export type Config<Key extends MenuKey> = {
environment: TApplicationContext<{}>['environment'];
queryOptions?: {
onError?: QueryFunctionOptions['onError'];
};
/**
* @deprecated The `menu.json` file has been deprecated in favor of defining the menu links
* in the custom application config file.
*/
loadMenuConfig?: () => Promise<MenuLoaderResult<Key>>;
};
const defaultApiUrl = window.location.origin;
const mapLabelAllLocalesWithDefaults = (
labelAllLocales: TLocalizedField[],
defaultLabel?: string
): Array<{ __typename: 'LocalizedField' } & TLocalizedField> => {
let mappedLabelAllLocales = labelAllLocales;
if (defaultLabel) {
// Map all supported locales with the given localized labels.
// If a locale is not defined in the config, we use the `default` label as the value.
// This is only needed for development as we're trying to map two different schemas.
mappedLabelAllLocales = supportedLocales.map((supportedLocale) => {
const existingField = labelAllLocales.find(
(field) => field.locale === supportedLocale
);
if (existingField) return existingField;
return {
locale: supportedLocale,
value: defaultLabel,
};
});
}
// Add the `__typename`.
return mappedLabelAllLocales.map((field) => ({
__typename: 'LocalizedField',
...field,
}));
};
/**
* Transform menu links defined in the `custom-application-config.json` to the `FetchApplicationsMenu` schema.
* This is only needed for development.
*/
const mapApplicationMenuConfigToGraqhQLQueryResult = (
applicationConfig: ApplicationWindow['app']
): TFetchApplicationsMenuQuery => {
const entryPointUriPath = applicationConfig.entryPointUriPath;
const menuLinks = applicationConfig.__DEVELOPMENT__?.menuLinks;
// @ts-expect-error: the `accountLinks` is not explicitly typed as it's only used by the account app.
const accountLinks = (applicationConfig.__DEVELOPMENT__?.accountLinks! ??
[]) as ApplicationMenuLinksForDevelopmentConfig['submenuLinks'];
return {
applicationsMenu: {
__typename: 'ApplicationsMenu',
navBar: menuLinks
? [
{
__typename: 'NavbarMenu',
shouldRenderDivider: false,
key: entryPointUriPath,
uriPath: entryPointUriPath,
icon: menuLinks.icon,
labelAllLocales: mapLabelAllLocalesWithDefaults(
menuLinks.labelAllLocales,
menuLinks.defaultLabel
),
permissions: menuLinks.permissions,
// @ts-ignore: not defined in schema, as it's only used internally.
featureToggle: menuLinks.featureToggle ?? null,
// @ts-ignore: not defined in schema, as it's only used internally.
menuVisibility: menuLinks.menuVisibility ?? null,
// @ts-ignore: not defined in schema, as it's only used internally.
actionRights: menuLinks.actionRights ?? null,
// @ts-ignore: not defined in schema, as it's only used internally.
dataFences: menuLinks.dataFences ?? null,
submenu: menuLinks.submenuLinks.map((submenuLink) => ({
__typename: 'BaseMenu',
key: `${entryPointUriPath}-${submenuLink.uriPath}`,
// The `uriPath` of each submenu link is supposed to be defined relative
// to the entry point URI path.
// However, when rendering the link, we need to provide the full uri path.
// Special case when the value is `/`: it means that the link is supposed to be
// treated the same as the entry point uri path. In this case, the return value
// should not contain any unnecessary trailing slash and therefore we return the
// main value `entryPointUriPath`.
uriPath:
submenuLink.uriPath === '/'
? entryPointUriPath
: `${entryPointUriPath}/${submenuLink.uriPath}`,
labelAllLocales: mapLabelAllLocalesWithDefaults(
submenuLink.labelAllLocales,
submenuLink.defaultLabel
),
permissions: submenuLink.permissions,
// @ts-ignore: not defined in schema, as it's only used internally.
featureToggle: submenuLink.featureToggle ?? null,
// @ts-ignore: not defined in schema, as it's only used internally.
menuVisibility: submenuLink.menuVisibility ?? null,
// @ts-ignore: not defined in schema, as it's only used internally.
actionRights: submenuLink.actionRights ?? null,
// @ts-ignore: not defined in schema, as it's only used internally.
dataFences: submenuLink.dataFences ?? null,
})),
},
]
: [],
appBar: accountLinks.map((menuLink) => ({
__typename: 'BaseMenu',
key: menuLink.uriPath,
uriPath: menuLink.uriPath,
labelAllLocales: mapLabelAllLocalesWithDefaults(
menuLink.labelAllLocales,
menuLink.defaultLabel
),
permissions: menuLink.permissions,
// @ts-ignore: not defined in schema, as it's only used internally.
featureToggle: menuLink.featureToggle ?? null,
})),
},
};
};
/**
* Transform menu links defined in the `menu.json` to the `FetchApplicationsMenu` schema.
* This is only needed for development.
* @deprecated The `menu.json` file has been deprecated in favor of defining the menu links
* in the custom application config file.
*/
const mapLegacyMenuJsonToGraphQLQueryResult = <Key extends MenuKey>(
menuKey: Key,
menuJson: MenuLoaderResult<Key>
): TFetchApplicationsMenuQuery => {
return {
applicationsMenu: {
__typename: 'ApplicationsMenu',
// @ts-ignore: to suppress `featureToggle` error.
navBar:
menuKey === 'navBar'
? menuJson.map((data) => {
const menuLink = data as TNavbarMenu;
return {
__typename: 'NavbarMenu',
shouldRenderDivider: false,
key: menuLink.uriPath,
uriPath: menuLink.uriPath,
icon: menuLink.icon,
labelAllLocales: mapLabelAllLocalesWithDefaults(
menuLink.labelAllLocales,
// There is no `defaultValue`, so we pick the first in the list.
menuLink.labelAllLocales[0].value
),
permissions: menuLink.permissions,
// @ts-ignore: not defined in schema, as it's only used internally.
featureToggle: menuLink.featureToggle ?? null,
// @ts-ignore: not defined in schema, as it's only used internally.
menuVisibility: menuLink.menuVisibility ?? null,
// @ts-ignore: not defined in schema, as it's only used internally.
actionRights: menuLink.actionRights ?? null,
// @ts-ignore: not defined in schema, as it's only used internally.
dataFences: menuLink.dataFences ?? null,
submenu: menuLink.submenu.map((submenuLink) => ({
__typename: 'BaseMenu',
key: `${menuLink.uriPath}-${submenuLink.uriPath}`,
uriPath: submenuLink.uriPath,
labelAllLocales: mapLabelAllLocalesWithDefaults(
submenuLink.labelAllLocales
),
permissions: submenuLink.permissions,
// @ts-ignore: not defined in schema, as it's only used internally.
featureToggle: submenuLink.featureToggle ?? null,
// @ts-ignore: not defined in schema, as it's only used internally.
menuVisibility: submenuLink.menuVisibility ?? null,
// @ts-ignore: not defined in schema, as it's only used internally.
actionRights: submenuLink.actionRights ?? null,
// @ts-ignore: not defined in schema, as it's only used internally.
dataFences: submenuLink.dataFences ?? null,
})),
};
})
: [],
// @ts-ignore: to suppress `featureToggle` error.
appBar:
menuKey === 'appBar'
? menuJson.map((menuLink) => ({
__typename: 'BaseMenu',
key: menuLink.uriPath,
uriPath: menuLink.uriPath,
labelAllLocales: mapLabelAllLocalesWithDefaults(
menuLink.labelAllLocales
),
permissions: menuLink.permissions,
// @ts-ignore: not defined in schema, as it's only used internally.
featureToggle: menuLink.featureToggle ?? null,
}))
: [],
},
};
};
function useApplicationsMenu<Key extends MenuKey>(
menuKey: Key,
config: Config<Key>
): MenuLoaderResult<Key> | undefined {
const apolloClient = useApolloClient();
const mcProxyApiUrl = useApplicationContext(
(context) => context.environment.mcProxyApiUrl
);
// Fetch all menu links from the GraphQL API in the Merchant Center Proxy.
// For local development, we don't fetch data from the remote server but use
// only the configuration for the menu links defined for the application.
// To do so, we manually write the data in the Apollo cache and use the
// `fetchPolicy: cache-only` to instruct Apollo to read the data from the cache.
// NOTE: we lazily execute the query to ensure that (for development) we can
// write the data into the cache BEFORE the query attempts to read from it.
// If not, Apollo throws an error like `Can't find field 'applicationMenu' on ROOT_QUERY object`.
const [executeQuery, { data: menuQueryResult, called }] = useMcLazyQuery<
TFetchApplicationsMenuQuery,
TFetchApplicationsMenuQueryVariables
>(FetchApplicationsMenu, {
onError: config.queryOptions?.onError,
fetchPolicy: config.environment.servedByProxy
? 'cache-first'
: 'cache-only',
context: {
// Allow to overwrite the API url from application config
uri: `${mcProxyApiUrl || defaultApiUrl}/api/graphql`,
skipGraphQlTargetCheck: true,
},
});
// For development, we read the menu data from the configuration file and
// write it into the Apollo cache.
useEffect(() => {
if (
config.environment.__DEVELOPMENT__ &&
(config.environment.__DEVELOPMENT__.menuLinks ||
// @ts-expect-error: the `accountLinks` is not explicitly typed as it's only used by the account app.
config.environment.__DEVELOPMENT__.accountLinks)
) {
const applicationMenu = mapApplicationMenuConfigToGraqhQLQueryResult(
config.environment
);
apolloClient.writeQuery({
query: FetchApplicationsMenu,
data: applicationMenu,
});
} else if (!config.environment.servedByProxy && config.loadMenuConfig) {
config.loadMenuConfig().then((menuConfig) => {
const menuJson = Array.isArray(menuConfig) ? menuConfig : [menuConfig];
const applicationMenu = mapLegacyMenuJsonToGraphQLQueryResult<MenuKey>(
menuKey,
menuJson
);
apolloClient.writeQuery({
query: FetchApplicationsMenu,
data: applicationMenu,
});
});
}
if (!called) {
executeQuery();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // Make sure to run this effect only once, otherwise we might end up in an infinite loop!
if (menuQueryResult && menuQueryResult.applicationsMenu) {
return menuQueryResult.applicationsMenu[menuKey] as MenuLoaderResult<Key>;
}
return;
}
export default useApplicationsMenu; | the_stack |
import { assert } from './util';
import { App } from '../components/app/app';
import { DomCallback, DomController } from '../platform/dom-controller';
import { EventListenerOptions, Platform } from '../platform/platform';
import { pointerCoord } from './dom';
export class ScrollView {
ev: ScrollEvent;
isScrolling = false;
onScrollStart: (ev: ScrollEvent) => void;
onScroll: (ev: ScrollEvent) => void;
onScrollEnd: (ev: ScrollEvent) => void;
initialized: boolean = false;
_el: HTMLElement;
private _eventsEnabled = false;
private _js: boolean;
private _t: number = 0;
private _l: number = 0;
private _lsn: Function;
private _endTmr: Function;
constructor(
private _app: App,
private _plt: Platform,
private _dom: DomController
) {
this.ev = {
timeStamp: 0,
scrollTop: 0,
scrollLeft: 0,
scrollHeight: 0,
scrollWidth: 0,
contentHeight: 0,
contentWidth: 0,
contentTop: 0,
contentBottom: 0,
startY: 0,
startX: 0,
deltaY: 0,
deltaX: 0,
velocityY: 0,
velocityX: 0,
directionY: 'down',
directionX: null,
domWrite: _dom.write.bind(_dom)
};
}
init(ele: HTMLElement, contentTop: number, contentBottom: number) {
assert(ele, 'scroll-view, element can not be null');
this._el = ele;
if (!this.initialized) {
this.initialized = true;
if (this._js) {
this.enableJsScroll(contentTop, contentBottom);
} else {
this.enableNativeScrolling();
}
}
}
enableEvents() {
this._eventsEnabled = true;
}
setScrolling(isScrolling: boolean, ev: ScrollEvent) {
if (this.isScrolling) {
if (isScrolling) {
this.onScroll && this.onScroll(ev);
} else {
this.isScrolling = false;
this.onScrollEnd && this.onScrollEnd(ev);
}
} else if (isScrolling) {
this.isScrolling = true;
this.onScrollStart && this.onScrollStart(ev);
}
}
private enableNativeScrolling() {
assert(this.onScrollStart, 'onScrollStart is not defined');
assert(this.onScroll, 'onScroll is not defined');
assert(this.onScrollEnd, 'onScrollEnd is not defined');
this._js = false;
if (!this._el) {
return;
}
console.debug(`ScrollView, enableNativeScrolling`);
const self = this;
const ev = self.ev;
const positions: number[] = [];
function scrollCallback(scrollEvent: UIEvent) {
// remind the app that it's currently scrolling
self._app.setScrolling();
// if events are disabled, we do nothing
if (!self._eventsEnabled) {
return;
}
ev.timeStamp = scrollEvent.timeStamp;
// Event.timeStamp is 0 in firefox
if (!ev.timeStamp) {
ev.timeStamp = Date.now();
}
// get the current scrollTop
// ******** DOM READ ****************
ev.scrollTop = self.getTop();
// get the current scrollLeft
// ******** DOM READ ****************
ev.scrollLeft = self.getLeft();
if (!self.isScrolling) {
// remember the start positions
ev.startY = ev.scrollTop;
ev.startX = ev.scrollLeft;
// new scroll, so do some resets
ev.velocityY = ev.velocityX = 0;
ev.deltaY = ev.deltaX = 0;
positions.length = 0;
}
// actively scrolling
positions.push(ev.scrollTop, ev.scrollLeft, ev.timeStamp);
if (positions.length > 3) {
// we've gotten at least 2 scroll events so far
ev.deltaY = (ev.scrollTop - ev.startY);
ev.deltaX = (ev.scrollLeft - ev.startX);
var endPos = (positions.length - 1);
var startPos = endPos;
var timeRange = (ev.timeStamp - 100);
// move pointer to position measured 100ms ago
for (var i = endPos; i > 0 && positions[i] > timeRange; i -= 3) {
startPos = i;
}
if (startPos !== endPos) {
// compute relative movement between these two points
var movedTop = (positions[startPos - 2] - positions[endPos - 2]);
var movedLeft = (positions[startPos - 1] - positions[endPos - 1]);
var factor = FRAME_MS / (positions[endPos] - positions[startPos]);
// based on XXms compute the movement to apply for each render step
ev.velocityY = movedTop * factor;
ev.velocityX = movedLeft * factor;
// figure out which direction we're scrolling
ev.directionY = (movedTop > 0 ? 'up' : 'down');
ev.directionX = (movedLeft > 0 ? 'left' : 'right');
}
}
function scrollEnd() {
// reset velocity, do not reset the directions or deltas
ev.velocityY = ev.velocityX = 0;
// emit that the scroll has ended
self.setScrolling(false, ev);
self._endTmr = null;
}
// emit on each scroll event
self.setScrolling(true, ev);
// debounce for a moment after the last scroll event
self._dom.cancel(self._endTmr);
self._endTmr = self._dom.read(scrollEnd, SCROLL_END_DEBOUNCE_MS);
}
// clear out any existing listeners (just to be safe)
self._lsn && self._lsn();
// assign the raw scroll listener
// note that it does not have a wrapping requestAnimationFrame on purpose
// a scroll event callback will always be right before the raf callback
// so there's little to no value of using raf here since it'll all ways immediately
// call the raf if it was set within the scroll event, so this will save us some time
self._lsn = self._plt.registerListener(self._el, 'scroll', scrollCallback, EVENT_OPTS);
}
/**
* @hidden
* JS Scrolling has been provided only as a temporary solution
* until iOS apps can take advantage of scroll events at all times.
* The goal is to eventually remove JS scrolling entirely. When we
* no longer have to worry about iOS not firing scroll events during
* inertia then this can be burned to the ground. iOS's more modern
* WKWebView does not have this issue, only UIWebView does.
*/
enableJsScroll(contentTop: number, contentBottom: number) {
const self = this;
self._js = true;
const ele = self._el;
if (!ele) {
return;
}
console.debug(`ScrollView, enableJsScroll`);
const ev = self.ev;
const positions: number[] = [];
let rafCancel: Function;
let max: number;
function setMax() {
if (!max) {
// ******** DOM READ ****************
max = ele.scrollHeight - ele.parentElement.offsetHeight + contentTop + contentBottom;
}
}
function jsScrollDecelerate(timeStamp: number) {
ev.timeStamp = timeStamp;
console.debug(`scroll-view, decelerate, velocity: ${ev.velocityY}`);
if (ev.velocityY) {
ev.velocityY *= DECELERATION_FRICTION;
// update top with updated velocity
// clamp top within scroll limits
// ******** DOM READ ****************
setMax();
self._t = Math.min(Math.max(self._t + ev.velocityY, 0), max);
ev.scrollTop = self._t;
// emit on each scroll event
self.onScroll(ev);
self._dom.write(() => {
// ******** DOM WRITE ****************
self.setTop(self._t);
if (self._t > 0 && self._t < max && Math.abs(ev.velocityY) > MIN_VELOCITY_CONTINUE_DECELERATION) {
rafCancel = self._dom.read(rafTimeStamp => {
jsScrollDecelerate(rafTimeStamp);
});
} else {
// haven't scrolled in a while, so it's a scrollend
self.isScrolling = false;
// reset velocity, do not reset the directions or deltas
ev.velocityY = ev.velocityX = 0;
// emit that the scroll has ended
self.onScrollEnd(ev);
}
});
}
}
function jsScrollTouchStart(touchEvent: TouchEvent) {
positions.length = 0;
max = null;
self._dom.cancel(rafCancel);
positions.push(pointerCoord(touchEvent).y, touchEvent.timeStamp);
}
function jsScrollTouchMove(touchEvent: TouchEvent) {
if (!positions.length) {
return;
}
ev.timeStamp = touchEvent.timeStamp;
var y = pointerCoord(touchEvent).y;
// ******** DOM READ ****************
setMax();
self._t -= (y - positions[positions.length - 2]);
self._t = Math.min(Math.max(self._t, 0), max);
positions.push(y, ev.timeStamp);
if (!self.isScrolling) {
// remember the start position
ev.startY = self._t;
// new scroll, so do some resets
ev.velocityY = ev.deltaY = 0;
self.isScrolling = true;
// emit only on the first scroll event
self.onScrollStart(ev);
}
self._dom.write(() => {
// ******** DOM WRITE ****************
self.setTop(self._t);
});
}
function jsScrollTouchEnd(touchEvent: TouchEvent) {
// figure out what the scroll position was about 100ms ago
self._dom.cancel(rafCancel);
if (!positions.length && self.isScrolling) {
self.isScrolling = false;
ev.velocityY = ev.velocityX = 0;
self.onScrollEnd(ev);
return;
}
var y = pointerCoord(touchEvent).y;
positions.push(y, touchEvent.timeStamp);
var endPos = (positions.length - 1);
var startPos = endPos;
var timeRange = (touchEvent.timeStamp - 100);
// move pointer to position measured 100ms ago
for (var i = endPos; i > 0 && positions[i] > timeRange; i -= 2) {
startPos = i;
}
if (startPos !== endPos) {
// compute relative movement between these two points
var timeOffset = (positions[endPos] - positions[startPos]);
var movedTop = (positions[startPos - 1] - positions[endPos - 1]);
// based on XXms compute the movement to apply for each render step
ev.velocityY = ((movedTop / timeOffset) * FRAME_MS);
// verify that we have enough velocity to start deceleration
if (Math.abs(ev.velocityY) > MIN_VELOCITY_START_DECELERATION) {
// ******** DOM READ ****************
setMax();
rafCancel = self._dom.read((rafTimeStamp: number) => {
jsScrollDecelerate(rafTimeStamp);
});
}
} else {
self.isScrolling = false;
ev.velocityY = 0;
self.onScrollEnd(ev);
}
positions.length = 0;
}
const plt = self._plt;
const unRegStart = plt.registerListener(ele, 'touchstart', jsScrollTouchStart, EVENT_OPTS);
const unRegMove = plt.registerListener(ele, 'touchmove', jsScrollTouchMove, EVENT_OPTS);
const unRegEnd = plt.registerListener(ele, 'touchend', jsScrollTouchEnd, EVENT_OPTS);
ele.parentElement.classList.add('js-scroll');
// stop listening for actual scroll events
self._lsn && self._lsn();
// create an unregister for all of these events
self._lsn = () => {
unRegStart();
unRegMove();
unRegEnd();
ele.parentElement.classList.remove('js-scroll');
};
}
/**
* DOM READ
*/
getTop() {
if (this._js) {
return this._t;
}
return this._t = this._el.scrollTop;
}
/**
* DOM READ
*/
getLeft() {
if (this._js) {
return 0;
}
return this._l = this._el.scrollLeft;
}
/**
* DOM WRITE
*/
setTop(top: number) {
this._t = top;
if (this._js) {
(<any>this._el.style)[this._plt.Css.transform] = `translate3d(${this._l * -1}px,${top * -1}px,0px)`;
} else {
this._el.scrollTop = top;
}
}
/**
* DOM WRITE
*/
setLeft(left: number) {
this._l = left;
if (this._js) {
(<any>this._el.style)[this._plt.Css.transform] = `translate3d(${left * -1}px,${this._t * -1}px,0px)`;
} else {
this._el.scrollLeft = left;
}
}
scrollTo(x: number, y: number, duration: number, done?: Function): Promise<any> {
// scroll animation loop w/ easing
// credit https://gist.github.com/dezinezync/5487119
let promise: Promise<any>;
if (done === undefined) {
// only create a promise if a done callback wasn't provided
// done can be a null, which avoids any functions
promise = new Promise(resolve => {
done = resolve;
});
}
const self = this;
const el = self._el;
if (!el) {
// invalid element
done();
return promise;
}
if (duration < 32) {
self.setTop(y);
self.setLeft(x);
done();
return promise;
}
const fromY = el.scrollTop;
const fromX = el.scrollLeft;
const maxAttempts = (duration / 16) + 100;
const transform = self._plt.Css.transform;
let startTime: number;
let attempts = 0;
let stopScroll = false;
// scroll loop
function step(timeStamp: number) {
attempts++;
if (!self._el || stopScroll || attempts > maxAttempts) {
self.setScrolling(false, null);
(<any>el.style)[transform] = '';
done();
return;
}
let time = Math.min(1, ((timeStamp - startTime) / duration));
// where .5 would be 50% of time on a linear scale easedT gives a
// fraction based on the easing method
let easedT = (--time) * time * time + 1;
if (fromY !== y) {
self.setTop((easedT * (y - fromY)) + fromY);
}
if (fromX !== x) {
self.setLeft(Math.floor((easedT * (x - fromX)) + fromX));
}
if (easedT < 1) {
// do not use DomController here
// must use nativeRaf in order to fire in the next frame
self._plt.raf(step);
} else {
stopScroll = true;
self.setScrolling(false, null);
(<any>el.style)[transform] = '';
done();
}
}
// start scroll loop
self.setScrolling(true, null);
self.isScrolling = true;
// chill out for a frame first
self._dom.write(timeStamp => {
startTime = timeStamp;
step(timeStamp);
}, 16);
return promise;
}
scrollToTop(duration: number): Promise<any> {
return this.scrollTo(0, 0, duration);
}
scrollToBottom(duration: number): Promise<any> {
let y = 0;
if (this._el) {
y = this._el.scrollHeight - this._el.clientHeight;
}
return this.scrollTo(0, y, duration);
}
stop() {
this.setScrolling(false, null);
}
/**
* @hidden
*/
destroy() {
this.stop();
this._endTmr && this._dom.cancel(this._endTmr);
this._lsn && this._lsn();
let ev = this.ev;
ev.domWrite = ev.contentElement = ev.fixedElement = ev.scrollElement = ev.headerElement = null;
this._lsn = this._el = this._dom = this.ev = ev = null;
this.onScrollStart = this.onScroll = this.onScrollEnd = null;
}
}
export interface ScrollEvent {
timeStamp: number;
scrollTop: number;
scrollLeft: number;
scrollHeight: number;
scrollWidth: number;
contentHeight: number;
contentWidth: number;
contentTop: number;
contentBottom: number;
startY: number;
startX: number;
deltaY: number;
deltaX: number;
velocityY: number;
velocityX: number;
directionY: string;
directionX: string;
domWrite: {(fn: DomCallback, ctx?: any): void};
contentElement?: HTMLElement;
fixedElement?: HTMLElement;
scrollElement?: HTMLElement;
headerElement?: HTMLElement;
footerElement?: HTMLElement;
}
const SCROLL_END_DEBOUNCE_MS = 80;
const MIN_VELOCITY_START_DECELERATION = 4;
const MIN_VELOCITY_CONTINUE_DECELERATION = 0.12;
const DECELERATION_FRICTION = 0.97;
const FRAME_MS = (1000 / 60);
const EVENT_OPTS: EventListenerOptions = {
passive: true,
zone: false
}; | the_stack |
import {
Transform,
JSCodeshift,
Collection,
JSXAttribute,
StringLiteral,
JSXIdentifier,
} from 'jscodeshift';
import { findImportsByPath, findStyledComponentNames } from './utils';
// [old icon name, new icon name, product name (optional)]
const RENAMED_ICONS = [
['AddItem', 'AddItems', 'Item Catalog'],
['AddItemFilled', 'AddItems', 'Item Catalog'],
['AddPerson', 'AddEmployees', 'Employees'],
['AddPersonFilled', 'AddEmployees', 'Employees'],
['BatteryCharging', 'Battery'],
['Bin', 'Delete'],
['Calculator', 'FeeCalculator', 'Fee Calculator'],
['CalculatorFilled', 'FeeCalculator', 'Fee Calculator'],
['Card', 'SumUpCard', 'SumUp Card'],
['CardReader', 'CardReaderAir', 'Air Card Reader'],
['CashAtm', 'Atm'],
['Check', 'Checkmark'],
['CircleCheckmark', 'Confirm'],
['CircleCheckmarkFilled', 'Confirm'],
['CircleCross', 'Alert'],
['CircleCrossFilled', 'Alert'],
['CircleHelp', 'Help'],
['CircleHelpFilled', 'Help'],
['CircleInfo', 'Info'],
['CircleInfoFilled', 'Info'],
['CircleMore', 'More'],
['CirclePlus', 'Plus'],
['CircleWarning', 'Notify'],
['CircleWarningFilled', 'Notify'],
['Clock', 'Time'],
['CloudDownload', 'DownloadCloud'],
['Cross', 'Close'],
['Dashboard', 'Reports', 'Reports'],
['DashboardFilled', 'Reports', 'Reports'],
['Fallback', 'Tipping', 'Tipping'],
['FileZip', 'ZipFile'],
['Gift', 'Refer', 'Referrals'],
['GiftFilled', 'Refer', 'Referrals'],
['Hamburger', 'HamburgerMenu'],
['Heart', 'Like'],
['House', 'Home'],
['HouseFilled', 'Home'],
['LiveChatFilled', 'LiveChat', 'Support'],
['Lock', 'SecurePayments', 'Secure Payments'],
['LogOut', 'Logout'],
['Mail', 'EmailChat', 'Support'],
['PaperPlane', 'Send'],
['PenStroke', 'Edit'],
['Person', 'Profile', 'Profile'],
['PersonFilled', 'Profile', 'Profile'],
['SettingsFilled', 'Settings'],
['ShoppingBag', 'Shop', 'Shop'],
['ShoppingCart', 'Checkout', 'Checkout'],
['ShoppingCartFilled', 'Checkout', 'Checkout'],
['Store', 'OnlineStore', 'Online Store'],
['StoreFilled', 'OnlineStore', 'Online Store'],
['SupportFilled', 'Support', 'Support'],
['Terminal', 'VirtualTerminal', 'Virtual Terminal'],
['TerminalFilled', 'VirtualTerminal', 'Virtual Terminal'],
['Transactions', 'Sales', 'Sales'],
['TransactionsFilled', 'Sales', 'Sales'],
['Wallet', 'Payouts', 'Payouts'],
['WalletFilled', 'Payouts', 'Payouts'],
];
// [old icon name, custom error message (optional)]
const REMOVED_ICONS = [
[
'Calendar',
'The icon is being redesigned and will be released in an upcoming minor version.',
],
['FilterFunnel'],
['Folder'],
[
'Globe',
'The icon is being redesigned and will be released in an upcoming minor version.',
],
[
'Rename',
'Use the "Edit" icon instead, and use an accessible label for "Rename".',
],
['SelectCollapse', 'Use the Chevron icons instead.'],
['SelectExpand', 'Use the Chevron icons instead.'],
['Spinner', 'Use the Spinner component from "@sumup/circuit-ui" instead.'],
[
'Table',
'The icon is being redesigned and will be released in an upcoming minor version.',
],
['ThumbDown'],
['ThumbUp'],
['Zap'],
];
const SMALL_ICONS = [
'ArrowLeft',
'ArrowRight',
'ChevronDown',
'ChevronLeft',
'ChevronRight',
'ChevronUp',
'Close',
'Delete',
'Edit',
'Minus',
'Pause',
'Play',
'Plus',
'Search',
'Checkmark',
'Alert',
'Confirm',
'Help',
'Info',
'Notify',
];
const LARGE_ONLY_LEGACY_ICONS = [
'AddItems',
'AddEmployees',
'More',
'Logout',
'LiveChat',
'EmailChat',
'Support',
'AmericanExpress',
'ApplePay',
'BancoEstado',
'Bitcoin',
'Dankort',
'DinersClub',
'Discover',
'Ec',
'Elo',
'Elv',
'GooglePay',
'Hiper',
'Hipercard',
'Jcb',
'Maestro',
'Mastercard',
'RedCompra',
'SamsungPay',
'UnionPay',
'VisaElectron',
'Visa',
'Vpay',
'Wifi',
'FeeCalculator',
'CardReaderAir',
'Laptop',
'Nfc',
'VirtualTerminal',
'Archive',
'DownloadCloud',
'History',
'Payouts',
'Company',
'CardUnknown',
'Atm',
'Cash',
'CashStack',
'Tipping',
'Sales',
'Image',
'Barcode',
'Battery',
'BrowserSecure',
'Time',
'Reports',
'Refer',
'Like',
'Home',
'SecurePayments',
'Package',
'Send',
'Profile',
'Secure',
'Settings',
'Shop',
'Checkout',
'SimCard',
'OnlineStore',
'Truck',
'Zap',
'Messenger',
'Facebook',
'Instagram',
'Linkedin',
'Pinterest',
'Twitter',
'Youtube',
'SumUpLogo',
];
function handleIconSizeRenamed(j: JSCodeshift, root: Collection): void {
const imports = findImportsByPath(j, root, '@sumup/icons');
if (imports.length < 1) {
return;
}
const components = imports.reduce<string[]>((acc, cur) => {
const localName = cur.local;
const styledComponents = findStyledComponentNames(j, root, localName);
return [...acc, localName, ...styledComponents];
}, []);
components.forEach((component) => {
const jsxElement = root.findJSXElements(component);
// The babel and TypeScript parsers use different node types.
['Literal', 'StringLiteral'].forEach((type) => {
jsxElement
.find(j.JSXAttribute, {
name: {
type: 'JSXIdentifier',
name: 'size',
},
value: {
type,
value: 'small',
},
})
.replaceWith(() =>
j.jsxAttribute(j.jsxIdentifier('size'), j.stringLiteral('16')),
);
jsxElement
.find(j.JSXAttribute, {
name: {
type: 'JSXIdentifier',
name: 'size',
},
value: {
type,
value: 'large',
},
})
.replaceWith(() =>
j.jsxAttribute(j.jsxIdentifier('size'), j.stringLiteral('24')),
);
});
});
}
function handleIconRenamed(
j: JSCodeshift,
root: Collection,
filePath: string,
oldIconName: string,
newIconName: string,
productName?: string,
): void {
const imports = findImportsByPath(j, root, '@sumup/icons');
const legacyIconImport = imports.find((i) => i.name === oldIconName);
if (!legacyIconImport) {
return;
}
if (productName) {
console.warn(
[
`The "${oldIconName}" icon has been renamed to "${newIconName}",`,
`and should only be used in the context of the ${productName}`,
'product/feature.',
'If you have doubts about your use of the icon, file an issue or',
'contact the Design System team.',
`\nin ${filePath}`,
].join(' '),
);
}
root
.find(j.Identifier)
.filter((nodePath) => {
const isLegacyIconName = nodePath.node.name === oldIconName;
return isLegacyIconName;
})
.replaceWith(j.identifier(newIconName));
}
function handleIconRemoved(
j: JSCodeshift,
root: Collection,
filePath: string,
oldIconName: string,
customMessage?: string,
): void {
const imports = findImportsByPath(j, root, '@sumup/icons');
const legacyIconImport = imports.find((i) => i.name === oldIconName);
if (legacyIconImport) {
const defaultMessage =
'Copy it locally to finish the migration, and request a new icon from the Design System team.';
console.error(
[
`The "${oldIconName}" icon has been removed.`,
customMessage || defaultMessage,
`\nin ${filePath}`,
].join(' '),
);
}
}
function handleIconDefaultSize(
j: JSCodeshift,
root: Collection,
filePath: string,
): void {
const imports = findImportsByPath(j, root, '@sumup/icons');
if (!imports.length) {
return;
}
imports
.filter(
(i) =>
i.local !== 'Checkmark' && // 16px only, so the default would still be 16
!i.local.startsWith('Flag') && // idem
!REMOVED_ICONS.map((icon) => icon[0]).includes(i.local) && // These icons were removed
!LARGE_ONLY_LEGACY_ICONS.includes(i.local), // These icons were only 24px in v1, so the default was already 24
)
.forEach((i) => {
root
.findJSXElements(i.local)
.filter((jsxElement) => {
const hasSmallIcon = SMALL_ICONS.includes(i.local);
const attributes = jsxElement.node.openingElement
.attributes as JSXAttribute[];
const sizeAttribute = attributes.find((a) => a.name.name === 'size');
const hasSize16 =
(sizeAttribute?.value as StringLiteral)?.value === '16';
const hasImplicitSize16 = !sizeAttribute;
if (hasImplicitSize16 && hasSmallIcon) {
return true; // we will add the new size
}
const actionMessage = [
'Verify your page with the 24px icon size, and request a new 16px size',
'from the Design System team if needed.',
`\nin ${filePath}`,
];
if (hasSize16 && !hasSmallIcon) {
console.error(
[
`The 16px size of the "${i.local}" icon has been removed.`,
...actionMessage,
].join(' '),
);
}
if (hasImplicitSize16 && !hasSmallIcon) {
console.error(
[
`The default size of the "${i.local}" icon changed from 16px to 24px.`,
...actionMessage,
].join(' '),
);
}
return false;
})
.replaceWith(({ node }) => {
const attributes = node.openingElement.attributes || [];
return j.jsxElement(
j.jsxOpeningElement(
j.jsxIdentifier((node.openingElement.name as JSXIdentifier).name),
attributes.concat(
j.jsxAttribute(j.jsxIdentifier('size'), j.stringLiteral('16')),
),
node.openingElement.selfClosing,
),
node.closingElement,
node.children,
);
});
});
}
const transform: Transform = (file, api) => {
const j = api.jscodeshift;
const root = j(file.source);
const filePath = file.path;
REMOVED_ICONS.forEach(([oldIconName, customMessage]) => {
handleIconRemoved(j, root, filePath, oldIconName, customMessage);
});
RENAMED_ICONS.forEach(([oldIconName, newIconName, productName]) => {
handleIconRenamed(j, root, filePath, oldIconName, newIconName, productName);
});
handleIconSizeRenamed(j, root);
handleIconDefaultSize(j, root, filePath);
return root.toSource();
};
export default transform; | the_stack |
export default [
{
index: 1,
md: ' foo→baz→→bim\n\n',
html: '<pre><code>foo→baz→→bim</code></pre>\n\n',
},
{
index: 2,
md: ' foo→baz→→bim\n\n',
html: '<pre><code>foo→baz→→bim</code></pre>\n\n',
},
{
index: 3,
md: ' a→a\n ὐ→a\n\n',
html: '<pre><code>a→a\nὐ→a</code></pre>\n\n',
},
{
index: 4,
md: '- foo\n\n bar\n\n',
html: '<ul>\n<li>\n<p>foo</p>\n<p>bar</p>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
// {
// "index": 5,
// "md": "- foo\n\n bar\n\n",
// "html": "<ul>\n<li>\n<p>foo</p>\n<pre><code> bar\n</code></pre>\n</li>\n</ul>\n\n",
// "option": {
// "bulletListMarker": "-"
// }
// },
// {
// "index": 6,
// "md": ">→→foo\n\n",
// "html": "<blockquote>\n<pre><code> foo\n</code></pre>\n</blockquote>\n\n"
// },
// {
// index: 7,
// md: '-→→foo\n\n',
// html: '<ul>\n<li>\n<pre><code> foo\n</code></pre>\n</li>\n</ul>\n\n',
// },
// {
// index: 8,
// md: ' foo\n→bar\n\n',
// html: '<pre><code>foo\nbar\n</code></pre>\n\n',
// },
// {
// index: 9,
// md: ' - foo\n - bar\n→ - baz\n\n',
// html:
// '<ul>\n<li>foo\n<ul>\n<li>bar\n<ul>\n<li>baz</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n\n',
// },
// {
// "index": 10,
// "md": "#→Foo\n\n",
// "html": "<h1>Foo</h1>\n\n"
// },
// {
// index: 11,
// md: '*→*→*→\n\n',
// html: '<hr />\n\n',
// },
{
index: 12,
md: '* \\`one\n* two\\`\n\n',
html: '<ul>\n<li>`one</li>\n<li>two`</li>\n</ul>\n\n',
},
{
index: 13,
md: '***\n***\n***\n\n',
html: '<hr />\n<hr />\n<hr />\n\n',
option: {
hr: '***',
},
},
{
index: 14,
md: '+++\n\n',
html: '<p>+++</p>\n\n',
},
{
index: 15,
md: '\\===\n\n',
html: '<p>===</p>\n\n',
},
{
index: 16,
md: '\\-- \\*\\* \\_\\_\n',
html: '<p>--\n**\n__</p>\n\n',
},
{
index: 17,
md: '***\n***\n***\n\n',
html: '<hr />\n<hr />\n<hr />\n\n',
option: {
hr: '***',
},
},
{
index: 18,
md: ' ***\n\n',
html: '<pre><code>***</code></pre>\n\n',
},
{
index: 19,
md: 'Foo \\*\\*\\*\n\n',
html: '<p>Foo\n***</p>\n\n',
},
{
index: 20,
md: '_____________________________________\n\n',
html: '<hr />\n\n',
option: {
hr: '_____________________________________',
},
},
{
index: 21,
md: ' - - -\n\n',
html: '<hr />\n\n',
option: {
hr: ' - - -',
},
},
{
index: 22,
md: ' ** * ** * ** * **\n\n',
html: '<hr />\n\n',
option: {
hr: ' ** * ** * ** * **',
},
},
{
index: 23,
md: '- - - -\n\n',
html: '<hr />\n\n',
option: {
hr: '- - - -',
},
},
{
index: 24,
md: '- - - -\n\n',
html: '<hr />\n\n',
option: {
hr: '- - - -',
},
},
{
index: 25,
md: '\\_ \\_ \\_ \\_ a\n\na------\n\n\\---a---\n\n',
html: '<p>_ _ _ _ a</p>\n<p>a------</p>\n<p>---a---</p>\n\n',
},
{
index: 26,
md: '*\\-*\n\n',
html: '<p><em>-</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 27,
md: '- foo\n\n***\n\n- bar\n\n',
html: '<ul>\n<li>foo</li>\n</ul>\n<hr />\n<ul>\n<li>bar</li>\n</ul>\n\n',
option: {
hr: '***',
bulletListMarker: '-',
},
},
{
index: 28,
md: 'Foo\n\n***\n\nbar\n\n',
html: '<p>Foo</p>\n<hr />\n<p>bar</p>\n\n',
option: {
hr: '***',
},
},
{
index: 29,
md: 'Foo\n---\n\nbar\n\n',
html: '<h2>Foo</h2>\n<p>bar</p>\n\n',
option: {
headingStyle: 'setext',
},
},
{
index: 30,
md: '* Foo\n\n* * *\n\n* Bar\n\n',
html: '<ul>\n<li>Foo</li>\n</ul>\n<hr />\n<ul>\n<li>Bar</li>\n</ul>\n\n',
},
{
index: 31,
md: '- Foo\n- * * *\n\n',
html: '<ul>\n<li>Foo</li>\n<li>\n<hr />\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 32,
md: '# foo\n\n## foo\n\n### foo\n\n#### foo\n\n##### foo\n\n###### foo\n\n',
html:
'<h1>foo</h1>\n<h2>foo</h2>\n<h3>foo</h3>\n<h4>foo</h4>\n<h5>foo</h5>\n<h6>foo</h6>\n\n',
},
{
index: 33,
md: '####### foo\n\n',
html: '<p>####### foo</p>\n\n',
},
{
index: 34,
md: '#5 bolt\n\n#hashtag\n\n',
html: '<p>#5 bolt</p>\n<p>#hashtag</p>\n\n',
},
{
index: 35,
md: '\\## foo\n\n',
html: '<p>## foo</p>\n\n',
},
{
index: 36,
md: '# foo *bar* \\*baz\\*\n\n',
html: '<h1>foo <em>bar</em> *baz*</h1>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 37,
md: '# foo\n\n',
html: '<h1>foo</h1>\n\n',
},
{
index: 38,
md: '### foo\n\n## foo\n\n# foo\n\n',
html: '<h3>foo</h3>\n<h2>foo</h2>\n<h1>foo</h1>\n\n',
},
{
index: 39,
md: ' # foo\n\n',
html: '<pre><code># foo</code></pre>\n\n',
},
{
index: 40,
md: 'foo # bar\n\n',
html: '<p>foo\n# bar</p>\n\n',
},
// {
// index: 41,
// md: '## foo ##\n ### bar ###\n\n',
// html: '<h2>foo</h2>\n<h3>bar</h3>\n\n',
// },
// {
// index: 42,
// md: '# foo ##################################\n##### foo ##\n\n',
// html: '<h1>foo</h1>\n<h5>foo</h5>\n\n',
// },
// {
// index: 43,
// md: '### foo ### \n\n',
// html: '<h3>foo</h3>\n\n',
// },
{
index: 44,
md: '### foo \\### b\n\n',
html: '<h3>foo ### b</h3>\n\n',
},
{
index: 45,
md: '# foo#\n\n',
html: '<h1>foo#</h1>\n\n',
},
{
index: 46,
md: '### foo \\###\n\n## foo \\###\n\n# foo \\#\n\n',
html: '<h3>foo ###</h3>\n<h2>foo ###</h2>\n<h1>foo #</h1>\n\n',
},
{
index: 47,
md: '****\n\n## foo\n\n****\n\n',
html: '<hr />\n<h2>foo</h2>\n<hr />\n\n',
option: {
hr: '****',
},
},
{
index: 48,
md: 'Foo bar\n\n# baz\n\nBar foo\n\n',
html: '<p>Foo bar</p>\n<h1>baz</h1>\n<p>Bar foo</p>\n\n',
},
// {
// index: 49,
// md: '## \n#\n### ###\n\n',
// html: '<h2></h2>\n<h1></h1>\n<h3></h3>\n\n',
// },
{
index: 50,
md: 'Foo *bar*\n=========\n\nFoo *bar*\n---------\n\n',
html: '<h1>Foo <em>bar</em></h1>\n<h2>Foo <em>bar</em></h2>\n\n',
option: {
headingStyle: 'setext',
emDelimiter: '*',
},
},
{
index: 51,
md: 'Foo *bar baz*\n=============\n\n',
html: '<h1>Foo <em>bar\nbaz</em></h1>\n\n',
option: {
headingStyle: 'setext',
emDelimiter: '*',
},
},
{
index: 52,
md: 'Foo *bar baz*\n=============\n\n',
html: '<h1>Foo <em>bar\nbaz</em></h1>\n\n',
option: {
headingStyle: 'setext',
emDelimiter: '*',
},
},
{
index: 53,
md: 'Foo\n---\n\nFoo\n===\n\n',
html: '<h2>Foo</h2>\n<h1>Foo</h1>\n\n',
option: {
headingStyle: 'setext',
},
},
{
index: 54,
md: 'Foo\n---\n\nFoo\n---\n\nFoo\n===\n\n',
html: '<h2>Foo</h2>\n<h2>Foo</h2>\n<h1>Foo</h1>\n\n',
option: {
headingStyle: 'setext',
},
},
{
index: 55,
md: ' Foo\n ---\n \n Foo\n \n\n---\n\n',
html: '<pre><code>Foo\n---\n\nFoo\n</code></pre>\n<hr />\n\n',
option: {
headingStyle: 'setext',
hr: '---',
},
},
{
index: 56,
md: 'Foo\n---\n\n',
html: '<h2>Foo</h2>\n\n',
option: {
headingStyle: 'setext',
},
},
{
index: 57,
md: 'Foo \\---\n\n',
html: '<p>Foo\n---</p>\n\n',
},
{
index: 58,
md: 'Foo = =\n\nFoo\n\n--- -\n\n',
html: '<p>Foo\n= =</p>\n<p>Foo</p>\n<hr />\n\n',
option: {
headingStyle: 'setext',
hr: '--- -',
},
},
{
index: 59,
md: 'Foo\n---\n\n',
html: '<h2>Foo</h2>\n\n',
option: {
headingStyle: 'setext',
},
},
{
index: 60,
md: 'Foo\\\\\n-----\n\n',
html: '<h2>Foo\\</h2>\n\n',
option: {
headingStyle: 'setext',
},
},
{
index: 61,
md:
'\\`Foo\n-----\n\n\\`\n\n\\<a title="a lot\n----------------\n\nof dashes"/>\n\n',
html:
'<h2>`Foo</h2>\n<p>`</p>\n<h2><a title="a lot</h2>\n<p>of dashes"/></p>\n\n',
option: {
headingStyle: 'setext',
},
},
{
index: 62,
md: '> Foo\n\n---\n\n',
html: '<blockquote>\n<p>Foo</p>\n</blockquote>\n<hr />\n\n',
option: {
headingStyle: 'setext',
hr: '---',
},
},
{
index: 63,
md: '> foo bar ===\n\n',
html: '<blockquote>\n<p>foo\nbar\n===</p>\n</blockquote>\n\n',
option: {
headingStyle: 'setext',
},
},
{
index: 64,
md: '- Foo\n\n---\n\n',
html: '<ul>\n<li>Foo</li>\n</ul>\n<hr />\n\n',
option: {
headingStyle: 'setext',
hr: '---',
bulletListMarker: '-',
},
},
{
index: 65,
md: 'Foo Bar\n-------\n\n',
html: '<h2>Foo\nBar</h2>\n\n',
option: {
headingStyle: 'setext',
},
},
{
index: 66,
md: '---\n\nFoo\n---\n\nBar\n---\n\nBaz\n\n',
html: '<hr />\n<h2>Foo</h2>\n<h2>Bar</h2>\n<p>Baz</p>\n\n',
option: {
headingStyle: 'setext',
hr: '---',
},
},
{
index: 67,
md: '\\====\n\n',
html: '<p>====</p>\n\n',
option: {
headingStyle: 'setext',
},
},
{
index: 68,
md: '---\n---\n\n',
html: '<hr />\n<hr />\n\n',
option: {
headingStyle: 'setext',
hr: '---',
},
},
{
index: 69,
md: '- foo\n\n-----\n\n',
html: '<ul>\n<li>foo</li>\n</ul>\n<hr />\n\n',
option: {
headingStyle: 'setext',
bulletListMarker: '-',
hr: '-----',
},
},
{
index: 70,
md: ' foo\n \n\n---\n\n',
html: '<pre><code>foo\n</code></pre>\n<hr />\n\n',
option: {
headingStyle: 'setext',
hr: '---',
},
},
{
index: 71,
md: '> foo\n\n-----\n\n',
html: '<blockquote>\n<p>foo</p>\n</blockquote>\n<hr />\n\n',
option: {
headingStyle: 'setext',
hr: '-----',
},
},
{
index: 72,
md: '\\> foo\n------\n\n',
html: '<h2>> foo</h2>\n\n',
option: {
headingStyle: 'setext',
},
},
{
index: 73,
md: 'Foo\n\nbar\n---\n\nbaz\n\n',
html: '<p>Foo</p>\n<h2>bar</h2>\n<p>baz</p>\n\n',
option: {
headingStyle: 'setext',
},
},
{
index: 74,
md: 'Foo bar\n\n---\n\nbaz\n\n',
html: '<p>Foo\nbar</p>\n<hr />\n<p>baz</p>\n\n',
option: {
headingStyle: 'setext',
hr: '---',
},
},
{
index: 75,
md: 'Foo bar\n\n* * *\n\nbaz\n\n',
html: '<p>Foo\nbar</p>\n<hr />\n<p>baz</p>\n\n',
option: {
headingStyle: 'setext',
},
},
{
index: 76,
md: 'Foo bar \\--- baz\n\n',
html: '<p>Foo\nbar\n---\nbaz</p>\n\n',
option: {
headingStyle: 'setext',
},
},
{
index: 77,
md: ' a simple\n indented code block\n\n',
html: '<pre><code>a simple\n indented code block</code></pre>\n\n',
},
{
index: 78,
md: '- foo\n\n bar\n\n',
html: '<ul>\n<li>\n<p>foo</p>\n<p>bar</p>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 79,
md: '1. foo\n\n - bar\n\n',
html: '<ol>\n<li>\n<p>foo</p>\n<ul>\n<li>bar</li>\n</ul>\n</li>\n</ol>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 80,
md: ' <a/>\n *hi*\n \n - one\n\n',
html: '<pre><code><a/>\n*hi*\n\n- one</code></pre>\n\n',
},
{
index: 81,
md: ' chunk1\n \n chunk2\n \n \n \n chunk3\n\n',
html: '<pre><code>chunk1\n\nchunk2\n\n\n\nchunk3</code></pre>\n\n',
},
{
index: 82,
md: ' chunk1\n \n chunk2\n\n',
html: '<pre><code>chunk1\n \n chunk2</code></pre>\n\n',
},
{
index: 83,
md: 'Foo bar\n\n',
html: '<p>Foo\nbar</p>\n\n',
},
{
index: 84,
md: ' foo\n \n\nbar\n\n',
html: '<pre><code>foo\n</code></pre>\n<p>bar</p>\n\n',
},
{
index: 85,
md: '# Heading\n\n foo\n \n\n## Heading\n\n foo\n \n\n----\n\n',
html:
'<h1>Heading</h1>\n<pre><code>foo\n</code></pre>\n<h2>Heading</h2>\n<pre><code>foo\n</code></pre>\n<hr />\n\n',
option: {
hr: '----',
},
},
{
index: 86,
md: ' foo\n bar\n\n',
html: '<pre><code> foo\nbar</code></pre>\n\n',
},
{
index: 87,
md: ' foo\n\n\n',
html: '<pre><code>foo</code></pre>\n\n',
},
// {
// index: 88,
// md: ' foo \n\n',
// html: '<pre><code>foo </code></pre>\n\n',
// },
{
index: 89,
md: '```\n<\n >\n```\n\n',
html: '<pre><code><\n >\n</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
},
},
{
index: 90,
md: '~~~\n<\n >\n~~~\n\n',
html: '<pre><code><\n >\n</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
fence: '~~~',
},
},
// {
// index: 91,
// md: '``\nfoo\n``\n\n',
// html: '<p><code>foo</code></p>\n\n',
// option: {
// codeBlockStyle: 'fenced',
// },
// },
{
index: 92,
md: '```\naaa\n~~~\n```\n\n',
html: '<pre><code>aaa\n~~~\n</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
},
},
{
index: 93,
md: '~~~\naaa\n```\n~~~\n\n',
html: '<pre><code>aaa\n```\n</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
fence: '~~~',
},
},
{
index: 94,
md: '````\naaa\n```\n``````\n\n',
html: '<pre><code>aaa\n```\n</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
fence: '````',
endFence: '``````',
},
},
{
index: 95,
md: '~~~~\naaa\n~~~\n~~~~\n\n',
html: '<pre><code>aaa\n~~~\n</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
fence: '~~~~',
},
},
{
index: 96,
md: '```\n\n',
html: '<pre><code></code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
endFence: '',
},
},
{
index: 97,
md: '`````\n\n```\naaa\n\n',
html: '<pre><code>\n```\naaa</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
fence: '`````',
endFence: '',
},
},
{
index: 98,
md: '> ```\n> aaa\n\nbbb\n\n',
html:
'<blockquote>\n<pre><code>aaa\n</code></pre>\n</blockquote>\n<p>bbb</p>\n\n',
option: {
codeBlockStyle: 'fenced',
endFence: '',
},
},
{
index: 99,
md: '```\n\n \n```\n\n',
html: '<pre><code>\n \n</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
},
},
{
index: 100,
md: '```\n```\n\n',
html: '<pre><code></code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
},
},
// {
// index: 101,
// md: ' ```\n aaa\naaa\n```\n\n',
// html: '<pre><code>aaa\naaa\n</code></pre>\n\n',
// option: {
// codeBlockStyle: 'fenced',
// },
// },
// {
// index: 102,
// md: ' ```\naaa\n aaa\naaa\n ```\n\n',
// html: '<pre><code>aaa\naaa\naaa\n</code></pre>\n\n',
// option: {
// codeBlockStyle: 'fenced',
// },
// },
// {
// index: 103,
// md: ' ```\n aaa\n aaa\n aaa\n ```\n\n',
// html: '<pre><code>aaa\n aaa\naaa\n</code></pre>\n\n',
// option: {
// codeBlockStyle: 'fenced',
// },
// },
{
index: 104,
md: ' ```\n aaa\n ```\n\n',
html: '<pre><code>```\naaa\n```</code></pre>\n\n',
},
{
index: 105,
md: '```\naaa\n ```\n\n',
html: '<pre><code>aaa\n</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
endFence: ' ```',
},
},
{
index: 106,
md: ' ```\naaa\n ```\n\n',
html: '<pre><code>aaa\n</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
startFence: ' ```',
endFence: ' ```',
},
},
{
index: 107,
md: '```\naaa\n ```\n\n',
html: '<pre><code>aaa\n ```</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
endFence: '',
},
},
{
index: 108,
md: '``` ```\naaa\n\n',
html: '<p><code> </code>\naaa</p>\n\n',
option: {
codeBlockStyle: 'fenced',
codeDelimiter: '```',
},
},
{
index: 109,
md: '~~~~~~\naaa\n~~~ ~~\n\n',
html: '<pre><code>aaa\n~~~ ~~</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
startFence: '~~~~~~',
endFence: '',
},
},
{
index: 110,
md: 'foo\n\n```\nbar\n```\n\nbaz\n\n',
html: '<p>foo</p>\n<pre><code>bar\n</code></pre>\n<p>baz</p>\n\n',
option: {
codeBlockStyle: 'fenced',
},
},
{
index: 111,
md: '## foo\n\n~~~\nbar\n~~~\n\n# baz\n\n',
html: '<h2>foo</h2>\n<pre><code>bar\n</code></pre>\n<h1>baz</h1>\n\n',
option: {
codeBlockStyle: 'fenced',
fence: '~~~',
},
},
{
index: 112,
md: '```ruby\ndef foo(x)\n return 3\nend\n```\n\n',
html:
'<pre><code class="language-ruby">def foo(x)\n return 3\nend\n</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
},
},
// {
// index: 113,
// md:
// '~~~~ruby startline=3 $%@#$\ndef foo(x)\n return 3\nend\n~~~~~~~\n\n',
// html:
// '<pre><code class="language-ruby">def foo(x)\n return 3\nend\n</code></pre>\n\n',
// option:{
// codeBlockStyle: 'fenced',
// fence:'~~~~',
// endFence:'~~~~~~~'
// }
// },
{
index: 114,
md: '````;\n````\n\n',
html: '<pre><code class="language-;"></code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
fence: '````',
},
},
{
index: 115,
md: '```aa``` foo\n\n',
html: '<p><code>aa</code>\nfoo</p>\n\n',
option: {
codeBlockStyle: 'fenced',
codeDelimiter: '```',
},
},
{
index: 116,
md: '~~~aa\nfoo\n~~~\n\n',
html: '<pre><code class="language-aa">foo\n</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
fence: '~~~',
},
},
{
index: 117,
md: '```\n``` aaa\n```\n\n',
html: '<pre><code>``` aaa\n</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
},
},
// Info:表格
// {
// index: 118,
// md:
// '<table><tr><td>\n<pre>\n**Hello**,\n\n_world_.\n</pre>\n</td></tr></table>\n\n',
// html:
// '<table><tr><td>\n<pre>\n**Hello**,\n<p><em>world</em>.\n</pre></p>\n</td></tr></table>\n\n',
// },
// {
// index: 119,
// md:
// '<table>\n <tr>\n <td>\n hi\n </td>\n </tr>\n</table>\n\nokay.\n\n',
// html:
// '<table>\n <tr>\n <td>\n hi\n </td>\n </tr>\n</table>\n<p>okay.</p>\n\n',
// },
// 不规范的 HTML
// {
// index: 120,
// md: '<div>*hello*<foo><a>\n\n',
// html: ' <div>\n *hello*\n <foo><a>\n\n',
// },
// {
// index: 121,
// md: '</div>\n*foo*\n\n',
// html: '</div>\n*foo*\n\n',
// },
// {
// index: 122,
// md: '<DIV CLASS="foo">\n\n*Markdown*\n\n</DIV>\n\n',
// html: '<DIV CLASS="foo">\n<p><em>Markdown</em></p>\n</DIV>\n\n',
// },
// 空内容
// {
// index: 123,
// md: '<div id="foo"\n class="bar">\n</div>\n\n',
// html: '<div id="foo"\n class="bar">\n</div>\n\n',
// },
// {
// index: 124,
// md: '<div id="foo" class="bar\n baz">\n</div>\n\n',
// html: '<div id="foo" class="bar\n baz">\n</div>\n\n',
// },
// {
// index: 125,
// md: '<div>\n*foo*\n\n*bar*\n\n',
// html: '<div>\n*foo*\n<p><em>bar</em></p>\n\n',
// },
// {
// index: 126,
// md: '<div id="foo"\n*hi*\n\n',
// html: '<div id="foo"\n*hi*\n\n',
// },
// {
// index: 127,
// md: '<div class\nfoo\n\n',
// html: '<div class\nfoo\n\n',
// },
// {
// index: 128,
// md: '<div *???-&&&-<---\n*foo*\n\n',
// html: '<div *???-&&&-<---\n*foo*\n\n',
// },
{
index: 129,
md: '<div><a href="bar">*foo*</a></div>\n\n',
html: '<div><a href="bar">*foo*</a></div>\n\n',
},
{
index: 130,
md: '<table><tbody><tr><td>foo</td></tr></tbody></table>\n\n',
html: '<table><tr><td>\nfoo\n</td></tr></table>\n\n',
},
// {
// index: 131,
// md: '<div></div>\n``` c\nint x = 33;\n```\n\n',
// html: '<div></div>\n``` c\nint x = 33;\n```\n\n',
// },
// {
// index: 132,
// md: '<a href="foo">\n*bar*\n</a>\n\n',
// html: '<a href="foo">\n*bar*\n</a>\n\n',
// },
// {
// index: 133,
// md: '<Warning>\n*bar*\n</Warning>\n\n',
// html: '<Warning>\n*bar*\n</Warning>\n\n',
// },
// {
// index: 134,
// md: '<i class="foo">\n*bar*\n</i>\n\n',
// html: '<i class="foo">\n*bar*\n</i>\n\n',
// },
// {
// index: 135,
// md: '</ins>\n*bar*\n\n',
// html: '</ins>\n*bar*\n\n',
// },
// {
// index: 136,
// md: '<del>\n*foo*\n</del>\n\n',
// html: '<del>\n*foo*\n</del>\n\n',
// },
// {
// index: 137,
// md: '<del>\n\n*foo*\n\n</del>\n\n',
// html: '<del>\n<p><em>foo</em></p>\n</del>\n\n',
// },
// {
// index: 138,
// md: '<del>*foo*</del>\n\n',
// html: '<p><del><em>foo</em></del></p>\n\n',
// },
// {
// index: 139,
// md:
// '<pre language="haskell"><code>\nimport Text.HTML.TagSoup\n\nmain :: IO ()\nmain = print $ parseTags tags\n</code></pre>\nokay\n\n',
// html:
// '<pre language="haskell"><code>\nimport Text.HTML.TagSoup\n\nmain :: IO ()\nmain = print $ parseTags tags\n</code></pre>\n<p>okay</p>\n\n',
// },
// {
// index: 140,
// md:
// '<script type="text/javascript">\n// JavaScript example\n\ndocument.getElementById("demo").innerHTML = "Hello JavaScript!";\n</script>\nokay\n\n',
// html:
// '<script type="text/javascript">\n// JavaScript example\n\ndocument.getElementById("demo").innerHTML = "Hello JavaScript!";\n</script>\n<p>okay</p>\n\n',
// },
{
index: 141,
md:
'<style type="text/css">h1 {color:red;} p {color:blue;}</style>\n\nokay\n\n',
html:
'<style\n type="text/css">\nh1 {color:red;}\n\np {color:blue;}\n</style>\n<p>okay</p>\n\n',
},
// {
// index: 142,
// md: '<style\n type="text/css">\n\nfoo\n\n',
// html: '<style\n type="text/css">\n\nfoo\n\n',
// },
// {
// index: 143,
// md: '> <div>\n> foo\n\nbar\n\n',
// html: '<blockquote>\n<div>\nfoo\n</blockquote>\n<p>bar</p>\n\n',
// },
// {
// index: 144,
// md: '- <div>\n- foo\n\n',
// html: '<ul>\n<li>\n<div>\n</li>\n<li>foo</li>\n</ul>\n\n',
// },
{
index: 145,
md: '<style>p{color:red;}</style>\n\n*foo*\n\n',
html: '<style>p{color:red;}</style>\n<p><em>foo</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 146,
md: '<!-- foo -->*bar*\n\n*baz*\n\n',
html: '<!-- foo -->*bar*\n<p><em>baz</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
// {
// index: 147,
// md: '<script>\nfoo\n</script>1. *bar*\n\n',
// html: '<script>\nfoo\n</script>1. *bar*\n\n',
// },
{
index: 148,
md: '<!-- Foo\n\nbar\n baz -->\n\nokay\n\n',
html: '<!-- Foo\n\nbar\n baz -->\n<p>okay</p>\n\n',
},
// {
// index: 149,
// md: "<?php\n\n echo '>';\n\n?>\nokay\n\n",
// html: "<?php\n\n echo '>';\n\n?>\n<p>okay</p>\n\n",
// },
// {
// index: 150,
// md: '<!DOCTYPE html>\n\n',
// html: '<!DOCTYPE html>\n\n',
// },
// {
// index: 151,
// md:
// '<![CDATA[\nfunction matchwo(a,b)\n{\n if (a < b && a < 0) then {\n return 1;\n\n } else {\n\n return 0;\n }\n}\n]]>\nokay\n\n',
// html:
// '<![CDATA[\nfunction matchwo(a,b)\n{\n if (a < b && a < 0) then {\n return 1;\n\n } else {\n\n return 0;\n }\n}\n]]>\n<p>okay</p>\n\n',
// },
{
index: 152,
md: '<!-- foo -->\n\n <!-- foo -->\n\n',
html: ' <!-- foo -->\n<pre><code><!-- foo --></code></pre>\n\n',
},
// {
// index: 153,
// md: ' <div>\n\n <div>\n\n',
// html: ' <div>\n<pre><code><div>\n</code></pre>\n\n',
// },
{
index: 154,
md: 'Foo\n\n<div>bar</div>\n\n',
html: '<p>Foo</p>\n<div>\nbar\n</div>\n\n',
},
{
index: 155,
md: '<div>bar</div>\n*foo*\n\n',
html: '<div>\nbar\n</div>\n*foo*\n\n',
},
// {
// index: 156,
// md: 'Foo\n<a href="bar">\nbaz\n\n',
// html: '<p>Foo\n<a href="bar">\nbaz</p>\n\n',
// },
// {
// index: 157,
// md: '<div>\n\n*Emphasized* text.\n\n</div>\n\n',
// html: '<div>\n<p><em>Emphasized</em> text.</p>\n</div>\n\n',
// },
{
index: 158,
md: '<div>*Emphasized* text.</div>\n\n',
html: '<div>\n*Emphasized* text.\n</div>\n\n',
},
{
index: 159,
md: '<table><tbody><tr><td>Hi</td></tr></tbody></table>\n\n',
html: '<table>\n<tr>\n<td>\nHi\n</td>\n</tr>\n</table>\n\n',
},
// {
// index: 160,
// md:
// '<table>\n\n <tr>\n\n <td>\n Hi\n </td>\n\n </tr>\n\n</table>\n\n',
// html:
// '<table>\n <tr>\n<pre><code><td>\n Hi\n</td>\n</code></pre>\n </tr>\n</table>\n\n',
// },
{
index: 161,
md: '[foo]: /url "title"\n\n[foo]\n\n',
html: '<p><a href="/url" title="title">foo</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
// {
// index: 162,
// md: " [foo]: \n /url \n 'the title' \n\n[foo]\n\n",
// html: '<p><a href="/url" title="the title">foo</a></p>\n\n',
// },
{
index: 163,
md: `[Foo\\*bar\\]]: my_(url) "title (with parens)"\n\n[Foo\\*bar\\]]\n\n`,
html:
'<p><a href="my_(url)" title="title (with parens)">Foo*bar]</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
{
index: 164,
md: `[Foo bar]: <my url> "title"\n\n[Foo bar]\n\n`,
html: '<p><a href="my%20url" title="title">Foo bar</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
{
index: 165,
md: `[foo]: /url "\ntitle\nline1\nline2\n"\n\n[foo]\n\n`,
html: '<p><a href="/url" title="\ntitle\nline1\nline2\n">foo</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
{
index: 166,
md: "\\[foo\\]: /url 'title\n\nwith blank line'\n\n\\[foo\\]\n\n",
html:
"<p>[foo]: /url 'title</p>\n<p>with blank line'</p>\n<p>[foo]</p>\n\n",
option: {
linkStyle: 'referenced',
},
},
{
index: 167,
md: '[foo]: /url\n\n[foo]\n\n',
html: '<p><a href="/url">foo</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
{
index: 168,
md: '\\[foo\\]:\n\n\\[foo\\]\n\n',
html: '<p>[foo]:</p>\n<p>[foo]</p>\n\n',
option: {
linkStyle: 'referenced',
},
},
// {
// index: 169,
// md: '[foo]: <>\n\n[foo]\n\n',
// html: '<p><a href="">foo</a></p>\n\n',
// option: {
// linkStyle: 'referenced',
// },
// },
// {
// index: 170,
// md: '\\[foo\\]: <bar>(baz)\n\n\\[foo\\]\n\n',
// html: '<p>[foo]: <bar>(baz)</p>\n<p>[foo]</p>\n\n',
// option: {
// linkStyle: 'referenced',
// },
// },
{
index: 171,
md: '[foo]: /url\\bar\\*baz "foo\\"bar\\baz"\n\n[foo]\n\n',
html:
'<p><a href="/url%5Cbar*baz" title="foo"bar\\baz">foo</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
// {
// index: 172,
// md: '[foo]\n\n[foo]: url\n\n',
// html: '<p><a href="url">foo</a></p>\n\n',
// option: {
// linkStyle: 'referenced',
// },
// },
// {
// index: 173,
// md: '[foo]\n\n[foo]: first\n[foo]: second\n\n',
// html: '<p><a href="first">foo</a></p>\n\n',
// option: {
// linkStyle: 'referenced',
// },
// },
// {
// index: 174,
// md: '[FOO]: /url\n\n[Foo]\n\n',
// html: '<p><a href="/url">Foo</a></p>\n\n',
// option: {
// linkStyle: 'referenced',
// },
// },
// {
// index: 175,
// md: '[ΑΓΩ]: /φου\n\n[αγω]\n\n',
// html: '<p><a href="/%CF%86%CE%BF%CF%85">αγω</a></p>\n\n',
// option: {
// linkStyle: 'referenced',
// },
// },
// {
// index: 176,
// md: '[foo]: /url\n\n',
// html: '\n',
// option: {
// linkStyle: 'referenced',
// },
// },
// {
// index: 177,
// md: '[\nfoo\n]: /url\nbar\n\n',
// html: '<p>bar</p>\n\n',
// option: {
// linkStyle: 'referenced',
// },
// },
{
index: 178,
md: '\\[foo\\]: /url "title" ok\n\n',
html: '<p>[foo]: /url "title" ok</p>\n\n',
option: {
linkStyle: 'referenced',
},
},
// {
// index: 179,
// md: '[foo]: /url\n"title" ok\n\n',
// html: '<p>"title" ok</p>\n\n',
// option: {
// linkStyle: 'referenced',
// },
// },
{
index: 180,
md: ' [foo]: /url "title"\n \n\n\\[foo\\]\n\n',
html:
'<pre><code>[foo]: /url "title"\n</code></pre>\n<p>[foo]</p>\n\n',
option: {
linkStyle: 'referenced',
},
},
{
index: 181,
md: '```\n[foo]: /url\n```\n\n\\[foo\\]\n\n',
html: '<pre><code>[foo]: /url\n</code></pre>\n<p>[foo]</p>\n\n',
option: {
linkStyle: 'referenced',
codeBlockStyle: 'fenced',
},
},
{
index: 182,
md: 'Foo \\[bar\\]: /baz\n\n\\[bar\\]\n\n',
html: '<p>Foo\n[bar]: /baz</p>\n<p>[bar]</p>\n\n',
option: {
linkStyle: 'referenced',
},
},
// {
// index: 183,
// md: '# [Foo]\n[foo]: /url\n> bar\n\n',
// html:
// '<h1><a href="/url">Foo</a></h1>\n<blockquote>\n<p>bar</p>\n</blockquote>\n\n',
// option: {
// linkStyle: 'referenced',
// },
// },
{
index: 184,
md: '[foo]: /url\n\nbar\n===\n\n[foo]\n\n',
html: '<h1>bar</h1>\n<p><a href="/url">foo</a></p>\n\n',
option: {
linkStyle: 'referenced',
headingStyle: 'setext',
linkReferenceStyle: 'shortcut',
},
},
{
index: 185,
md: '[foo]: /url\n\n\\=== [foo]\n\n',
html: '<p>===\n<a href="/url">foo</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
{
index: 186,
md:
'[foo]: /foo-url "foo"\n[bar]: /bar-url "bar"\n[baz]: /baz-url\n\n[foo], [bar], [baz]\n\n',
html:
'<p><a href="/foo-url" title="foo">foo</a>,\n<a href="/bar-url" title="bar">bar</a>,\n<a href="/baz-url">baz</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
// {
// index: 187,
// md: '[foo]\n\n> [foo]: /url\n\n',
// html: '<p><a href="/url">foo</a></p>\n<blockquote>\n</blockquote>\n\n',
// option: {
// linkStyle: 'referenced',
// },
// },
// {
// index: 188,
// md: '[foo]: /url\n\n',
// html: '',
// option: {
// linkStyle: 'referenced',
// },
// },
{
index: 189,
md: 'aaa\n\nbbb\n\n',
html: '<p>aaa</p>\n<p>bbb</p>\n\n',
},
{
index: 190,
md: 'aaa bbb\n\nccc ddd\n\n',
html: '<p>aaa\nbbb</p>\n<p>ccc\nddd</p>\n\n',
},
// {
// index: 191,
// md: 'aaa\n\n\nbbb\n\n',
// html: '<p>aaa</p>\n<p>bbb</p>\n\n',
// },
{
index: 192,
md: 'aaa bbb\n\n',
html: '<p>aaa\nbbb</p>\n\n',
},
{
index: 193,
md: 'aaa bbb ccc\n\n',
html: '<p>aaa\nbbb\nccc</p>\n\n',
},
// {
// index: 194,
// md: ' aaa\nbbb\n\n',
// html: '<p>aaa\nbbb</p>\n\n',
// },
{
index: 195,
md: ' aaa\n \n\nbbb\n\n',
html: '<pre><code>aaa\n</code></pre>\n<p>bbb</p>\n\n',
},
{
index: 196,
md: 'aaa \nbbb\n\n',
html: '<p>aaa<br />\nbbb</p>\n\n',
option: {
br: ' ',
},
},
{
index: 197,
md: 'aaa\n\n# aaa\n\n\n',
html: '<p>aaa</p>\n<h1>aaa</h1>\n\n',
},
{
index: 198,
md: '| foo | bar |\n| --- | --- |\n| baz | bim |\n\n',
html:
'<table>\n<thead>\n<tr>\n<th>foo</th>\n<th>bar</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>baz</td>\n<td>bim</td>\n</tr>\n</tbody>\n</table>\n\n',
},
{
index: 199,
md: '| abc | defghi |\n| :-: | --: |\n| bar | baz |\n\n',
html:
'<table>\n<thead>\n<tr>\n<th style="text-align:center">abc</th>\n<th style="text-align:right">defghi</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style="text-align:center">bar</td>\n<td style="text-align:right">baz</td>\n</tr>\n</tbody>\n</table>\n\n',
},
{
index: 200,
md: '| f\\|oo |\n| --- |\n| b `\\|` az |\n| b **\\|** im |\n\n',
html:
'<table>\n<thead>\n<tr>\n<th>f|oo</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>b <code>\\|</code> az</td>\n</tr>\n<tr>\n<td>b <strong>|</strong> im</td>\n</tr>\n</tbody>\n</table>\n\n',
},
{
index: 201,
md: '| abc | def |\n| --- | --- |\n| bar | baz |\n\n> bar\n\n',
html:
'<table>\n<thead>\n<tr>\n<th>abc</th>\n<th>def</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>bar</td>\n<td>baz</td>\n</tr>\n</tbody>\n</table>\n<blockquote>\n<p>bar</p>\n</blockquote>\n\n',
},
// {
// index: 202,
// md: '| abc | def |\n| --- | --- |\n| bar | baz |\nbar\n\nbar\n\n',
// html:
// '<table>\n<thead>\n<tr>\n<th>abc</th>\n<th>def</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>bar</td>\n<td>baz</td>\n</tr>\n<tr>\n<td>bar</td>\n<td></td>\n</tr>\n</tbody>\n</table>\n<p>bar</p>\n\n',
// },
{
index: 203,
md: '| abc | def | | \\--- | | bar |\n\n',
html: '<p>| abc | def |\n| --- |\n| bar |</p>\n\n',
},
{
index: 204,
md: '| abc | def |\n| --- | --- |\n| bar | |\n| bar | baz |\n\n',
html:
'<table>\n<thead>\n<tr>\n<th>abc</th>\n<th>def</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>bar</td>\n<td></td>\n</tr>\n<tr>\n<td>bar</td>\n<td>baz</td>\n</tr>\n</tbody>\n</table>\n\n',
},
{
index: 205,
md: '| abc | def |\n| --- | --- |\n\n',
html:
'<table>\n<thead>\n<tr>\n<th>abc</th>\n<th>def</th>\n</tr>\n</thead><tbody></tbody>\n</table>\n\n',
},
{
index: 206,
md: '> # Foo\n> \n> bar baz\n\n',
html: '<blockquote>\n<h1>Foo</h1>\n<p>bar\nbaz</p>\n</blockquote>\n\n',
},
// {
// index: 207,
// md: '># Foo\n>bar\n> baz\n\n',
// html: '<blockquote>\n<h1>Foo</h1>\n<p>bar\nbaz</p>\n</blockquote>\n\n',
// },
// {
// index: 208,
// md: ' > # Foo\n > bar\n > baz\n\n',
// html: '<blockquote>\n<h1>Foo</h1>\n<p>bar\nbaz</p>\n</blockquote>\n\n',
// },
{
index: 209,
md: ' > # Foo\n > bar\n > baz\n\n',
html: '<pre><code>> # Foo\n> bar\n> baz</code></pre>\n\n',
},
// {
// index: 210,
// md: '> # Foo\n> bar\nbaz\n\n',
// html: '<blockquote>\n<h1>Foo</h1>\n<p>bar\nbaz</p>\n</blockquote>\n\n',
// },
{
index: 211,
md: '> bar baz foo\n\n',
html: '<blockquote>\n<p>bar\nbaz\nfoo</p>\n</blockquote>\n\n',
},
{
index: 212,
md: '> foo\n\n---\n\n',
html: '<blockquote>\n<p>foo</p>\n</blockquote>\n<hr />\n\n',
option: {
hr: '---',
},
},
{
index: 213,
md: '> - foo\n\n- bar\n\n',
html:
'<blockquote>\n<ul>\n<li>foo</li>\n</ul>\n</blockquote>\n<ul>\n<li>bar</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 214,
md: '> foo\n> \n\n bar\n\n',
html:
'<blockquote>\n<pre><code>foo\n</code></pre>\n</blockquote>\n<pre><code>bar</code></pre>\n\n',
},
// {
// index: 215,
// md: '> ```\nfoo\n```\n\n',
// html:
// '<blockquote>\n<pre><code></code></pre>\n</blockquote>\n<p>foo</p>\n<pre><code></code></pre>\n\n',
// option:{
// codeBlockStyle:'fenced'
// }
// },
{
index: 216,
md: '> foo \\- bar\n\n',
html: '<blockquote>\n<p>foo\n- bar</p>\n</blockquote>\n\n',
},
{
index: 217,
md: '>\n\n',
html: '<blockquote>\n</blockquote>\n\n',
},
// {
// index: 218,
// md: '>\n> \n> \n\n',
// html: '<blockquote>\n</blockquote>\n\n',
// },
// {
// index: 219,
// md: '>\n> foo\n> \n\n',
// html: '<blockquote>\n<p>foo</p>\n</blockquote>\n\n',
// },
{
index: 220,
md: '> foo\n\n> bar\n\n',
html:
'<blockquote>\n<p>foo</p>\n</blockquote>\n<blockquote>\n<p>bar</p>\n</blockquote>\n\n',
},
// {
// index: 221,
// md: '> foo\n> bar\n\n',
// html: '<blockquote>\n<p>foo\nbar</p>\n</blockquote>\n\n',
// },
{
index: 222,
md: '> foo\n> \n> bar\n\n',
html: '<blockquote>\n<p>foo</p>\n<p>bar</p>\n</blockquote>\n\n',
},
{
index: 223,
md: 'foo\n\n> bar\n\n',
html: '<p>foo</p>\n<blockquote>\n<p>bar</p>\n</blockquote>\n\n',
},
{
index: 224,
md: '> aaa\n\n***\n\n> bbb\n\n',
html:
'<blockquote>\n<p>aaa</p>\n</blockquote>\n<hr />\n<blockquote>\n<p>bbb</p>\n</blockquote>\n\n',
option: {
hr: '***',
},
},
// {
// index: 225,
// md: '> bar\nbaz\n\n',
// html: '<blockquote>\n<p>bar\nbaz</p>\n</blockquote>\n\n',
// },
{
index: 226,
md: '> bar\n\nbaz\n\n',
html: '<blockquote>\n<p>bar</p>\n</blockquote>\n<p>baz</p>\n\n',
},
// {
// index: 227,
// md: '> bar\n>\nbaz\n\n',
// html: '<blockquote>\n<p>bar</p>\n</blockquote>\n<p>baz</p>\n\n',
// },
{
index: 228,
md: '> > > foo bar\n\n',
html:
'<blockquote>\n<blockquote>\n<blockquote>\n<p>foo\nbar</p>\n</blockquote>\n</blockquote>\n</blockquote>\n\n',
},
{
index: 229,
md: '> > > foo bar baz\n\n',
html:
'<blockquote>\n<blockquote>\n<blockquote>\n<p>foo\nbar\nbaz</p>\n</blockquote>\n</blockquote>\n</blockquote>\n\n',
},
{
index: 230,
md: '> code\n> \n\n> not code\n\n',
html:
'<blockquote>\n<pre><code>code\n</code></pre>\n</blockquote>\n<blockquote>\n<p>not code</p>\n</blockquote>\n\n',
},
{
index: 231,
md:
'A paragraph with two lines.\n\n indented code\n \n\n> A block quote.\n\n',
html:
'<p>A paragraph\nwith two lines.</p>\n<pre><code>indented code\n</code></pre>\n<blockquote>\n<p>A block quote.</p>\n</blockquote>\n\n',
},
{
index: 232,
md:
'1. A paragraph with two lines.\n\n indented code\n \n\n > A block quote.\n\n',
html:
'<ol>\n<li>\n<p>A paragraph\nwith two lines.</p>\n<pre><code>indented code\n</code></pre>\n<blockquote>\n<p>A block quote.</p>\n</blockquote>\n</li>\n</ol>\n\n',
},
{
index: 233,
md: '- one\n\ntwo\n\n',
html: '<ul>\n<li>one</li>\n</ul>\n<p>two</p>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 234,
md: '- one\n\n two\n\n',
html: '<ul>\n<li>\n<p>one</p>\n<p>two</p>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 235,
md: ' - one\n\n two\n\n',
html: '<ul>\n<li>one</li>\n</ul>\n<pre><code> two</code></pre>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 236,
md: '- one\n\n two\n\n',
html: '<ul>\n<li>\n<p>one</p>\n<p>two</p>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 237,
md: '> > 1. one\n> > \n> > two\n\n',
html:
'<blockquote>\n<blockquote>\n<ol>\n<li>\n<p>one</p>\n<p>two</p>\n</li>\n</ol>\n</blockquote>\n</blockquote>\n\n',
},
{
index: 238,
md: '> > * one\n> > \n> > two\n\n',
html:
'<blockquote>\n<blockquote>\n<ul>\n<li>one</li>\n</ul>\n<p>two</p>\n</blockquote>\n</blockquote>\n\n',
},
{
index: 239,
md: '\\-one\n\n2.two\n\n',
html: '<p>-one</p>\n<p>2.two</p>\n\n',
},
{
index: 240,
md: '- foo\n\n bar\n\n',
html: '<ul>\n<li>\n<p>foo</p>\n<p>bar</p>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 241,
md: '1. foo\n\n ```\n bar\n ```\n\n baz\n\n > bam\n\n',
html:
'<ol>\n<li>\n<p>foo</p>\n<pre><code>bar\n</code></pre>\n<p>baz</p>\n<blockquote>\n<p>bam</p>\n</blockquote>\n</li>\n</ol>\n\n',
option: {
codeBlockStyle: 'fenced',
},
},
{
index: 242,
md: '- Foo\n\n bar\n \n \n baz\n\n',
html:
'<ul>\n<li>\n<p>Foo</p>\n<pre><code>bar\n\n\nbaz</code></pre>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 243,
md: '123456789. ok\n\n',
html: '<ol start="123456789">\n<li>ok</li>\n</ol>\n\n',
},
{
index: 244,
md: '1234567890\\. not ok\n\n',
html: '<p>1234567890. not ok</p>\n\n',
},
{
index: 245,
md: '0. ok\n\n',
html: '<ol start="0">\n<li>ok</li>\n</ol>\n\n',
},
{
index: 246,
md: '3. ok\n\n',
html: '<ol start="3">\n<li>ok</li>\n</ol>\n\n',
},
{
index: 247,
md: '\\-1. not ok\n\n',
html: '<p>-1. not ok</p>\n\n',
},
{
index: 248,
md: '- foo\n\n bar\n\n',
html:
'<ul>\n<li>\n<p>foo</p>\n<pre><code>bar</code></pre>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 249,
md: '10. foo\n\n bar\n\n',
html:
'<ol start="10">\n<li>\n<p>foo</p>\n<pre><code>bar</code></pre>\n</li>\n</ol>\n\n',
},
{
index: 250,
md: ' indented code\n \n\nparagraph\n\n more code\n\n',
html:
'<pre><code>indented code\n</code></pre>\n<p>paragraph</p>\n<pre><code>more code</code></pre>\n\n',
},
{
index: 251,
md: '1. indented code\n \n\n paragraph\n\n more code\n\n',
html:
'<ol>\n<li>\n<pre><code>indented code\n</code></pre>\n<p>paragraph</p>\n<pre><code>more code</code></pre>\n</li>\n</ol>\n\n',
},
{
index: 252,
md: '1. indented code\n \n\n paragraph\n\n more code\n\n',
html:
'<ol>\n<li>\n<pre><code> indented code\n</code></pre>\n<p>paragraph</p>\n<pre><code>more code</code></pre>\n</li>\n</ol>\n\n',
},
{
index: 253,
md: 'foo\n\nbar\n\n',
html: '<p>foo</p>\n<p>bar</p>\n\n',
},
{
index: 254,
md: '- foo\n\nbar\n\n',
html: '<ul>\n<li>foo</li>\n</ul>\n<p>bar</p>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 255,
md: '- foo\n\n bar\n\n',
html: '<ul>\n<li>\n<p>foo</p>\n<p>bar</p>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 256,
md: '- foo\n- ```\n bar\n ```\n- ```\n baz\n ```\n\n',
html:
'<ul>\n<li>foo</li>\n<li>\n<pre><code>bar\n</code></pre>\n</li>\n<li>\n<pre><code>baz\n</code></pre>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
codeBlockStyle: 'fenced',
},
},
{
index: 257,
md: '* foo\n\n',
html: '<ul>\n<li>foo</li>\n</ul>\n\n',
},
{
index: 258,
md: '- \n\nfoo\n\n',
html: '<ul>\n<li></li>\n</ul>\n<p>foo</p>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 259,
md: '- foo\n- \n- bar\n\n',
html: '<ul>\n<li>foo</li>\n<li></li>\n<li>bar</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 260,
md: '- foo\n- \n- bar\n\n',
html: '<ul>\n<li>foo</li>\n<li></li>\n<li>bar</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 261,
md: '1. foo\n2. \n3. bar\n\n',
html: '<ol>\n<li>foo</li>\n<li></li>\n<li>bar</li>\n</ol>\n\n',
},
{
index: 262,
md: '*\n\n',
html: '<ul>\n<li></li>\n</ul>\n\n',
},
{
index: 263,
md: 'foo \\*\n\nfoo 1.\n\n',
html: '<p>foo\n*</p>\n<p>foo\n1.</p>\n\n',
},
// {
// index: 264,
// md:
// ' 1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n\n',
// html:
// '<ol>\n<li>\n<p>A paragraph\nwith two lines.</p>\n<pre><code>indented code\n</code></pre>\n<blockquote>\n<p>A block quote.</p>\n</blockquote>\n</li>\n</ol>\n\n',
// },
// {
// index: 265,
// md:
// ' 1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n\n',
// html:
// '<ol>\n<li>\n<p>A paragraph\nwith two lines.</p>\n<pre><code>indented code\n</code></pre>\n<blockquote>\n<p>A block quote.</p>\n</blockquote>\n</li>\n</ol>\n\n',
// },
// {
// index: 266,
// md:
// ' 1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n\n',
// html:
// '<ol>\n<li>\n<p>A paragraph\nwith two lines.</p>\n<pre><code>indented code\n</code></pre>\n<blockquote>\n<p>A block quote.</p>\n</blockquote>\n</li>\n</ol>\n\n',
// },
{
index: 267,
md:
' 1. A paragraph\n with two lines.\n \n indented code\n \n > A block quote.\n\n',
html:
'<pre><code>1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.</code></pre>\n\n',
},
// {
// index: 268,
// md:
// ' 1. A paragraph\nwith two lines.\n\n indented code\n\n > A block quote.\n\n',
// html:
// '<ol>\n<li>\n<p>A paragraph\nwith two lines.</p>\n<pre><code>indented code\n</code></pre>\n<blockquote>\n<p>A block quote.</p>\n</blockquote>\n</li>\n</ol>\n\n',
// },
// {
// index: 269,
// md: ' 1. A paragraph\n with two lines.\n\n',
// html: '<ol>\n<li>A paragraph\nwith two lines.</li>\n</ol>\n\n',
// },
{
index: 270,
md: '> 1. > Blockquote continued here.\n\n',
html:
'<blockquote>\n<ol>\n<li>\n<blockquote>\n<p>Blockquote\ncontinued here.</p>\n</blockquote>\n</li>\n</ol>\n</blockquote>\n\n',
},
// {
// index: 271,
// md: '> 1. > Blockquote\n> continued here.\n\n',
// html:
// '<blockquote>\n<ol>\n<li>\n<blockquote>\n<p>Blockquote\ncontinued here.</p>\n</blockquote>\n</li>\n</ol>\n</blockquote>\n\n',
// },
{
index: 272,
md: '- foo\n - bar\n - baz\n - boo\n\n',
html:
'<ul>\n<li>foo\n<ul>\n<li>bar\n<ul>\n<li>baz\n<ul>\n<li>boo</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 273,
md: '- foo\n- bar\n- baz\n- boo\n\n',
html:
'<ul>\n<li>foo</li>\n<li>bar</li>\n<li>baz</li>\n<li>boo</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 274,
md: '10. foo\n - bar\n\n',
html:
'<ol start="10">\n<li>foo\n<ul>\n<li>bar</li>\n</ul>\n</li>\n</ol>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 275,
md: '10. foo\n\n- bar\n\n',
html: '<ol start="10">\n<li>foo</li>\n</ol>\n<ul>\n<li>bar</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 276,
md: '- - foo\n\n',
html: '<ul>\n<li>\n<ul>\n<li>foo</li>\n</ul>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 277,
md: '1. - 2. foo\n\n',
html:
'<ol>\n<li>\n<ul>\n<li>\n<ol start="2">\n<li>foo</li>\n</ol>\n</li>\n</ul>\n</li>\n</ol>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 278,
md: '- Foo\n ===\n- Bar\n ---\n\n baz\n\n',
html:
'<ul>\n<li>\n<h1>Foo</h1>\n</li>\n<li>\n<h2>Bar</h2>\n<p>baz</p></li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
headingStyle: 'setext',
},
},
{
index: 279,
md: '- [ ] foo\n- [x] bar\n\n',
html:
'<ul>\n<li><input disabled="" type="checkbox"> foo</li>\n<li><input checked="" disabled="" type="checkbox"> bar</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 280,
md: '- [x] foo\n - [ ] bar\n - [x] baz\n- [ ] bim\n\n',
html:
'<ul>\n<li><input checked="" disabled="" type="checkbox"> foo\n<ul>\n<li><input disabled="" type="checkbox"> bar</li>\n<li><input checked="" disabled="" type="checkbox"> baz</li>\n</ul>\n</li>\n<li><input disabled="" type="checkbox"> bim</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 281,
md: '- foo\n- bar\n\n+ baz\n\n',
html:
'<ul>\n<li>foo</li>\n<li>bar</li>\n</ul>\n<ul>\n<li>baz</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 282,
md: '1. foo\n2. bar\n\n3) baz\n\n',
html:
'<ol>\n<li>foo</li>\n<li>bar</li>\n</ol>\n<ol start="3">\n<li>baz</li>\n</ol>\n\n',
},
{
index: 283,
md: 'Foo\n\n- bar\n- baz\n\n',
html: '<p>Foo</p>\n<ul>\n<li>bar</li>\n<li>baz</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 284,
md:
'The number of windows in my house is 14. The number of doors is 6.\n\n',
html:
'<p>The number of windows in my house is\n14. The number of doors is 6.</p>\n\n',
},
{
index: 285,
md:
'The number of windows in my house is\n\n1. The number of doors is 6.\n\n',
html:
'<p>The number of windows in my house is</p>\n<ol>\n<li>The number of doors is 6.</li>\n</ol>\n\n',
},
{
index: 286,
md: '- foo\n\n- bar\n\n- baz\n\n',
html:
'<ul>\n<li>\n<p>foo</p>\n</li>\n<li>\n<p>bar</p>\n</li>\n<li>\n<p>baz</p>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 287,
md: '- foo\n - bar\n - baz\n\n bim\n\n',
html:
'<ul>\n<li>foo\n<ul>\n<li>bar\n<ul>\n<li>\n<p>baz</p>\n<p>bim</p>\n</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 288,
md: '- foo\n- bar\n\n<!-- -->\n\n- baz\n- bim\n\n',
html:
'<ul>\n<li>foo</li>\n<li>bar</li>\n</ul>\n<!-- -->\n<ul>\n<li>baz</li>\n<li>bim</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 289,
md: '- foo\n\n notcode\n\n- foo\n\n<!-- -->\n\n code\n\n',
html:
'<ul>\n<li>\n<p>foo</p>\n<p>notcode</p>\n</li>\n<li>\n<p>foo</p>\n</li>\n</ul>\n<!-- -->\n<pre><code>code</code></pre>\n\n',
option: {
bulletListMarker: '-',
},
},
// Info:没有必要测
// {
// index: 290,
// md: '- a\n - b\n - c\n - d\n - e\n - f\n- g\n\n',
// html:
// '<ul>\n<li>a</li>\n<li>b</li>\n<li>c</li>\n<li>d</li>\n<li>e</li>\n<li>f</li>\n<li>g</li>\n</ul>\n\n',
// option: {
// bulletListMarker: '-',
// },
// },
// {
// index: 291,
// md: '1. a\n\n 2. b\n\n 3. c\n\n',
// html:
// '<ol>\n<li>\n<p>a</p>\n</li>\n<li>\n<p>b</p>\n</li>\n<li>\n<p>c</p>\n</li>\n</ol>\n\n',
// },
// {
// index: 292,
// md: '- a\n - b\n - c\n - d\n - e\n\n',
// html:
// '<ul>\n<li>a</li>\n<li>b</li>\n<li>c</li>\n<li>d\n- e</li>\n</ul>\n\n',
// option: {
// bulletListMarker: '-',
// },
// },
{
index: 293,
md: '1. a\n\n 2. b\n\n 3. c\n\n',
html:
'<ol>\n<li>\n<p>a</p>\n</li>\n<li>\n<p>b</p>\n</li>\n</ol>\n<pre><code>3. c</code></pre>\n\n',
},
{
index: 294,
md: '- a\n\n- b\n\n- c\n\n',
html:
'<ul>\n<li>\n<p>a</p>\n</li>\n<li>\n<p>b</p>\n</li>\n<li>\n<p>c</p>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 295,
md: '* a\n\n* \n* c\n\n',
html:
'<ul>\n<li>\n<p>a</p>\n</li>\n<li></li>\n<li>\n<p>c</p>\n</li>\n</ul>\n\n',
},
{
index: 296,
md: '- a\n\n- b\n\n c\n\n- d\n\n',
html:
'<ul>\n<li>\n<p>a</p>\n</li>\n<li>\n<p>b</p>\n<p>c</p>\n</li>\n<li>\n<p>d</p>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
// {
// index: 297,
// md: '- a\n- b\n\n [ref]: /url\n- d\n\n',
// html:
// '<ul>\n<li>\n<p>a</p>\n</li>\n<li>\n<p>b</p>\n</li>\n<li>\n<p>d</p>\n</li>\n</ul>\n\n',
// },
{
index: 298,
md: '- a\n- ```\n b\n\n\n ```\n- c\n\n',
html:
'<ul>\n<li>a</li>\n<li>\n<pre><code>b\n\n\n</code></pre>\n</li>\n<li>c</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
codeBlockStyle: 'fenced',
},
},
{
index: 299,
md: '- a\n - b\n\n c\n- d\n\n',
html:
'<ul>\n<li>a\n<ul>\n<li>\n<p>b</p>\n<p>c</p>\n</li>\n</ul>\n</li>\n<li>d</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 300,
md: '* a\n > b\n* c\n\n',
html:
'<ul>\n<li>a\n<blockquote>\n<p>b</p>\n</blockquote>\n</li>\n<li>c</li>\n</ul>\n\n',
},
{
index: 301,
md: '- a\n > b\n ```\n c\n ```\n- d\n\n',
html:
'<ul>\n<li>a\n<blockquote>\n<p>b</p>\n</blockquote>\n<pre><code>c\n</code></pre>\n</li>\n<li>d</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
codeBlockStyle: 'fenced',
},
},
{
index: 302,
md: '- a\n\n',
html: '<ul>\n<li>a</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 303,
md: '- a\n - b\n\n',
html: '<ul>\n<li>a\n<ul>\n<li>b</li>\n</ul>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 304,
md: '1. ```\n foo\n ```\n\n bar\n\n',
html:
'<ol>\n<li>\n<pre><code>foo\n</code></pre>\n<p>bar</p>\n</li>\n</ol>\n\n',
option: {
codeBlockStyle: 'fenced',
},
},
{
index: 305,
md: '* foo\n\n * bar\n\n baz\n\n',
html:
'<ul>\n<li>\n<p>foo</p>\n<ul>\n<li>bar</li>\n</ul>\n<p>baz</p>\n</li>\n</ul>\n\n',
},
{
index: 306,
md: '- a\n\n - b\n - c\n\n- d\n\n - e\n - f\n\n',
html:
'<ul>\n<li>\n<p>a</p>\n<ul>\n<li>b</li>\n<li>c</li>\n</ul>\n</li>\n<li>\n<p>d</p>\n<ul>\n<li>e</li>\n<li>f</li>\n</ul>\n</li>\n</ul>\n\n',
option: {
bulletListMarker: '-',
},
},
{
index: 307,
md: '`hi`lo\\`\n\n',
html: '<p><code>hi</code>lo`</p>\n\n',
},
{
index: 308,
md:
'\\!"#\\$\\%\\&\'\\(\\)\\*+,-./:;\\<=>\\?\\@\\[\\\\\\]\\^\\_\\`\\{|\\}\\~\n\n',
html: "<p>!"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~</p>\n\n",
},
{
index: 309,
md: '\\\\ \\\\A\\\\a\\\\ \\\\3\\\\φ\\\\«\n\n',
html: '<p>\\→\\A\\a\\ \\3\\φ\\«</p>\n\n',
},
{
index: 310,
md:
'\\*not emphasized\\* \\<br/> not a tag \\[not a link\\]\\(/foo\\) \\`not code\\` 1. not a list \\* not a list # not a heading \\[foo\\]: /url "not a reference" \\ö not a character entity\n\n',
html:
'<p>*not emphasized*\n<br/> not a tag\n[not a link](/foo)\n`not code`\n1. not a list\n* not a list\n# not a heading\n[foo]: /url "not a reference"\n&ouml; not a character entity</p>\n\n',
},
{
index: 311,
md: '\\\\*emphasis*\n\n',
html: '<p>\\<em>emphasis</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 312,
md: 'foo \nbar\n\n',
html: '<p>foo<br />\nbar</p>\n\n',
},
{
index: 313,
md: '``\\[\\` ``\n\n',
html: '<p><code>\\[\\`</code></p>\n\n',
},
{
index: 314,
md: ' \\[\\]\n\n',
html: '<pre><code>\\[\\]</code></pre>\n\n',
},
{
index: 315,
md: '~~~\n\\[\\]\n~~~\n\n',
html: '<pre><code>\\[\\]\n</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
fence: '~~~',
},
},
{
index: 316,
md: '<http://example.com?find=\\*>\n\n',
html:
'<p><a href="http://example.com?find=%5C*">http://example.com?find=\\*</a></p>\n\n',
},
// {
// index: 317,
// md: '<a href="/bar\\/)">\n\n',
// html: '<a href="/bar\\/)">\n\n',
// },
{
index: 318,
md: '[foo](/bar* "ti*tle")\n\n',
html: '<p><a href="/bar*" title="ti*tle">foo</a></p>\n\n',
},
{
index: 319,
md: '[foo]: /bar\\* "ti\\*tle"\n\n[foo]\n\n',
html: '<p><a href="/bar*" title="ti*tle">foo</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
{
index: 320,
md: '```foo+bar\nfoo\n```\n\n',
html: '<pre><code class="language-foo+bar">foo\n</code></pre>\n\n',
option: {
codeBlockStyle: 'fenced',
},
},
// {
// index: 321,
// md:
// ' & © Æ Ď\n¾ ℋ ⅆ\n∲ ≧̸\n\n',
// html: '<p> & © Æ Ď\n¾ ℋ ⅆ\n∲ ≧̸</p>\n\n',
// },
// {
// index: 322,
// md: '# Ӓ Ϡ �\n\n',
// html: '<p># Ӓ Ϡ �</p>\n\n',
// },
// {
// index: 323,
// md: '" ആ ಫ\n\n',
// html: '<p>" ആ ಫ</p>\n\n',
// },
// {
// index: 324,
// md:
// '  &x; &#; &#x;\n�\n&#abcdef0;\n&ThisIsNotDefined; &hi?;\n\n',
// html:
// '<p>&nbsp &x; &#; &#x;\n&#87654321;\n&#abcdef0;\n&ThisIsNotDefined; &hi?;</p>\n\n',
// },
// {
// index: 325,
// md: '©\n\n',
// html: '<p>&copy</p>\n\n',
// },
// {
// index: 326,
// md: '&MadeUpEntity;\n\n',
// html: '<p>&MadeUpEntity;</p>\n\n',
// },
// {
// index: 327,
// md: '<a href="öö.html">\n\n',
// html: '<a href="öö.html">\n\n',
// },
// {
// index: 328,
// md: '[foo](/föö "föö")\n\n',
// html: '<p><a href="/f%C3%B6%C3%B6" title="föö">foo</a></p>\n\n',
// },
// {
// index: 329,
// md: '[foo]\n\n[foo]: /föö "föö"\n\n',
// html: '<p><a href="/f%C3%B6%C3%B6" title="föö">foo</a></p>\n\n',
// },
// {
// index: 330,
// md: '``` föö\nfoo\n```\n\n',
// html: '<pre><code class="language-föö">foo\n</code></pre>\n\n',
// },
{
index: 331,
md: '`föö`\n\n',
html: '<p><code>f&ouml;&ouml;</code></p>\n\n',
},
// {
// index: 332,
// md: ' föfö\n\n',
// html: '<pre><code>f&ouml;f&ouml;\n</code></pre>\n\n',
// },
// {
// index: 333,
// md: '*foo*\n*foo*\n\n',
// html: '<p>*foo*\n<em>foo</em></p>\n\n',
// },
// {
// index: 334,
// md: '* foo\n\n* foo\n\n',
// html: '<p>* foo</p>\n<ul>\n<li>foo</li>\n</ul>\n\n',
// },
// {
// index: 335,
// md: 'foo bar\n\n',
// html: '<p>foo\n\nbar</p>\n\n',
// },
// {
// index: 336,
// md: '	foo\n\n',
// html: '<p>→foo</p>\n\n',
// },
// {
// index: 337,
// md: '[a](url "tit")\n\n',
// html: '<p>[a](url "tit")</p>\n\n',
// },
{
index: 338,
md: '`foo`\n\n',
html: '<p><code>foo</code></p>\n\n',
},
{
index: 339,
md: '``foo ` bar``\n\n',
html: '<p><code>foo ` bar</code></p>\n\n',
},
{
index: 340,
md: '` `` `\n\n',
html: '<p><code>``</code></p>\n\n',
},
{
index: 341,
md: '` `` `\n\n',
html: '<p><code> `` </code></p>\n\n',
},
{
index: 342,
md: '`a`\n\n',
html: '<p><code> a</code></p>\n\n',
},
{
index: 343,
md: '` b `\n\n',
html: '<p><code> b </code></p>\n\n',
},
{
index: 344,
md: '` `\n` `\n\n',
html: '<p><code> </code>\n<code></code></p>\n\n',
},
{
index: 345,
md: '`foo bar baz`\n\n',
html: '<p><code>foo bar baz</code></p>\n\n',
},
// {
// index: 346,
// md: '``\nfoo \n``\n\n',
// html: '<p><code>foo </code></p>\n\n',
// },
{
index: 347,
md: '`foo bar baz`\n\n',
html: '<p><code>foo bar baz</code></p>\n\n',
},
{
index: 348,
md: '`foo\\`bar\\`\n\n',
html: '<p><code>foo\\</code>bar`</p>\n\n',
},
{
index: 349,
md: '``foo`bar``\n\n',
html: '<p><code>foo`bar</code></p>\n\n',
},
{
index: 350,
md: '`foo `` bar`\n\n',
html: '<p><code>foo `` bar</code></p>\n\n',
},
{
index: 351,
md: '\\*foo`*`\n\n',
html: '<p>*foo<code>*</code></p>\n\n',
},
{
index: 352,
md: '\\[not a `link](/foo`\\)\n\n',
html: '<p>[not a <code>link](/foo</code>)</p>\n\n',
},
{
index: 353,
md: '`<a href="`">\\`\n\n',
html: '<p><code><a href="</code>">`</p>\n\n',
},
// {
// index: 354,
// md: '<a href="`">`\n\n',
// html: '<p><a href="`">`</p>\n\n',
// },
{
index: 355,
md: '`<http://foo.bar.`baz>\\`\n\n',
html: '<p><code><http://foo.bar.</code>baz>`</p>\n\n',
},
{
index: 356,
md: '<http://foo.bar.`baz>\\`\n\n',
html: '<p><a href="http://foo.bar.%60baz">http://foo.bar.`baz</a>`</p>\n\n',
},
{
index: 357,
md: '\\`\\`\\`foo\\`\\`\n\n',
html: '<p>```foo``</p>\n\n',
},
{
index: 358,
md: '\\`foo\n\n',
html: '<p>`foo</p>\n\n',
},
{
index: 359,
md: '\\`foo`bar`\n\n',
html: '<p>`foo<code>bar</code></p>\n\n',
},
{
index: 360,
md: '*foo bar*\n\n',
html: '<p><em>foo bar</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 361,
md: 'a \\* foo bar\\*\n\n',
html: '<p>a * foo bar*</p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 362,
md: 'a\\*"foo"\\*\n\n',
html: '<p>a*"foo"*</p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 363,
md: '\\* a \\*\n\n',
html: '<p>* a *</p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 364,
md: 'foo*bar*\n\n',
html: '<p>foo<em>bar</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 365,
md: '5*6*78\n\n',
html: '<p>5<em>6</em>78</p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 366,
md: '_foo bar_\n\n',
html: '<p><em>foo bar</em></p>\n\n',
},
{
index: 367,
md: '\\_ foo bar\\_\n\n',
html: '<p>_ foo bar_</p>\n\n',
},
{
index: 368,
md: 'a\\_"foo"\\_\n\n',
html: '<p>a_"foo"_</p>\n\n',
},
{
index: 369,
md: 'foo\\_bar\\_\n\n',
html: '<p>foo_bar_</p>\n\n',
},
{
index: 370,
md: '5\\_6\\_78\n\n',
html: '<p>5_6_78</p>\n\n',
},
{
index: 371,
md: 'пристаням\\_стремятся\\_\n\n',
html: '<p>пристаням_стремятся_</p>\n\n',
},
{
index: 372,
md: 'aa\\_"bb"\\_cc\n\n',
html: '<p>aa_"bb"_cc</p>\n\n',
},
{
index: 373,
md: 'foo-_\\(bar\\)_\n\n',
html: '<p>foo-<em>(bar)</em></p>\n\n',
},
{
index: 374,
md: '\\_foo\\*\n\n',
html: '<p>_foo*</p>\n\n',
},
{
index: 375,
md: '\\*foo bar \\*\n\n',
html: '<p>*foo bar *</p>\n\n',
},
{
index: 376,
md: '\\*foo bar \\*\n\n',
html: '<p>*foo bar\n*</p>\n\n',
},
{
index: 377,
md: '\\*\\(\\*foo\\)\n\n',
html: '<p>*(*foo)</p>\n\n',
},
{
index: 378,
md: '*\\(*foo*\\)*\n\n',
html: '<p><em>(<em>foo</em>)</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 379,
md: '*foo*bar\n\n',
html: '<p><em>foo</em>bar</p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 380,
md: '\\_foo bar \\_\n\n',
html: '<p>_foo bar _</p>\n\n',
},
{
index: 381,
md: '\\_\\(\\_foo\\)\n\n',
html: '<p>_(_foo)</p>\n\n',
},
{
index: 382,
md: '_\\(_foo_\\)_\n\n',
html: '<p><em>(<em>foo</em>)</em></p>\n\n',
},
{
index: 383,
md: '\\_foo\\_bar\n\n',
html: '<p>_foo_bar</p>\n\n',
},
{
index: 384,
md: '\\_пристаням\\_стремятся\n\n',
html: '<p>_пристаням_стремятся</p>\n\n',
},
{
index: 385,
md: '_foo\\_bar\\_baz_\n\n',
html: '<p><em>foo_bar_baz</em></p>\n\n',
},
{
index: 386,
md: '_\\(bar\\)_.\n\n',
html: '<p><em>(bar)</em>.</p>\n\n',
},
{
index: 387,
md: '**foo bar**\n\n',
html: '<p><strong>foo bar</strong></p>\n\n',
},
{
index: 388,
md: '\\*\\* foo bar\\*\\*\n\n',
html: '<p>** foo bar**</p>\n\n',
},
{
index: 389,
md: 'a\\*\\*"foo"\\*\\*\n\n',
html: '<p>a**"foo"**</p>\n\n',
},
{
index: 390,
md: 'foo**bar**\n\n',
html: '<p>foo<strong>bar</strong></p>\n\n',
},
{
index: 391,
md: '__foo bar__\n\n',
html: '<p><strong>foo bar</strong></p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 392,
md: '\\_\\_ foo bar\\_\\_\n\n',
html: '<p>__ foo bar__</p>\n\n',
},
{
index: 393,
md: '\\_\\_ foo bar\\_\\_\n\n',
html: '<p>__\nfoo bar__</p>\n\n',
},
{
index: 394,
md: 'a\\_\\_"foo"\\_\\_\n\n',
html: '<p>a__"foo"__</p>\n\n',
},
{
index: 395,
md: 'foo\\_\\_bar\\_\\_\n\n',
html: '<p>foo__bar__</p>\n\n',
},
{
index: 396,
md: '5\\_\\_6\\_\\_78\n\n',
html: '<p>5__6__78</p>\n\n',
},
{
index: 397,
md: 'пристаням\\_\\_стремятся\\_\\_\n\n',
html: '<p>пристаням__стремятся__</p>\n\n',
},
{
index: 398,
md: '__foo, __bar__, baz__\n\n',
html: '<p><strong>foo, <strong>bar</strong>, baz</strong></p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 399,
md: 'foo-__\\(bar\\)__\n\n',
html: '<p>foo-<strong>(bar)</strong></p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 400,
md: '\\*\\*foo bar \\*\\*\n\n',
html: '<p>**foo bar **</p>\n\n',
},
{
index: 401,
md: '\\*\\*\\(\\*\\*foo\\)\n\n',
html: '<p>**(**foo)</p>\n\n',
},
{
index: 402,
md: '*\\(**foo**\\)*\n\n',
html: '<p><em>(<strong>foo</strong>)</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 403,
md:
'**Gomphocarpus \\(*Gomphocarpus physocarpus*, syn. *Asclepias physocarpa*\\)**\n\n',
html:
'<p><strong>Gomphocarpus (<em>Gomphocarpus physocarpus</em>, syn.\n<em>Asclepias physocarpa</em>)</strong></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 404,
md: '**foo "*bar*" foo**\n\n',
html: '<p><strong>foo "<em>bar</em>" foo</strong></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 405,
md: '**foo**bar\n\n',
html: '<p><strong>foo</strong>bar</p>\n\n',
},
{
index: 406,
md: '\\_\\_foo bar \\_\\_\n\n',
html: '<p>__foo bar __</p>\n\n',
},
{
index: 407,
md: '\\_\\_\\(\\_\\_foo\\)\n\n',
html: '<p>__(__foo)</p>\n\n',
},
{
index: 408,
md: '_\\(__foo__\\)_\n\n',
html: '<p><em>(<strong>foo</strong>)</em></p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 409,
md: '\\_\\_foo\\_\\_bar\n\n',
html: '<p>__foo__bar</p>\n\n',
},
{
index: 410,
md: '\\_\\_пристаням\\_\\_стремятся\n\n',
html: '<p>__пристаням__стремятся</p>\n\n',
},
{
index: 411,
md: '__foo\\_\\_bar\\_\\_baz__\n\n',
html: '<p><strong>foo__bar__baz</strong></p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 412,
md: '__\\(bar\\)__.\n\n',
html: '<p><strong>(bar)</strong>.</p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 413,
md: '*foo [bar](/url)*\n\n',
html: '<p><em>foo <a href="/url">bar</a></em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 414,
md: '*foo bar*\n\n',
html: '<p><em>foo\nbar</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 415,
md: '_foo __bar__ baz_\n\n',
html: '<p><em>foo <strong>bar</strong> baz</em></p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 416,
md: '_foo _bar_ baz_\n\n',
html: '<p><em>foo <em>bar</em> baz</em></p>\n\n',
},
{
index: 417,
md: '__foo_ bar_\n\n',
html: '<p><em><em>foo</em> bar</em></p>\n\n',
},
{
index: 418,
md: '*foo *bar**\n\n',
html: '<p><em>foo <em>bar</em></em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 419,
md: '*foo **bar** baz*\n\n',
html: '<p><em>foo <strong>bar</strong> baz</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 420,
md: '*foo**bar**baz*\n\n',
html: '<p><em>foo<strong>bar</strong>baz</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 421,
md: '*foo\\*\\*bar*\n\n',
html: '<p><em>foo**bar</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 422,
md: '***foo** bar*\n\n',
html: '<p><em><strong>foo</strong> bar</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 423,
md: '*foo **bar***\n\n',
html: '<p><em>foo <strong>bar</strong></em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 424,
md: '*foo**bar***\n\n',
html: '<p><em>foo<strong>bar</strong></em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 425,
md: 'foo***bar***baz\n\n',
html: '<p>foo<em><strong>bar</strong></em>baz</p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 426,
md: 'foo******bar******\\*\\*\\*baz\n\n',
html:
'<p>foo<strong><strong><strong>bar</strong></strong></strong>***baz</p>\n\n',
},
{
index: 427,
md: '*foo **bar *baz* bim** bop*\n\n',
html: '<p><em>foo <strong>bar <em>baz</em> bim</strong> bop</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 428,
md: '*foo [*bar*](/url)*\n\n',
html: '<p><em>foo <a href="/url"><em>bar</em></a></em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 429,
md: '\\*\\* is not an empty emphasis\n\n',
html: '<p>** is not an empty emphasis</p>\n\n',
},
{
index: 430,
md: '\\*\\*\\*\\* is not an empty strong emphasis\n\n',
html: '<p>**** is not an empty strong emphasis</p>\n\n',
},
{
index: 431,
md: '**foo [bar](/url)**\n\n',
html: '<p><strong>foo <a href="/url">bar</a></strong></p>\n\n',
},
{
index: 432,
md: '**foo bar**\n\n',
html: '<p><strong>foo\nbar</strong></p>\n\n',
},
{
index: 433,
md: '__foo _bar_ baz__\n\n',
html: '<p><strong>foo <em>bar</em> baz</strong></p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 434,
md: '__foo __bar__ baz__\n\n',
html: '<p><strong>foo <strong>bar</strong> baz</strong></p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 435,
md: '____foo__ bar__\n\n',
html: '<p><strong><strong>foo</strong> bar</strong></p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 436,
md: '**foo **bar****\n\n',
html: '<p><strong>foo <strong>bar</strong></strong></p>\n\n',
},
{
index: 437,
md: '**foo *bar* baz**\n\n',
html: '<p><strong>foo <em>bar</em> baz</strong></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 438,
md: '**foo*bar*baz**\n\n',
html: '<p><strong>foo<em>bar</em>baz</strong></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 439,
md: '***foo* bar**\n\n',
html: '<p><strong><em>foo</em> bar</strong></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 440,
md: '**foo *bar***\n\n',
html: '<p><strong>foo <em>bar</em></strong></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 441,
md: '**foo *bar **baz** bim* bop**\n\n',
html:
'<p><strong>foo <em>bar <strong>baz</strong>\nbim</em> bop</strong></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 442,
md: '**foo [*bar*](/url)**\n\n',
html: '<p><strong>foo <a href="/url"><em>bar</em></a></strong></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 443,
md: '\\_\\_ is not an empty emphasis\n\n',
html: '<p>__ is not an empty emphasis</p>\n\n',
},
{
index: 444,
md: '\\_\\_\\_\\_ is not an empty strong emphasis\n\n',
html: '<p>____ is not an empty strong emphasis</p>\n\n',
},
{
index: 445,
md: 'foo \\*\\*\\*\n\n',
html: '<p>foo ***</p>\n\n',
},
{
index: 446,
md: 'foo *\\**\n\n',
html: '<p>foo <em>*</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 447,
md: 'foo *\\_*\n\n',
html: '<p>foo <em>_</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 448,
md: 'foo \\*\\*\\*\\*\\*\n\n',
html: '<p>foo *****</p>\n\n',
},
{
index: 449,
md: 'foo **\\***\n\n',
html: '<p>foo <strong>*</strong></p>\n\n',
},
{
index: 450,
md: 'foo **\\_**\n\n',
html: '<p>foo <strong>_</strong></p>\n\n',
},
{
index: 451,
md: '\\**foo*\n\n',
html: '<p>*<em>foo</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 452,
md: '*foo*\\*\n\n',
html: '<p><em>foo</em>*</p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 453,
md: '\\***foo**\n\n',
html: '<p>*<strong>foo</strong></p>\n\n',
},
{
index: 454,
md: '\\*\\*\\**foo*\n\n',
html: '<p>***<em>foo</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 455,
md: '**foo**\\*\n\n',
html: '<p><strong>foo</strong>*</p>\n\n',
},
{
index: 456,
md: '*foo*\\*\\*\\*\n\n',
html: '<p><em>foo</em>***</p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 457,
md: 'foo \\_\\_\\_\n\n',
html: '<p>foo ___</p>\n\n',
},
{
index: 458,
md: 'foo _\\__\n\n',
html: '<p>foo <em>_</em></p>\n\n',
},
{
index: 459,
md: 'foo _\\*_\n\n',
html: '<p>foo <em>*</em></p>\n\n',
},
{
index: 460,
md: 'foo \\_\\_\\_\\_\\_\n\n',
html: '<p>foo _____</p>\n\n',
},
{
index: 461,
md: 'foo __\\___\n\n',
html: '<p>foo <strong>_</strong></p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 462,
md: 'foo __\\*__\n\n',
html: '<p>foo <strong>*</strong></p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 463,
md: '\\__foo_\n\n',
html: '<p>_<em>foo</em></p>\n\n',
},
{
index: 464,
md: '_foo_\\_\n\n',
html: '<p><em>foo</em>_</p>\n\n',
},
{
index: 465,
md: '\\___foo__\n\n',
html: '<p>_<strong>foo</strong></p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 466,
md: '\\_\\_\\__foo_\n\n',
html: '<p>___<em>foo</em></p>\n\n',
},
{
index: 467,
md: '__foo__\\_\n\n',
html: '<p><strong>foo</strong>_</p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 468,
md: '_foo_\\_\\_\\_\n\n',
html: '<p><em>foo</em>___</p>\n\n',
},
{
index: 469,
md: '**foo**\n\n',
html: '<p><strong>foo</strong></p>\n\n',
},
{
index: 470,
md: '*_foo_*\n\n',
html: '<p><em><em>foo</em></em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 471,
md: '__foo__\n\n',
html: '<p><strong>foo</strong></p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 472,
md: '_*foo*_\n\n',
html: '<p><em><em>foo</em></em></p>\n\n',
},
{
index: 473,
md: '****foo****\n\n',
html: '<p><strong><strong>foo</strong></strong></p>\n\n',
},
{
index: 474,
md: '____foo____\n\n',
html: '<p><strong><strong>foo</strong></strong></p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 475,
md: '******foo******\n\n',
html: '<p><strong><strong><strong>foo</strong></strong></strong></p>\n\n',
},
{
index: 476,
md: '***foo***\n\n',
html: '<p><em><strong>foo</strong></em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 477,
md: '_____foo_____\n\n',
html: '<p><em><strong><strong>foo</strong></strong></em></p>\n\n',
option: {
strongDelimiter: '__',
},
},
{
index: 478,
md: '*foo \\_bar* baz\\_\n\n',
html: '<p><em>foo _bar</em> baz_</p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 479,
md: '*foo __bar \\*baz bim__ bam*\n\n',
html: '<p><em>foo <strong>bar *baz bim</strong> bam</em></p>\n\n',
option: {
emDelimiter: '*',
strongDelimiter: '__',
},
},
{
index: 480,
md: '\\*\\*foo **bar baz**\n\n',
html: '<p>**foo <strong>bar baz</strong></p>\n\n',
},
{
index: 481,
md: '\\*foo *bar baz*\n\n',
html: '<p>*foo <em>bar baz</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 482,
md: '\\*[bar\\*](/url)\n\n',
html: '<p>*<a href="/url">bar*</a></p>\n\n',
},
{
index: 483,
md: '\\_foo [bar\\_](/url)\n\n',
html: '<p>_foo <a href="/url">bar_</a></p>\n\n',
},
{
index: 484,
md: '\\*\n\n',
html: '<p>*<img src="foo" alt="" title="*"/></p>\n\n',
},
// {
// index: 485,
// md: '\\*\\*<a href="**">\n\n',
// html: '<p>**<a href="**"></p>\n\n',
// },
// {
// index: 486,
// md: '\\_\\_<a href="__">\n\n',
// html: '<p>__<a href="__"></p>\n\n',
// },
{
index: 487,
md: '*a `*`*\n\n',
html: '<p><em>a <code>*</code></em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 488,
md: '_a `_`_\n\n',
html: '<p><em>a <code>_</code></em></p>\n\n',
},
{
index: 489,
md: '\\*\\*a<http://foo.bar/?q=**>\n\n',
html:
'<p>**a<a href="http://foo.bar/?q=**">http://foo.bar/?q=**</a></p>\n\n',
},
{
index: 490,
md: '\\_\\_a<http://foo.bar/?q=__>\n\n',
html:
'<p>__a<a href="http://foo.bar/?q=__">http://foo.bar/?q=__</a></p>\n\n',
},
{
index: 491,
md: '~~Hi~~ Hello, world\\!\n\n',
html: '<p><s>Hi</s> Hello, world!</p>\n\n',
},
{
index: 492,
md: 'This \\~\\~has a\n\nnew paragraph\\~\\~.\n\n',
html: '<p>This ~~has a</p>\n<p>new paragraph~~.</p>\n\n',
},
{
index: 493,
md: '[link](/uri "title")\n\n',
html: '<p><a href="/uri" title="title">link</a></p>\n\n',
},
{
index: 494,
md: '[link](/uri)\n\n',
html: '<p><a href="/uri">link</a></p>\n\n',
},
{
index: 495,
md: '[link]()\n\n',
html: '<p><a href="">link</a></p>\n\n',
},
// {
// index: 496,
// md: '[link](<>)\n\n',
// html: '<p><a href="">link</a></p>\n\n',
// },
{
index: 497,
md: '\\[link\\]\\(/my uri\\)\n\n',
html: '<p>[link](/my uri)</p>\n\n',
},
{
index: 498,
md: '[link](</my uri>)\n\n',
html: '<p><a href="/my%20uri">link</a></p>\n\n',
},
{
index: 499,
md: '\\[link\\]\\(foo bar\\)\n\n',
html: '<p>[link](foo\nbar)</p>\n\n',
},
// {
// index: 500,
// md: '[link](<foo\nbar>)\n\n',
// html: '<p>[link](<foo\nbar>)</p>\n\n',
// },
{
index: 501,
md: '[a](<b)c>)\n\n',
html: '<p><a href="b)c">a</a></p>\n\n',
},
{
index: 502,
md: '\\[link\\]\\(\\<foo>\\)\n\n',
html: '<p>[link](<foo>)</p>\n\n',
},
// {
// index: 503,
// md: '[a](<b)c\n[a](<b)c>\n[a](<b>c)\n\n',
// html: '<p>[a](<b)c\n[a](<b)c>\n[a](<b>c)</p>\n\n',
// },
{
index: 504,
md: '[link](<(foo)>)\n\n',
html: '<p><a href="(foo)">link</a></p>\n\n',
},
{
index: 505,
md: '[link](<foo(and(bar))>)\n\n',
html: '<p><a href="foo(and(bar))">link</a></p>\n\n',
},
{
index: 506,
md: '[link](<foo(and(bar)>)\n\n',
html: '<p><a href="foo(and(bar)">link</a></p>\n\n',
},
{
index: 507,
md: '[link](<foo(and(bar)>)\n\n',
html: '<p><a href="foo(and(bar)">link</a></p>\n\n',
},
{
index: 508,
md: '[link](<foo):>)\n\n',
html: '<p><a href="foo):">link</a></p>\n\n',
},
{
index: 509,
md:
'[link](#fragment)\n\n[link](http://example.com#fragment)\n\n[link](http://example.com?foo=3#frag)\n\n',
html:
'<p><a href="#fragment">link</a></p>\n<p><a href="http://example.com#fragment">link</a></p>\n<p><a href="http://example.com?foo=3#frag">link</a></p>\n\n',
},
{
index: 510,
md: '[link](<foo\\bar>)\n\n',
html: '<p><a href="foo%5Cbar">link</a></p>\n\n',
},
{
index: 511,
md: '[link](<foo bä>)\n\n',
html: '<p><a href="foo%20b%C3%A4">link</a></p>\n\n',
},
{
index: 512,
md: '[link](<"title">)\n\n',
html: '<p><a href="%22title%22">link</a></p>\n\n',
},
// {
// index: 513,
// md:
// '[link](/url "title") [link](/url \'title\') [link](/url (title))\n\n',
// html:
// '<p><a href="/url" title="title">link</a>\n<a href="/url" title="title">link</a>\n<a href="/url" title="title">link</a></p>\n\n',
// },
{
index: 514,
md: '[link](/url "title """)\n\n',
html: '<p><a href="/url" title="title """>link</a></p>\n\n',
},
{
index: 515,
md: '[link](</url "title">)\n\n',
html: '<p><a href="/url%C2%A0%22title%22">link</a></p>\n\n',
},
{
index: 516,
md: '\\[link\\]\\(/url "title "and" title"\\)\n\n',
html: '<p>[link](/url "title "and" title")</p>\n\n',
},
{
index: 517,
md: '[link](/url "title "and" title")\n\n',
html:
'<p><a href="/url" title="title "and" title">link</a></p>\n\n',
},
{
index: 518,
md: '[link](/uri "title")\n\n',
html: '<p><a href="/uri" title="title">link</a></p>\n\n',
},
{
index: 519,
md: '\\[link\\] \\(/uri\\)\n\n',
html: '<p>[link] (/uri)</p>\n\n',
},
{
index: 520,
md: '[link \\[foo \\[bar\\]\\]](/uri)\n\n',
html: '<p><a href="/uri">link [foo [bar]]</a></p>\n\n',
},
{
index: 521,
md: '\\[link\\] bar\\]\\(/uri\\)\n\n',
html: '<p>[link] bar](/uri)</p>\n\n',
},
{
index: 522,
md: '\\[link [bar](/uri)\n\n',
html: '<p>[link <a href="/uri">bar</a></p>\n\n',
},
{
index: 523,
md: '[link \\[bar](/uri)\n\n',
html: '<p><a href="/uri">link [bar</a></p>\n\n',
},
{
index: 524,
md: '[link *foo **bar** `#`*](/uri)\n\n',
html:
'<p><a href="/uri">link <em>foo <strong>bar</strong> <code>#</code></em></a></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 525,
md: '[](/uri)\n\n',
html: '<p><a href="/uri"><img src="moon.jpg" alt="moon" /></a></p>\n\n',
},
{
index: 526,
md: '\\[foo [bar](/uri)\\]\\(/uri\\)\n\n',
html: '<p>[foo <a href="/uri">bar</a>](/uri)</p>\n\n',
},
{
index: 527,
md: '\\[foo *\\[bar [baz](/uri)\\]\\(/uri\\)*\\]\\(/uri\\)\n\n',
html: '<p>[foo <em>[bar <a href="/uri">baz</a>](/uri)</em>](/uri)</p>\n\n',
option: {
emDelimiter: '*',
},
},
// Todo
// {
// index: 528,
// md: '](uri2)](uri3)\n\n',
// html: '<p><img src="uri3" alt="[foo](uri2)" /></p>\n\n',
// },
{
index: 529,
md: '\\*[foo\\*](/uri)\n\n',
html: '<p>*<a href="/uri">foo*</a></p>\n\n',
},
{
index: 530,
md: '[foo \\*bar](baz*)\n\n',
html: '<p><a href="baz*">foo *bar</a></p>\n\n',
},
{
index: 531,
md: '*foo \\[bar* baz\\]\n\n',
html: '<p><em>foo [bar</em> baz]</p>\n\n',
option: {
emDelimiter: '*',
},
},
// {
// index: 532,
// md: '[foo <bar attr="](baz)">\n\n',
// html: '<p>[foo <bar attr="](baz)"></p>\n\n',
// },
{
index: 533,
md: '\\[foo`](/uri)`\n\n',
html: '<p>[foo<code>](/uri)</code></p>\n\n',
},
{
index: 534,
md: '\\[foo<http://example.com/?search=](uri)>\n\n',
html:
'<p>[foo<a href="http://example.com/?search=%5D(uri)">http://example.com/?search=](uri)</a></p>\n\n',
},
{
index: 535,
// md: '[foo][bar]\n\n[bar]: /url "title"\n\n',
md: '[ref]: /url "title"\n\n[foo][ref]\n\n',
html: '<p><a href="/url" title="title">foo</a></p>\n\n',
option: {
linkStyle: 'referenced',
},
},
{
index: 536,
md: '[ref]: /uri\n\n[link \\[foo \\[bar\\]\\]][ref]\n\n',
html: '<p><a href="/uri">link [foo [bar]]</a></p>\n\n',
option: {
linkStyle: 'referenced',
},
},
{
index: 537,
md: '[ref]: /uri\n\n[link \\[bar][ref]\n\n',
html: '<p><a href="/uri">link [bar</a></p>\n\n',
option: {
linkStyle: 'referenced',
},
},
{
index: 538,
md: '[ref]: /uri\n\n[link *foo **bar** `#`*][ref]\n\n',
html:
'<p><a href="/uri">link <em>foo <strong>bar</strong> <code>#</code></em></a></p>\n\n',
option: {
linkStyle: 'referenced',
emDelimiter: '*',
},
},
{
index: 539,
md: '[ref]: /uri\n\n[][ref]\n\n',
html: '<p><a href="/uri"><img src="moon.jpg" alt="moon" /></a></p>\n\n',
option: {
linkStyle: 'referenced',
},
},
{
index: 540,
md: '[ref]: /uri\n[ref2]: /uri\n\n\\[foo [bar][ref]\\][ref][ref2]\n\n',
html: '<p>[foo <a href="/uri">bar</a>]<a href="/uri">ref</a></p>\n\n',
option: {
linkStyle: 'referenced',
},
},
{
index: 541,
// md: '[foo *bar [baz][ref]*][ref]\n\n[ref]: /uri\n\n',
md:
'[ref]: /uri\n' +
'[ref2]: /uri\n' +
'\n' +
'\\[foo *bar [baz][ref]*\\][ref][ref2]\n\n',
html:
'<p>[foo <em>bar <a href="/uri">baz</a></em>]<a href="/uri">ref</a></p>\n\n',
option: {
emDelimiter: '*',
linkStyle: 'referenced',
},
},
{
index: 542,
md: '[ref]: /uri\n\n\\*[foo\\*][ref]\n\n',
html: '<p>*<a href="/uri">foo*</a></p>\n\n',
option: {
linkStyle: 'referenced',
},
},
{
index: 543,
md: '[ref]: /uri\n\n[foo \\*bar][ref]\\*\n\n',
html: '<p><a href="/uri">foo *bar</a>*</p>\n\n',
option: {
linkStyle: 'referenced',
},
},
// {
// index: 544,
// md: '[foo <bar attr="][ref]">\n\n[ref]: /uri\n\n',
// html: '<p>[foo <bar attr="][ref]"></p>\n\n',
// option:{
// linkStyle: 'referenced',
// }
// },
{
index: 545,
// md: '\\[foo`][ref]`\n\n[ref]: /uri\n\n',
md: '\\[foo`][ref]`\n\n',
html: '<p>[foo<code>][ref]</code></p>\n\n',
option: {
linkStyle: 'referenced',
},
},
{
index: 546,
// md: '[foo<http://example.com/?search=][ref]>\n\n[ref]: /uri\n\n',
md:
'[ref]: http://example.com/?search=][ref]\n' +
'\n' +
'\\[foo[http://example.com/\\?search=\\]\\[ref\\]][ref]\n\n',
html:
'<p>[foo<a href="http://example.com/?search=%5D%5Bref%5D">http://example.com/?search=][ref]</a></p>\n\n',
option: {
linkStyle: 'referenced',
},
},
// {
// index: 547,
// md: '[foo][BaR]\n\n[bar]: /url "title"\n\n',
// html: '<p><a href="/url" title="title">foo</a></p>\n\n',
// option:{
// linkStyle: 'referenced',
// }
// },
// {
// index: 548,
// md: '[ẞ]\n\n[SS]: /url\n\n',
// html: '<p><a href="/url">ẞ</a></p>\n\n',
// option:{
// linkStyle: 'referenced',
// }
// },
// {
// index: 549,
// md: '[Foo\n bar]: /url\n\n[Baz][Foo bar]\n\n',
// html: '<p><a href="/url">Baz</a></p>\n\n',
// option:{
// linkStyle: 'referenced',
// }
// },
{
index: 550,
// md: '[foo] [bar]\n\n[bar]: /url "title"\n\n',
md: '[ref]: /url "title"\n' + '\n' + '\\[foo\\] [bar][ref]\n\n',
html: '<p>[foo] <a href="/url" title="title">bar</a></p>\n\n',
option: {
linkStyle: 'referenced',
},
},
{
index: 551,
md: '[ref]: /url "title"\n' + '\n' + '\\[foo\\] [bar][ref]\n\n',
html: '<p>[foo]\n<a href="/url" title="title">bar</a></p>\n\n',
option: {
linkStyle: 'referenced',
},
},
// {
// index: 552,
// md: '[foo]: /url1\n\n[foo]: /url2\n\n[bar][foo]\n\n',
// html: '<p><a href="/url1">bar</a></p>\n\n',
// option:{
// linkStyle: 'referenced',
// }
// },
// {
// index: 553,
// md: '[bar][foo\\!]\n\n[foo!]: /url\n\n',
// html: '<p>[bar][foo!]</p>\n\n',
// option:{
// linkStyle: 'referenced',
// }
// },
{
index: 554,
// md: '[foo][ref[]\n\n[ref[]: /uri\n\n',
md: '\\[foo\\]\\[ref\\[\\]\n' + '\n' + '\\[ref\\[\\]: /uri\n\n',
html: '<p>[foo][ref[]</p>\n<p>[ref[]: /uri</p>\n\n',
option: {
linkStyle: 'referenced',
},
},
{
index: 555,
// md: '[foo][ref[bar]]\n\n[ref[bar]]: /uri\n\n',
md: '\\[foo\\]\\[ref\\[bar\\]\\]\n' + '\n' + '\\[ref\\[bar\\]\\]: /uri\n\n',
html: '<p>[foo][ref[bar]]</p>\n<p>[ref[bar]]: /uri</p>\n\n',
option: {
linkStyle: 'referenced',
},
},
{
index: 556,
// md: '[[[foo]]]\n\n[[[foo]]]: /url\n\n',
md: '\\[\\[\\[foo\\]\\]\\]\n' + '\n' + '\\[\\[\\[foo\\]\\]\\]: /url\n\n',
html: '<p>[[[foo]]]</p>\n<p>[[[foo]]]: /url</p>\n\n',
option: {
linkStyle: 'referenced',
},
},
// {
// index: 557,
// md: '[foo][ref\\[]\n\n[ref\\[]: /uri\n\n',
// html: '<p><a href="/uri">foo</a></p>\n\n',
// option:{
// linkStyle: 'referenced',
// }
// },
{
index: 558,
md: '[ref]: /uri\n' + '\n' + '[bar\\\\][ref]\n\n',
html: '<p><a href="/uri">bar\\</a></p>\n\n',
option: {
linkStyle: 'referenced',
},
},
{
index: 559,
// md: '[]\n\n[]: /uri\n\n',
md: '\\[\\]\n' + '\n' + '\\[\\]: /uri\n\n',
html: '<p>[]</p>\n<p>[]: /uri</p>\n\n',
option: {
linkStyle: 'referenced',
},
},
{
index: 560,
// md: '[\n ]\n\n[\n ]: /uri\n\n',
md: '\\[ \\]\n' + '\n' + '\\[ \\]: /uri\n\n',
html: '<p>[\n]</p>\n<p>[\n]: /uri</p>\n\n',
option: {
linkStyle: 'referenced',
},
},
{
index: 561,
md: '[foo]: /url "title"\n\n[foo][]\n\n',
html: '<p><a href="/url" title="title">foo</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'collapsed',
},
},
{
index: 562,
md: '[*foo* bar]: /url "title"\n\n[*foo* bar][]\n\n',
html: '<p><a href="/url" title="title"><em>foo</em> bar</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'collapsed',
emDelimiter: '*',
},
},
// {
// index: 563,
// md: '[Foo][]\n\n[foo]: /url "title"\n\n',
// html: '<p><a href="/url" title="title">Foo</a></p>\n\n',
// option:{
// linkStyle: 'referenced',
// linkReferenceStyle:'shortcut'
// }
// },
{
index: 564,
md: '[foo]: /url "title"\n\n[foo] \\[\\]\n\n',
html: '<p><a href="/url" title="title">foo</a>\n[]</p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
{
index: 565,
md: '[foo]: /url "title"\n\n[foo]\n\n',
html: '<p><a href="/url" title="title">foo</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
{
index: 566,
md: '[*foo* bar]: /url "title"\n\n[*foo* bar]\n\n',
html: '<p><a href="/url" title="title"><em>foo</em> bar</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
emDelimiter: '*',
},
},
{
index: 567,
md: '[*foo* bar]: /url "title"\n\n\\[[*foo* bar]\\]\n\n',
html: '<p>[<a href="/url" title="title"><em>foo</em> bar</a>]</p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
emDelimiter: '*',
},
},
{
index: 568,
md: '[foo]: /url\n\n\\[\\[bar [foo]\n\n',
html: '<p>[[bar <a href="/url">foo</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
// {
// index: 569,
// md: '[Foo]\n\n[foo]: /url "title"\n\n',
// html: '<p><a href="/url" title="title">Foo</a></p>\n\n',
// option:{
// linkStyle: 'referenced',
// linkReferenceStyle:'shortcut'
// }
// },
{
index: 570,
md: '[foo]: /url\n\n[foo] bar\n\n',
html: '<p><a href="/url">foo</a> bar</p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
// {
// index: 571,
// md: '\\[foo]\n\n[foo]: /url "title"\n\n',
// html: '<p>[foo]</p>\n\n',
// option:{
// linkStyle: 'referenced',
// linkReferenceStyle:'shortcut'
// }
// },
{
index: 572,
md: '[foo\\*]: /url\n\n\\*[foo\\*]\n\n',
html: '<p>*<a href="/url">foo*</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
// {
// index: 573,
// md: '[foo][bar]\n\n[foo]: /url1\n[bar]: /url2\n\n',
// html: '<p><a href="/url2">foo</a></p>\n\n',
// option:{
// linkStyle: 'referenced',
// }
// },
{
index: 574,
md: '[foo]: /url1\n\n[foo][]\n\n',
html: '<p><a href="/url1">foo</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'collapsed',
},
},
// {
// index: 575,
// md: '[foo]()\n\n[foo]: /url1\n\n',
// html: '<p><a href="">foo</a></p>\n\n',
// option: {
// linkStyle: 'referenced',
// linkReferenceStyle: 'collapsed',
// },
// },
{
index: 576,
// md: '[foo](not a link)\n\n[foo]: /url1\n\n',
md: '[foo]: /url1\n' + '\n' + '[foo]\\(not a link\\)\n\n',
html: '<p><a href="/url1">foo</a>(not a link)</p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
{
index: 577,
// md: '[foo][bar][baz]\n\n[baz]: /url\n\n',
md: '[bar]: /url\n' + '\n' + '\\[foo\\][bar]\n\n',
html: '<p>[foo]<a href="/url">bar</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
{
index: 578,
// md: '[foo][bar][baz]\n\n[baz]: /url1\n[bar]: /url2\n\n',
md:
'[ref]: /url2\n' + '[ref2]: /url1\n' + '\n' + '[foo][ref][baz][ref2]\n\n',
html: '<p><a href="/url2">foo</a><a href="/url1">baz</a></p>\n\n',
option: {
linkStyle: 'referenced',
},
},
{
index: 579,
// md: '[foo][bar][baz]\n\n[baz]: /url1\n[foo]: /url2\n\n',
md: '[bar]: /url1\n' + '\n' + '\\[foo\\][bar]\n\n',
html: '<p>[foo]<a href="/url1">bar</a></p>\n\n',
option: {
linkStyle: 'referenced',
linkReferenceStyle: 'shortcut',
},
},
{
index: 580,
md: '\n\n',
html: '<p><img src="/url" alt="foo" title="title" /></p>\n\n',
},
{
index: 581,
// md: '![foo *bar*]\n\n[foo *bar*]: train.jpg "train & tracks"\n\n',
md: '\n\n',
html:
'<p><img src="train.jpg" alt="foo bar" title="train & tracks" /></p>\n\n',
option: {
linkStyle: 'referenced',
emDelimiter: '*',
},
},
// {
// index: 582,
// md: '](/url2)\n\n',
// html: '<p><img src="/url2" alt="foo bar" /></p>\n\n',
// },
// {
// index: 583,
// md: '](/url2)\n\n',
// html: '<p><img src="/url2" alt="foo bar" /></p>\n\n',
// },
// {
// index: 584,
// md: '![foo *bar*][]\n\n[foo *bar*]: train.jpg "train & tracks"\n\n',
// html:
// '<p><img src="train.jpg" alt="foo bar" title="train & tracks" /></p>\n\n',
// option:{
// linkStyle:'referenced',
// emDelimiter: '*',
// }
// },
// {
// index: 585,
// md: '![foo *bar*][foobar]\n\n[FOOBAR]: train.jpg "train & tracks"\n\n',
// html:
// '<p><img src="train.jpg" alt="foo bar" title="train & tracks" /></p>\n\n',
// },
{
index: 586,
md: '\n\n',
html: '<p><img src="train.jpg" alt="foo" /></p>\n\n',
},
{
index: 587,
md: 'My \n\n',
html:
'<p>My <img src="/path/to/train.jpg" alt="foo bar" title="title" /></p>\n\n',
},
{
index: 588,
md: '\n\n',
html: '<p><img src="url" alt="foo" /></p>\n\n',
},
{
index: 589,
md: '\n\n',
html: '<p><img src="/url" alt="" /></p>\n\n',
},
// {
// index: 590,
// md: '![foo][bar]\n\n[bar]: /url\n\n',
// html: '<p><img src="/url" alt="foo" /></p>\n\n',
// option:{
// linkStyle:'referenced',
// }
// },
// {
// index: 591,
// md: '![foo][bar]\n\n[BAR]: /url\n\n',
// html: '<p><img src="/url" alt="foo" /></p>\n\n',
// },
// {
// index: 592,
// md: '![foo][]\n\n[foo]: /url "title"\n\n',
// html: '<p><img src="/url" alt="foo" title="title" /></p>\n\n',
// },
// {
// index: 593,
// md: '![*foo* bar][]\n\n[*foo* bar]: /url "title"\n\n',
// html: '<p><img src="/url" alt="foo bar" title="title" /></p>\n\n',
// },
// {
// index: 594,
// md: '![Foo][]\n\n[foo]: /url "title"\n\n',
// html: '<p><img src="/url" alt="Foo" title="title" /></p>\n\n',
// },
// {
// index: 595,
// md: '![foo] \n[]\n\n[foo]: /url "title"\n\n',
// html: '<p><img src="/url" alt="foo" title="title" />\n[]</p>\n\n',
// },
// {
// index: 596,
// md: '![foo]\n\n[foo]: /url "title"\n\n',
// html: '<p><img src="/url" alt="foo" title="title" /></p>\n\n',
// },
// {
// index: 597,
// md: '![*foo* bar]\n\n[*foo* bar]: /url "title"\n\n',
// html: '<p><img src="/url" alt="foo bar" title="title" /></p>\n\n',
// },
// {
// index: 598,
// md: '![[foo]]\n\n[[foo]]: /url "title"\n\n',
// html: '<p>![[foo]]</p>\n<p>[[foo]]: /url "title"</p>\n\n',
// },
// {
// index: 599,
// md: '![Foo]\n\n[foo]: /url "title"\n\n',
// html: '<p><img src="/url" alt="Foo" title="title" /></p>\n\n',
// },
// {
// index: 600,
// md: '!\\[foo]\n\n[foo]: /url "title"\n\n',
// html: '<p>![foo]</p>\n\n',
// },
// {
// index: 601,
// md: '\\![foo]\n\n[foo]: /url "title"\n\n',
// html: '<p>!<a href="/url" title="title">foo</a></p>\n\n',
// },
{
index: 602,
md: '<http://foo.bar.baz>\n\n',
html: '<p><a href="http://foo.bar.baz">http://foo.bar.baz</a></p>\n\n',
},
{
index: 603,
md: '<http://foo.bar.baz/test?q=hello&id=22&boolean>\n\n',
html:
'<p><a href="http://foo.bar.baz/test?q=hello&id=22&boolean">http://foo.bar.baz/test?q=hello&id=22&boolean</a></p>\n\n',
},
{
index: 604,
md: '<irc://foo.bar:2233/baz>\n\n',
html:
'<p><a href="irc://foo.bar:2233/baz">irc://foo.bar:2233/baz</a></p>\n\n',
},
{
index: 605,
md: '<MAILTO:FOO@BAR.BAZ>\n\n',
html: '<p><a href="MAILTO:FOO@BAR.BAZ">MAILTO:FOO@BAR.BAZ</a></p>\n\n',
},
{
index: 606,
md: '<a+b+c:d>\n\n',
html: '<p><a href="a+b+c:d">a+b+c:d</a></p>\n\n',
},
{
index: 607,
md: '<made-up-scheme://foo,bar>\n\n',
html:
'<p><a href="made-up-scheme://foo,bar">made-up-scheme://foo,bar</a></p>\n\n',
},
{
index: 608,
md: '<http://../>\n\n',
html: '<p><a href="http://../">http://../</a></p>\n\n',
},
{
index: 609,
md: '<localhost:5001/foo>\n\n',
html: '<p><a href="localhost:5001/foo">localhost:5001/foo</a></p>\n\n',
},
{
index: 610,
md: '\\<http://foo.bar/baz bim>\n\n',
html: '<p><http://foo.bar/baz bim></p>\n\n',
},
{
index: 611,
md: '<http://example.com/\\[\\>\n\n',
html:
'<p><a href="http://example.com/%5C%5B%5C">http://example.com/\\[\\</a></p>\n\n',
},
{
index: 612,
md: '<foo@bar.example.com>\n\n',
html:
'<p><a href="mailto:foo@bar.example.com">foo@bar.example.com</a></p>\n\n',
},
{
index: 613,
md: '<foo+special@Bar.baz-bar0.com>\n\n',
html:
'<p><a href="mailto:foo+special@Bar.baz-bar0.com">foo+special@Bar.baz-bar0.com</a></p>\n\n',
},
{
index: 614,
md: '\\<foo+\\@bar.example.com>\n\n',
html: '<p><foo+@bar.example.com></p>\n\n',
},
{
index: 615,
md: '\\<>\n\n',
html: '<p><></p>\n\n',
},
{
index: 616,
md: '\\< http://foo.bar >\n\n',
html: '<p>< http://foo.bar ></p>\n\n',
},
{
index: 617,
md: '\\<m:abc>\n\n',
html: '<p><m:abc></p>\n\n',
},
{
index: 618,
md: '\\<foo.bar.baz>\n\n',
html: '<p><foo.bar.baz></p>\n\n',
},
{
index: 619,
md: 'http://example.com\n\n',
html: '<p>http://example.com</p>\n\n',
},
{
index: 620,
md: 'foo\\@bar.example.com\n\n',
html: '<p>foo@bar.example.com</p>\n\n',
},
// {
// index: 621,
// md: 'www.commonmark.org\n\n',
// html:
// '<p><a href="http://www.commonmark.org">www.commonmark.org</a></p>\n\n',
// },
// {
// index: 622,
// md: 'Visit www.commonmark.org/help for more information.\n\n',
// html:
// '<p>Visit <a href="http://www.commonmark.org/help">www.commonmark.org/help</a> for more information.</p>\n\n',
// },
// {
// index: 623,
// md: 'Visit www.commonmark.org.\n\nVisit www.commonmark.org/a.b.\n\n',
// html:
// '<p>Visit <a href="http://www.commonmark.org">www.commonmark.org</a>.</p>\n<p>Visit <a href="http://www.commonmark.org/a.b">www.commonmark.org/a.b</a>.</p>\n\n',
// },
// {
// index: 624,
// md:
// 'www.google.com/search?q=Markup+(business)\n\nwww.google.com/search?q=Markup+(business)))\n\n(www.google.com/search?q=Markup+(business))\n\n(www.google.com/search?q=Markup+(business)\n\n',
// html:
// '<p><a href="http://www.google.com/search?q=Markup+(business)">www.google.com/search?q=Markup+(business)</a></p>\n<p><a href="http://www.google.com/search?q=Markup+(business)">www.google.com/search?q=Markup+(business)</a>))</p>\n<p>(<a href="http://www.google.com/search?q=Markup+(business)">www.google.com/search?q=Markup+(business)</a>)</p>\n<p>(<a href="http://www.google.com/search?q=Markup+(business)">www.google.com/search?q=Markup+(business)</a></p>\n\n',
// },
// {
// index: 625,
// md: 'www.google.com/search?q=(business))+ok\n\n',
// html:
// '<p><a href="http://www.google.com/search?q=(business))+ok">www.google.com/search?q=(business))+ok</a></p>\n\n',
// },
// {
// index: 626,
// md:
// 'www.google.com/search?q=commonmark&hl=en\n\nwww.google.com/search?q=commonmark&hl;\n\n',
// html:
// '<p><a href="http://www.google.com/search?q=commonmark&hl=en">www.google.com/search?q=commonmark&hl=en</a></p>\n<p><a href="http://www.google.com/search?q=commonmark">www.google.com/search?q=commonmark</a>&hl;</p>\n\n',
// },
// {
// index: 627,
// md: 'www.commonmark.org/he<lp\n\n',
// html:
// '<p><a href="http://www.commonmark.org/he">www.commonmark.org/he</a><lp</p>\n\n',
// },
// {
// index: 628,
// md:
// 'http://commonmark.org\n\n(Visit https://encrypted.google.com/search?q=Markup+(business))\n\n',
// html:
// '<p><a href="http://commonmark.org">http://commonmark.org</a></p>\n<p>(Visit <a href="https://encrypted.google.com/search?q=Markup+(business)">https://encrypted.google.com/search?q=Markup+(business)</a>)</p>\n\n',
// },
// {
// index: 629,
// md: 'foo@bar.baz\n\n',
// html: '<p><a href="mailto:foo@bar.baz">foo@bar.baz</a></p>\n\n',
// },
// {
// index: 630,
// md:
// "hello@mail+xyz.example isn't valid, but hello+xyz@mail.example is.\n\n",
// html:
// '<p>hello@mail+xyz.example isn\'t valid, but <a href="mailto:hello+xyz@mail.example">hello+xyz@mail.example</a> is.</p>\n\n',
// },
// {
// index: 631,
// md: 'a.b-c_d@a.b\n\na.b-c_d@a.b.\n\na.b-c_d@a.b-\n\na.b-c_d@a.b_\n\n',
// html:
// '<p><a href="mailto:a.b-c_d@a.b">a.b-c_d@a.b</a></p>\n<p><a href="mailto:a.b-c_d@a.b">a.b-c_d@a.b</a>.</p>\n<p>a.b-c_d@a.b-</p>\n<p>a.b-c_d@a.b_</p>\n\n',
// },
// {
// index: 632,
// md: '<a><bab><c2c>\n\n',
// html: '<p><a><bab><c2c></p>\n\n',
// },
// {
// index: 633,
// md: '<a/><b2/>\n\n',
// html: '<p><a/><b2/></p>\n\n',
// },
// {
// index: 634,
// md: '<a /><b2\ndata="foo" >\n\n',
// html: '<p><a /><b2\ndata="foo" ></p>\n\n',
// },
// {
// index: 635,
// md:
// '<a foo="bar" bam = \'baz <em>"</em>\'\n_boolean zoop:33=zoop:33 />\n\n',
// html:
// '<p><a foo="bar" bam = \'baz <em>"</em>\'\n_boolean zoop:33=zoop:33 /></p>\n\n',
// },
{
index: 636,
md: 'Foo<responsive-image src="foo.jpg" />\n\n',
html: '<p>Foo <responsive-image src="foo.jpg" /></p>\n\n',
option: {
keepFilter: ['responsive-image'],
},
},
{
index: 637,
md: '\\<33> \\<\\_\\_>\n\n',
html: '<p><33> <__></p>\n\n',
},
{
index: 638,
md: '\\<a h\\*#ref="hi">\n\n',
html: '<p><a h*#ref="hi"></p>\n\n',
},
{
index: 639,
md: "\\<a href=\"hi'> \\<a href=hi'>\n\n",
html: "<p><a href="hi'> <a href=hi'></p>\n\n",
},
{
index: 640,
md: '\\< a>\\< foo>\\<bar/ > \\<foo bar=baz bim\\!bop />\n\n',
html:
'<p>< a><\nfoo><bar/ >\n<foo bar=baz\nbim!bop /></p>\n\n',
},
{
index: 641,
md: "\\<a href='bar'title=title>\n\n",
html: "<p><a href='bar'title=title></p>\n\n",
},
// {
// index: 642,
// md: '</a></foo >\n\n',
// html: '<p></a></foo ></p>\n\n',
// },
{
index: 643,
md: '\\</a href="foo">\n\n',
html: '<p></a href="foo"></p>\n\n',
},
{
index: 644,
md: 'foo<!-- this is a\ncomment - with hyphen -->\n\n',
html: '<p>foo <!-- this is a\ncomment - with hyphen --></p>\n\n',
},
{
index: 645,
md: 'foo \\<\\!-- not a comment \\-- two hyphens \\-->\n\n',
html: '<p>foo <!-- not a comment -- two hyphens --></p>\n\n',
},
{
index: 646,
md: 'foo \\<\\!--> foo \\-->\n\nfoo \\<\\!-- foo--->\n\n',
html:
'<p>foo <!--> foo --></p>\n<p>foo <!-- foo---></p>\n\n',
},
// {
// index: 647,
// md: 'foo<?php echo $a; ?>\n\n',
// html: '<p>foo <?php echo $a; ?></p>\n\n',
// },
// {
// index: 648,
// md: 'foo<!ELEMENT br EMPTY>\n\n',
// html: '<p>foo <!ELEMENT br EMPTY></p>\n\n',
// },
// {
// index: 649,
// md: 'foo <![CDATA[>&<]]>\n\n',
// html: '<p>foo <![CDATA[>&<]]></p>\n\n',
// },
// {
// index: 650,
// md: 'foo<a href="ö">\n\n',
// html: '<p>foo <a href="ö"></p>\n\n',
// option:{
// keepFilter: ['a'],
// }
// },
// {
// index: 651,
// md: 'foo<a href="\\*" />\n\n',
// html: '<p>foo <a href="\\*"></p>\n\n',
// option:{
// keepFilter: ['a'],
// }
// },
{
index: 652,
md: '\\<a href=""">\n\n',
html: '<p><a href="""></p>\n\n',
},
// Todo:消毒无效标签
// {
// index: 653,
// // md:
// // '<strong> <title> <style> <em>\n\n<blockquote>\n <xmp> is disallowed. <XMP> is also disallowed.\n</blockquote>\n\n',
// md:
// '<strong><title> <style><em></em></strong>\n' +
// '\n' +
// '<strong><em><blockquote><xmp> is disallowed. <XMP> is also disallowed.</blockquote></em></strong>\n\n',
// html:
// '<p><strong> <title> <style> <em></p>\n<blockquote>\n <xmp> is disallowed. <XMP> is also disallowed.\n</blockquote>\n\n',
// option:{
// keepFilter: ['strong','em'],
// }
// },
{
index: 654,
md: 'foo \nbaz\n\n',
html: '<p>foo<br />\nbaz</p>\n\n',
},
// {
// index: 655,
// md: 'foo\\\nbaz\n\n',
// html: '<p>foo<br />\nbaz</p>\n\n',
// },
{
index: 656,
md: 'foo \nbaz\n\n',
html: '<p>foo<br />\nbaz</p>\n\n',
},
{
index: 657,
md: 'foo \nbar\n\n',
html: '<p>foo<br />\nbar</p>\n\n',
},
// {
// index: 658,
// md: 'foo\\\n bar\n\n',
// html: '<p>foo<br />\nbar</p>\n\n',
// },
{
index: 659,
md: '*foo \nbar*\n\n',
html: '<p><em>foo<br />\nbar</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 660,
md: '*foo \nbar*\n\n',
html: '<p><em>foo<br />\nbar</em></p>\n\n',
option: {
emDelimiter: '*',
},
},
{
index: 661,
md: '`code span`\n\n',
html: '<p><code>code span</code></p>\n\n',
},
{
index: 662,
md: '`code\\ span`\n\n',
html: '<p><code>code\\ span</code></p>\n\n',
},
// {
// index: 663,
// md: '<a href="foo \nbar">\n\n',
// html: '<p><a href="foo \nbar"></p>\n\n',
// },
// {
// index: 664,
// md: '<a href="foo\\\nbar">\n\n',
// html: '<p><a href="foo\\\nbar"></p>\n\n',
// },
{
index: 665,
md: 'foo\\\\\n\n',
html: '<p>foo\\</p>\n\n',
},
{
index: 666,
md: 'foo\n\n',
html: '<p>foo</p>\n\n',
},
{
index: 667,
md: '### foo\\\\\n\n',
html: '<h3>foo\\</h3>\n\n',
},
{
index: 668,
md: '### foo\n\n',
html: '<h3>foo</h3>\n\n',
},
{
index: 669,
md: 'foo baz\n\n',
html: '<p>foo\nbaz</p>\n\n',
},
// {
// index: 670,
// md: 'foo \n baz\n\n',
// html: '<p>foo\nbaz</p>\n\n',
// },
{
index: 671,
md: "hello \\$.;'there\n\n",
html: "<p>hello $.;'there</p>\n\n",
},
{
index: 672,
md: 'Foo χρῆν\n\n',
html: '<p>Foo χρῆν</p>\n\n',
},
{
index: 673,
md: 'Multiple spaces\n\n',
html: '<p>Multiple spaces</p>\n\n',
},
]; | the_stack |
import assert from 'assert';
import * as Builtin from '../runtime/builtins';
import * as Ast from '../ast';
import { stringEscape } from '../utils/escaping';
import type { ExecEnvironment } from '../runtime/exec_environment';
// A register-based IR for ThingTalk to JS
// Typed like ThingTalk
interface Instruction {
codegen(prefix : string) : string;
}
type Register = number;
// A sequence of instructions
class Block {
private _instructions : Instruction[];
constructor() {
this._instructions = [];
}
add(instr : Instruction) {
this._instructions.push(instr);
}
codegen(prefix : string) : string {
return this._instructions.map((i) => i.codegen(prefix)).join('\n');
}
}
class Copy {
private _what : Register;
private _into : Register;
constructor(what : Register, into : Register) {
this._what = what;
this._into = into;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._into} = _t_${this._what};`;
}
}
class CreateTuple {
private _size : number;
private _into : Register;
constructor(size : number, into : Register) {
this._size = size;
this._into = into;
}
codegen(prefix : string) : string {
return prefix + '_t_' + this._into + ' = new Array(' + this._size + ');';
}
}
class CreateObject {
private _into : Register;
constructor(into : Register) {
this._into = into;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._into} = {};`;
}
}
class SetIndex {
private _tuple : Register;
private _idx : number;
private _value : Register;
constructor(tuple : Register, idx : number, value : Register) {
this._tuple = tuple;
this._idx = idx;
this._value = value;
}
codegen(prefix : string) : string {
return prefix + '_t_' + this._tuple + '[' + this._idx + '] = _t_' + this._value + ';';
}
}
class GetIndex {
private _tuple : Register;
private _idx : number;
private _into : Register;
constructor(tuple : Register, idx : number, into : Register) {
this._tuple = tuple;
this._idx = idx;
this._into = into;
}
codegen(prefix : string) : string {
return prefix + '_t_' + this._into + ' = _t_' + this._tuple + '[' + this._idx + '];';
}
}
class GetASTObject {
private _idx : number;
private _into : Register;
constructor(idx : number, into : Register) {
this._idx = idx;
this._into = into;
}
codegen(prefix : string) : string {
return prefix + '_t_' + this._into + ' = __ast[' + this._idx + '];';
}
}
class GetKey {
private _object : Register;
private _key : string;
private _into : Register;
constructor(object : Register, key : string, into : Register) {
this._object = object;
this._key = key;
this._into = into;
}
codegen(prefix : string) : string {
if (this._key.includes('.'))
return `${prefix}_t_${this._into} = _t_${this._object}["${this._key}"];`;
return `${prefix}_t_${this._into} = _t_${this._object}.${this._key};`;
}
}
class SetKey {
private _object : Register;
private _key : string;
private _value : Register|null;
constructor(object : Register, key : string, value : Register|null) {
this._object = object;
this._key = key;
this._value = value;
}
codegen(prefix : string) : string {
if (this._value === null)
return `${prefix}_t_${this._object}.${this._key} = null;`;
else
return `${prefix}_t_${this._object}.${this._key} = _t_${this._value};`;
}
}
class GetVariable {
private _variable : string;
private _into : Register;
constructor(variable : string, into : Register) {
this._variable = variable;
this._into = into;
}
codegen(prefix : string) : string {
return prefix + '_t_' + this._into + ' = __env._scope.' + this._variable + ';';
}
}
class GetEnvironment {
private _variable : string;
private _into : Register;
constructor(variable : string, into : Register) {
this._variable = variable;
this._into = into;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._into} = __env.${this._variable};`;
}
}
class GetScope {
private _name : string;
private _into : Register;
constructor(name : string, into : Register) {
this._name = name;
this._into = into;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._into} = __scope.${this._name};`;
}
}
class AsyncIterator {
private _into : Register;
private _iterable : Register;
constructor(into : Register, iterable : Register) {
this._iterable = iterable;
this._into = into;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._into} = __builtin.getAsyncIterator(_t_${this._iterable});`;
}
}
interface ToJSSource {
toJSSource() : string;
}
function hasJSSource(x : unknown) : x is ToJSSource {
return typeof x === 'object' && x !== null && 'toJSSource' in x;
}
function anyToJS(js : unknown) : string {
if (Array.isArray(js))
return '[' + js.map(anyToJS).join(', ') + ']';
if (typeof js === 'string')
return stringEscape(js);
if (hasJSSource(js))
return js.toJSSource();
if (js instanceof Date)
return `new Date(${js.getTime()})`;
return String(js);
}
function valueToJSSource(value : Ast.Value|null) : string {
if (value === null)
return 'null';
const js = value.toJS();
return anyToJS(js);
}
class LoadConstant {
private _constant : Ast.Value|null;
private _into : Register;
constructor(constant : Ast.Value|null, into : Register) {
this._constant = constant;
this._into = into;
}
codegen(prefix : string) : string {
return prefix + '_t_' + this._into + ' = ' + valueToJSSource(this._constant) + ';';
}
}
class LoadBuiltin {
private _builtin : string;
private _into : Register;
constructor(builtin : string, into : Register) {
this._builtin = builtin;
this._into = into;
}
codegen(prefix : string) : string {
return prefix + '_t_' + this._into + ' = __builtin.' + this._builtin + ';';
}
}
class NewObject {
private _class : string;
private _into : Register;
private _args : Register[];
constructor(classname : string, into : Register, ...args : Register[]) {
this._class = classname;
this._into = into;
this._args = args;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._into} = new __builtin.${this._class}(${this._args.map((a) => '_t_' + a).join(', ')});`;
}
}
class MapAndReadField {
private _into : Register;
private _array : Register;
private _field : string;
constructor(into : Register, array : Register, field : string) {
this._into = into;
this._array = array;
this._field = field;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._into} = _t_${this._array}.map(($) => $.${this._field});`;
}
}
class FormatEvent {
private _hint : string;
private _outputType : Register;
private _output : Register;
private _into : Register;
constructor(hint : string,
outputType : Register,
output : Register,
into : Register) {
this._hint = hint;
this._outputType = outputType;
this._output = output;
this._into = into;
}
codegen(prefix : string) : string {
if (this._outputType === null)
return `${prefix}_t_${this._into} = await __env.formatEvent(null, _t_${this._output}, ${stringEscape(this._hint)});`;
else
return `${prefix}_t_${this._into} = await __env.formatEvent(_t_${this._outputType}, _t_${this._output}, ${stringEscape(this._hint)});`;
}
}
class BinaryFunctionOp {
private _a : Register;
private _b : Register;
private _fn : string;
private _into : Register;
constructor(a : Register, b : Register, fn : string, into : Register) {
this._a = a;
this._b = b;
this._fn = fn;
this._into = into;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._into} = __builtin.${this._fn}(_t_${this._a}, _t_${this._b});`;
}
}
class VoidFunctionOp {
private _fn : string;
private _args : Register[];
constructor(fn : string, ...args : Register[]) {
this._fn = fn;
this._args = args;
}
codegen(prefix : string) : string {
return `${prefix}__builtin.${this._fn}(${this._args.map((a) => '_t_' + a).join(', ')});`;
}
}
class FunctionOp {
private _fn : string;
private _into : Register;
private _args : Register[];
private _passEnv : boolean;
constructor(fn : string, passEnv : boolean, into : Register, ...args : Register[]) {
this._fn = fn;
this._into = into;
this._args = args;
this._passEnv = passEnv;
}
codegen(prefix : string) : string {
if (this._passEnv)
return `${prefix}_t_${this._into} = __builtin.${this._fn}(__env, ${this._args.map((a) => '_t_' + a).join(', ')});`;
else
return `${prefix}_t_${this._into} = __builtin.${this._fn}(${this._args.map((a) => '_t_' + a).join(', ')});`;
}
}
class BinaryOp {
private _a : Register;
private _b : Register;
private _op : string;
private _into : Register;
constructor(a : Register, b : Register, op : string, into : Register) {
this._a = a;
this._b = b;
this._op = op;
this._into = into;
}
codegen(prefix : string) : string {
return prefix + '_t_' + this._into + ' = ' + '_t_' + this._a + ' ' + this._op + ' ' + '_t_' + this._b + ';';
}
}
class UnaryOp {
private _v : Register;
private _op : string;
private _into : Register;
constructor(v : Register, op : string, into : Register) {
this._v = v;
this._op = op;
this._into = into;
}
codegen(prefix : string) : string {
return prefix + '_t_' + this._into + ' = ' + this._op + ' (' + '_t_' + this._v + ');';
}
}
class MethodOp {
private _obj : Register;
private _args : Register[];
private _op : string;
constructor(obj : Register, op : string, ...args : Register[]) {
this._obj = obj;
this._args = args;
this._op = op;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._obj}.${this._op}(${this._args.map((a) => '_t_' + a).join(', ')});`;
}
}
function objectToJS(obj : { [key : string] : unknown }) : string {
let buffer = '{ ';
for (const key in obj)
buffer += `${key}: ${anyToJS(obj[key])}, `;
buffer += '}';
return buffer;
}
class EnterProcedure {
private _procid : number;
private _procname : string|null;
constructor(procid : number, procname : string|null = null) {
this._procid = procid;
this._procname = procname;
}
codegen(prefix : string) : string {
return `${prefix}await __env.enterProcedure(${this._procid}, ${stringEscape(this._procname)});`;
}
}
class ExitProcedure {
private _procid : number;
private _procname : string|null;
constructor(procid : number, procname : string|null = null) {
this._procid = procid;
this._procname = procname;
}
codegen(prefix : string) : string {
return `${prefix}await __env.exitProcedure(${this._procid}, ${stringEscape(this._procname)});`;
}
}
interface QueryInvocationHints {
projection : string[];
filter ?: Register;
sort ?: [string, 'asc' | 'desc'];
limit ?: number;
}
function invocationHintsToJS(hints : QueryInvocationHints) : string {
let buffer = `{ projection: [${hints.projection.map(stringEscape).join(', ')}]`;
if (hints.filter !== undefined)
buffer += `, filter: _t_${hints.filter}`;
if (hints.sort !== undefined)
buffer += `, sort: [${hints.sort.map(stringEscape).join(', ')}]`;
if (hints.limit !== undefined)
buffer += `, limit: ${hints.limit}`;
buffer += ' }';
return buffer;
}
export type AttributeMap = { [key : string] : unknown };
class InvokeMonitor {
private _kind : string;
private _attrs : AttributeMap;
private _fname : string;
private _into : Register;
private _args : Register;
private _hints : QueryInvocationHints;
constructor(kind : string,
attrs : { [key : string] : unknown },
fname : string,
into : Register,
args : Register,
hints : QueryInvocationHints) {
this._kind = kind;
this._attrs = attrs;
this._fname = fname;
this._into = into;
this._args = args;
this._hints = hints;
}
codegen(prefix : string) : string {
const hints = invocationHintsToJS(this._hints);
return `${prefix}_t_${this._into} = await __env.invokeMonitor(${stringEscape(this._kind)}, ${objectToJS(this._attrs)}, ${stringEscape(this._fname)}, _t_${this._args}, ${hints});`;
}
}
class InvokeTimer {
private _into : Register;
private _base : Register;
private _interval : Register;
private _frequency : Register|null;
constructor(into : Register, base : Register, interval : Register, frequency : Register|null) {
this._into = into;
this._base = base;
this._interval = interval;
this._frequency = frequency;
}
codegen(prefix : string) : string {
if (this._frequency)
return `${prefix}_t_${this._into} = await __env.invokeTimer(_t_${this._base}, _t_${this._interval}, _t_${this._frequency});`;
return `${prefix}_t_${this._into} = await __env.invokeTimer(_t_${this._base}, _t_${this._interval}, null);`;
}
}
class InvokeAtTimer {
private _into : Register;
private _time : Register;
private _expiration_date : Register|null;
constructor(into : Register, time : Register, expiration_date : Register|null) {
this._into = into;
this._time = time;
this._expiration_date = expiration_date;
}
codegen(prefix : string) : string {
if (this._expiration_date)
return `${prefix}_t_${this._into} = await __env.invokeAtTimer(_t_${this._time}, _t_${this._expiration_date});`;
return `${prefix}_t_${this._into} = await __env.invokeAtTimer(_t_${this._time}, null);`;
}
}
class InvokeOnTimer {
private _into : Register;
private _date : Register;
constructor(into : Register, date : Register) {
this._into = into;
this._date = date;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._into} = await __env.invokeOnTimer(_t_${this._date});`;
}
}
class InvokeQuery {
private _kind : string;
private _attrs : AttributeMap;
private _fname : string;
private _into : Register;
private _args : Register;
private _hints : QueryInvocationHints;
constructor(kind : string,
attrs : AttributeMap,
fname : string,
into : Register,
args : Register,
hints : QueryInvocationHints) {
this._kind = kind;
this._attrs = attrs;
this._fname = fname;
this._into = into;
this._args = args;
this._hints = hints;
}
codegen(prefix : string) : string {
const hints = invocationHintsToJS(this._hints);
return `${prefix}_t_${this._into} = await __env.invokeQuery(${stringEscape(this._kind)}, ${objectToJS(this._attrs)}, ${stringEscape(this._fname)}, _t_${this._args}, ${hints});`;
}
}
class InvokeDBQuery {
private _kind : string;
private _attrs : AttributeMap;
private _into : Register;
private _query : Register;
constructor(kind : string,
attrs : AttributeMap,
into : Register,
query : Register) {
this._kind = kind;
this._attrs = attrs;
this._into = into;
this._query = query;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._into} = await __env.invokeDBQuery(${stringEscape(this._kind)}, ${objectToJS(this._attrs)}, _t_${this._query});`;
}
}
class InvokeStreamVarRef {
private _name : Register;
private _into : Register;
private _args : Register[];
constructor(name : Register, into : Register, args : Register[]) {
this._name = name;
this._into = into;
this._args = args;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._into} = await __builtin.invokeStreamVarRef(__env, _t_${this._name}${this._args.map((a) => ', _t_' + a).join('')});`;
}
}
class InvokeAction {
private _kind : string;
private _attrs : AttributeMap;
private _fname : string;
private _into : Register;
private _args : Register;
constructor(kind : string,
attrs : AttributeMap,
fname : string,
into : Register,
args : Register) {
this._kind = kind;
this._attrs = attrs;
this._fname = fname;
this._into = into;
this._args = args;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._into} = __env.invokeAction(${stringEscape(this._kind)}, ${objectToJS(this._attrs)}, ${stringEscape(this._fname)}, _t_${this._args});`;
}
}
class InvokeOutput {
private _outputType : Register;
private _output : Register;
constructor(outputType : Register, output : Register) {
this._outputType = outputType;
this._output = output;
}
codegen(prefix : string) : string {
return `${prefix}await __env.output(String(_t_${this._outputType}), _t_${this._output});`;
}
}
class InvokeReadState {
private _into : Register;
private _stateId : number;
constructor(into : Register, stateId : number) {
this._into = into;
this._stateId = stateId;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._into} = await __env.readState(${this._stateId});`;
}
}
class InvokeWriteState {
private _state : Register;
private _stateId : number;
constructor(state : Register, stateId : number) {
this._state = state;
this._stateId = stateId;
}
codegen(prefix : string) : string {
return `${prefix}await __env.writeState(${this._stateId}, _t_${this._state});`;
}
}
class CheckIsNewTuple {
private _into : Register;
private _state : Register;
private _tuple : Register;
private _keys : string[];
constructor(into : Register, state : Register, tuple : Register, keys : string[]) {
this._into = into;
this._state = state;
this._tuple = tuple;
this._keys = keys;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._into} = __builtin.isNewTuple(_t_${this._state}, _t_${this._tuple}, [${
this._keys.map(stringEscape).join(', ')}]);`;
}
}
class AddTupleToState {
private _into : Register;
private _state : Register;
private _tuple : Register;
constructor(into : Register, state : Register, tuple : Register) {
this._into = into;
this._state = state;
this._tuple = tuple;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._into} = __builtin.addTuple(_t_${this._state}, _t_${this._tuple});`;
}
}
class SendEndOfFlow {
private _principal : Register;
private _flow : Register;
constructor(principal : Register, flow : Register) {
this._principal = principal;
this._flow = flow;
}
codegen(prefix : string) : string {
return `${prefix}await __env.sendEndOfFlow(_t_${this._principal}, _t_${this._flow});`;
}
}
class ClearGetCache {
codegen(prefix : string) : string {
return prefix + '__env.clearGetCache();';
}
}
class Break {
codegen(prefix : string) : string {
return prefix + 'break;';
}
}
class IfStatement {
private _cond : Register;
iftrue : Block;
iffalse : Block;
constructor(cond : Register) {
this._cond = cond;
this.iftrue = new Block;
this.iffalse = new Block;
}
codegen(prefix : string) : string {
return prefix + 'if (_t_' + this._cond + ') {\n' +
this.iftrue.codegen(prefix + ' ') + '\n'
+ prefix + '} else {\n' +
this.iffalse.codegen(prefix + ' ') + '\n'
+ prefix + '}';
}
}
class ForOfStatement {
private _into : Register;
private _iterable : Register;
body : Block;
constructor(into : Register, iterable : Register) {
this._into = into;
this._iterable = iterable;
this.body = new Block;
}
codegen(prefix : string) : string {
return prefix + 'for (_t_' + this._into + ' of _t_' + this._iterable + ') {\n' +
this.body.codegen(prefix + ' ') + '\n'
+ prefix + '}';
}
}
class AsyncWhileLoop {
private _into : Register;
private _iterator : Register;
body : Block;
constructor(into : Register, iterator : Register) {
this._into = into;
this._iterator = iterator;
this.body = new Block;
}
codegen(prefix : string) : string {
return prefix + '{\n' +
prefix + ' let _iter_tmp = await _t_' + this._iterator + '.next();\n' +
prefix + ' while (!_iter_tmp.done) {\n' +
prefix + ' _t_' + this._into + ' = _iter_tmp.value;\n' +
this.body.codegen(prefix + ' ') + '\n' +
prefix + ' _iter_tmp = await _t_' + this._iterator + '.next();\n' +
prefix + ' }\n' +
prefix + '}';
}
}
class AsyncFunctionExpression {
private _into : Register;
body : Block;
constructor(into : Register) {
this._into = into;
this.body = new Block;
}
codegen(prefix : string) : string {
return prefix + `_t_${this._into} = async function(__emit) {\n` +
this.body.codegen(prefix + ' ') + '\n' +
prefix + '}';
}
}
class ArrayFilterExpression {
private _into : Register;
private _element : Register;
private _array : Register;
body : Block;
constructor(into : Register, element : Register, array : Register) {
this._into = into;
this._element = element;
this._array = array;
this.body = new Block;
}
codegen(prefix : string) : string {
return prefix + `_t_${this._into} = _t_${this._array}.filter((_t_${this._element}) => {\n` +
this.body.codegen(prefix + ' ') + '\n' +
prefix + '});';
}
}
class AsyncFunctionDeclaration {
private _into : Register;
private _body : IRBuilder;
constructor(into : Register, body : IRBuilder) {
this._into = into;
this._body = body;
}
codegen(prefix : string) : string {
return `${prefix}_t_${this._into} = ${this._body.codegenFunction(prefix)};`;
}
}
class InvokeEmit {
private _values : Register[];
constructor(...values : Register[]) {
this._values = values;
}
codegen(prefix : string) : string {
return `${prefix}__emit(${this._values.map((v) => '_t_' + v).join(', ')});`;
}
}
class LabeledLoop {
private _label : string;
body : Block;
constructor(label : string) {
this._label = label;
this.body = new Block;
}
codegen(prefix : string) : string {
return prefix + `_l_${this._label}: while (true) {\n` +
this.body.codegen(prefix + ' ') + '\n' +
prefix + '}';
}
}
class LabeledBreak {
private _label : string;
constructor(label : string) {
this._label = label;
}
codegen(prefix : string) : string {
return `${prefix}break _l_${this._label};`;
}
}
class LabeledContinue {
private _label : string;
constructor(label : string) {
this._label = label;
}
codegen(prefix : string) : string {
return `${prefix}continue _l_${this._label};`;
}
}
class TryCatch {
private _message : string;
try : Block;
constructor(message : string) {
this._message = message;
this.try = new Block;
}
codegen(prefix : string) : string {
return prefix + 'try {\n' +
this.try.codegen(prefix + ' ') + '\n' +
prefix + '} catch(_exc_) {\n' +
prefix + ' __env.reportError(' + stringEscape(this._message) + ', _exc_);\n' +
prefix + '}';
}
}
class ReturnValue {
private _value : Register;
constructor(value : Register) {
this._value = value;
}
codegen(prefix : string) : string {
return prefix + `return _t_${this._value};`;
}
}
class RootBlock extends Block {
private _temps : Register[];
private _beginHook : Instruction|null;
private _endHook : Instruction|null;
constructor() {
super();
this._temps = [];
this._beginHook = null;
this._endHook = null;
}
setBeginEndHooks(beginHook : Instruction|null, endHook : Instruction|null) : void {
this._beginHook = beginHook;
this._endHook = endHook;
}
declare(reg : Register) : void {
this._temps.push(reg);
}
codegen(prefix : string) : string {
let buffer = `${prefix} "use strict";\n`;
for (const t of this._temps)
buffer += `${prefix} let _t_${t};\n`;
if (this._beginHook) {
buffer += this._beginHook.codegen(prefix + ' ');
buffer += '\n';
}
if (this._endHook) {
buffer += `${prefix} try {\n`;
buffer += super.codegen(prefix + ' ');
buffer += '\n';
buffer += `${prefix} } finally {\n`;
buffer += this._endHook.codegen(prefix + ' ');
buffer += '\n';
buffer += `${prefix} }`;
} else {
buffer += super.codegen(prefix + ' ');
}
return buffer;
}
}
type RegisterRange = [Register, Register];
type TopLevelScope = { [key : string] : unknown };
// eslint-disable-next-line prefer-arrow-callback
const AsyncFunction = Object.getPrototypeOf(async function() {}).constructor;
class IRBuilder {
private _extraArgs : string[];
private _nArgs : number;
private _baseRegister : Register;
private _nextRegister : Register;
private _skipRegisterRanges : RegisterRange[];
private _nextLabel : number;
private _root : RootBlock;
private _blockStack : Block[];
constructor(baseRegister = 0, extraArgs : string[] = []) {
this._extraArgs = extraArgs;
this._nArgs = 0;
this._baseRegister = baseRegister;
this._nextRegister = baseRegister;
this._skipRegisterRanges = [];
this._nextLabel = 0;
this._root = new RootBlock;
this._blockStack = [this._root];
}
setBeginEndHooks(beginHook : Instruction|null, endHook : Instruction|null) : void {
this._root.setBeginEndHooks(beginHook, endHook);
}
get registerRange() : RegisterRange {
return [this._baseRegister, this._nextRegister];
}
get nextRegister() : Register {
return this._nextRegister;
}
skipRegisterRange(range : RegisterRange) : void {
this._skipRegisterRanges.push(range);
this._nextRegister = range[1];
}
codegen(prefix = '') : string {
let nextSkipPos = 0;
let nextSkip = nextSkipPos >= this._skipRegisterRanges.length ? null : this._skipRegisterRanges[nextSkipPos];
for (let reg = this._baseRegister + this._nArgs; reg < this._nextRegister; reg++) {
if (nextSkip && reg >= nextSkip[0]) {
reg = nextSkip[1];
reg --;
nextSkipPos++;
nextSkip = nextSkipPos >= this._skipRegisterRanges.length ? null : this._skipRegisterRanges[nextSkipPos];
continue;
}
this._root.declare(reg);
}
return this._root.codegen(prefix);
}
codegenFunction(prefix = '') : string {
const args = ['__env', ...this._extraArgs];
for (let i = 0; i < this._nArgs; i++)
args.push('_t_' + (this._baseRegister + i));
return `async function(${args.join(', ')}) {\n${this.codegen(prefix)}\n${prefix}}`;
}
compile(scope : TopLevelScope, asts : Ast.Node[]) : (x : ExecEnvironment) => Promise<void> {
const code = this.codegen();
const args = ['__builtin', '__scope', '__ast', '__env', ...this._extraArgs];
for (let i = 0; i < this._nArgs; i++)
args.push('_t_' + i);
const f = new AsyncFunction(...args, code);
return f.bind(null, Builtin, scope, asts);
}
private get _currentBlock() : Block {
return this._blockStack[this._blockStack.length-1];
}
allocRegister() : Register {
const reg = this._nextRegister++;
return reg;
}
allocArgument() : Register {
assert(this._baseRegister + this._nArgs === this._nextRegister);
const reg = this._nextRegister++;
this._nArgs++;
return reg;
}
allocLabel() : number {
const lbl = this._nextLabel++;
return lbl;
}
pushBlock(block : Block) : number {
const now = this._blockStack.length;
this._blockStack.push(block);
return now;
}
popBlock() : void {
this._blockStack.pop();
if (this._blockStack.length === 0)
throw new Error('Invalid pop');
}
saveStackState() : number {
return this._blockStack.length;
}
popTo(upto : number) : void {
this._blockStack.length = upto;
}
popAll() : void {
this._blockStack.length = 0;
this._blockStack[0] = this._root;
}
add(instr : Instruction) : void {
this._currentBlock.add(instr);
}
}
export {
Register,
IRBuilder,
IfStatement,
Copy,
CreateTuple,
CreateObject,
GetIndex,
SetIndex,
GetKey,
SetKey,
GetASTObject,
GetVariable,
GetEnvironment,
GetScope,
AsyncIterator,
LoadConstant,
LoadBuiltin,
NewObject,
BinaryFunctionOp,
BinaryOp,
UnaryOp,
MethodOp,
VoidFunctionOp,
FunctionOp,
MapAndReadField,
FormatEvent,
EnterProcedure,
ExitProcedure,
InvokeMonitor,
InvokeTimer,
InvokeAtTimer,
InvokeOnTimer,
InvokeQuery,
InvokeDBQuery,
InvokeStreamVarRef,
InvokeAction,
InvokeOutput,
InvokeReadState,
InvokeWriteState,
InvokeEmit,
CheckIsNewTuple,
AddTupleToState,
LabeledLoop,
LabeledBreak,
LabeledContinue,
ReturnValue,
ClearGetCache,
SendEndOfFlow,
ForOfStatement,
AsyncWhileLoop,
AsyncFunctionExpression,
AsyncFunctionDeclaration,
ArrayFilterExpression,
Break,
TryCatch
}; | the_stack |
import {
EndpointsInputConfig,
EndpointsResolvedConfig,
RegionInputConfig,
RegionResolvedConfig,
resolveEndpointsConfig,
resolveRegionConfig,
} from "@aws-sdk/config-resolver";
import { getContentLengthPlugin } from "@aws-sdk/middleware-content-length";
import {
getHostHeaderPlugin,
HostHeaderInputConfig,
HostHeaderResolvedConfig,
resolveHostHeaderConfig,
} from "@aws-sdk/middleware-host-header";
import { getLoggerPlugin } from "@aws-sdk/middleware-logger";
import { getRetryPlugin, resolveRetryConfig, RetryInputConfig, RetryResolvedConfig } from "@aws-sdk/middleware-retry";
import {
AwsAuthInputConfig,
AwsAuthResolvedConfig,
getAwsAuthPlugin,
resolveAwsAuthConfig,
} from "@aws-sdk/middleware-signing";
import {
getUserAgentPlugin,
resolveUserAgentConfig,
UserAgentInputConfig,
UserAgentResolvedConfig,
} from "@aws-sdk/middleware-user-agent";
import { HttpHandler as __HttpHandler } from "@aws-sdk/protocol-http";
import {
Client as __Client,
SmithyConfiguration as __SmithyConfiguration,
SmithyResolvedConfiguration as __SmithyResolvedConfiguration,
} from "@aws-sdk/smithy-client";
import {
Credentials as __Credentials,
Decoder as __Decoder,
Encoder as __Encoder,
Hash as __Hash,
HashConstructor as __HashConstructor,
HttpHandlerOptions as __HttpHandlerOptions,
Logger as __Logger,
Provider as __Provider,
Provider,
RegionInfoProvider,
StreamCollector as __StreamCollector,
UrlParser as __UrlParser,
UserAgent as __UserAgent,
} from "@aws-sdk/types";
import {
CreateCapacityProviderCommandInput,
CreateCapacityProviderCommandOutput,
} from "./commands/CreateCapacityProviderCommand";
import { CreateClusterCommandInput, CreateClusterCommandOutput } from "./commands/CreateClusterCommand";
import { CreateServiceCommandInput, CreateServiceCommandOutput } from "./commands/CreateServiceCommand";
import { CreateTaskSetCommandInput, CreateTaskSetCommandOutput } from "./commands/CreateTaskSetCommand";
import {
DeleteAccountSettingCommandInput,
DeleteAccountSettingCommandOutput,
} from "./commands/DeleteAccountSettingCommand";
import { DeleteAttributesCommandInput, DeleteAttributesCommandOutput } from "./commands/DeleteAttributesCommand";
import {
DeleteCapacityProviderCommandInput,
DeleteCapacityProviderCommandOutput,
} from "./commands/DeleteCapacityProviderCommand";
import { DeleteClusterCommandInput, DeleteClusterCommandOutput } from "./commands/DeleteClusterCommand";
import { DeleteServiceCommandInput, DeleteServiceCommandOutput } from "./commands/DeleteServiceCommand";
import { DeleteTaskSetCommandInput, DeleteTaskSetCommandOutput } from "./commands/DeleteTaskSetCommand";
import {
DeregisterContainerInstanceCommandInput,
DeregisterContainerInstanceCommandOutput,
} from "./commands/DeregisterContainerInstanceCommand";
import {
DeregisterTaskDefinitionCommandInput,
DeregisterTaskDefinitionCommandOutput,
} from "./commands/DeregisterTaskDefinitionCommand";
import {
DescribeCapacityProvidersCommandInput,
DescribeCapacityProvidersCommandOutput,
} from "./commands/DescribeCapacityProvidersCommand";
import { DescribeClustersCommandInput, DescribeClustersCommandOutput } from "./commands/DescribeClustersCommand";
import {
DescribeContainerInstancesCommandInput,
DescribeContainerInstancesCommandOutput,
} from "./commands/DescribeContainerInstancesCommand";
import { DescribeServicesCommandInput, DescribeServicesCommandOutput } from "./commands/DescribeServicesCommand";
import {
DescribeTaskDefinitionCommandInput,
DescribeTaskDefinitionCommandOutput,
} from "./commands/DescribeTaskDefinitionCommand";
import { DescribeTasksCommandInput, DescribeTasksCommandOutput } from "./commands/DescribeTasksCommand";
import { DescribeTaskSetsCommandInput, DescribeTaskSetsCommandOutput } from "./commands/DescribeTaskSetsCommand";
import {
DiscoverPollEndpointCommandInput,
DiscoverPollEndpointCommandOutput,
} from "./commands/DiscoverPollEndpointCommand";
import { ExecuteCommandCommandInput, ExecuteCommandCommandOutput } from "./commands/ExecuteCommandCommand";
import {
ListAccountSettingsCommandInput,
ListAccountSettingsCommandOutput,
} from "./commands/ListAccountSettingsCommand";
import { ListAttributesCommandInput, ListAttributesCommandOutput } from "./commands/ListAttributesCommand";
import { ListClustersCommandInput, ListClustersCommandOutput } from "./commands/ListClustersCommand";
import {
ListContainerInstancesCommandInput,
ListContainerInstancesCommandOutput,
} from "./commands/ListContainerInstancesCommand";
import { ListServicesCommandInput, ListServicesCommandOutput } from "./commands/ListServicesCommand";
import {
ListTagsForResourceCommandInput,
ListTagsForResourceCommandOutput,
} from "./commands/ListTagsForResourceCommand";
import {
ListTaskDefinitionFamiliesCommandInput,
ListTaskDefinitionFamiliesCommandOutput,
} from "./commands/ListTaskDefinitionFamiliesCommand";
import {
ListTaskDefinitionsCommandInput,
ListTaskDefinitionsCommandOutput,
} from "./commands/ListTaskDefinitionsCommand";
import { ListTasksCommandInput, ListTasksCommandOutput } from "./commands/ListTasksCommand";
import { PutAccountSettingCommandInput, PutAccountSettingCommandOutput } from "./commands/PutAccountSettingCommand";
import {
PutAccountSettingDefaultCommandInput,
PutAccountSettingDefaultCommandOutput,
} from "./commands/PutAccountSettingDefaultCommand";
import { PutAttributesCommandInput, PutAttributesCommandOutput } from "./commands/PutAttributesCommand";
import {
PutClusterCapacityProvidersCommandInput,
PutClusterCapacityProvidersCommandOutput,
} from "./commands/PutClusterCapacityProvidersCommand";
import {
RegisterContainerInstanceCommandInput,
RegisterContainerInstanceCommandOutput,
} from "./commands/RegisterContainerInstanceCommand";
import {
RegisterTaskDefinitionCommandInput,
RegisterTaskDefinitionCommandOutput,
} from "./commands/RegisterTaskDefinitionCommand";
import { RunTaskCommandInput, RunTaskCommandOutput } from "./commands/RunTaskCommand";
import { StartTaskCommandInput, StartTaskCommandOutput } from "./commands/StartTaskCommand";
import { StopTaskCommandInput, StopTaskCommandOutput } from "./commands/StopTaskCommand";
import {
SubmitAttachmentStateChangesCommandInput,
SubmitAttachmentStateChangesCommandOutput,
} from "./commands/SubmitAttachmentStateChangesCommand";
import {
SubmitContainerStateChangeCommandInput,
SubmitContainerStateChangeCommandOutput,
} from "./commands/SubmitContainerStateChangeCommand";
import {
SubmitTaskStateChangeCommandInput,
SubmitTaskStateChangeCommandOutput,
} from "./commands/SubmitTaskStateChangeCommand";
import { TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand";
import { UntagResourceCommandInput, UntagResourceCommandOutput } from "./commands/UntagResourceCommand";
import {
UpdateCapacityProviderCommandInput,
UpdateCapacityProviderCommandOutput,
} from "./commands/UpdateCapacityProviderCommand";
import { UpdateClusterCommandInput, UpdateClusterCommandOutput } from "./commands/UpdateClusterCommand";
import {
UpdateClusterSettingsCommandInput,
UpdateClusterSettingsCommandOutput,
} from "./commands/UpdateClusterSettingsCommand";
import {
UpdateContainerAgentCommandInput,
UpdateContainerAgentCommandOutput,
} from "./commands/UpdateContainerAgentCommand";
import {
UpdateContainerInstancesStateCommandInput,
UpdateContainerInstancesStateCommandOutput,
} from "./commands/UpdateContainerInstancesStateCommand";
import { UpdateServiceCommandInput, UpdateServiceCommandOutput } from "./commands/UpdateServiceCommand";
import {
UpdateServicePrimaryTaskSetCommandInput,
UpdateServicePrimaryTaskSetCommandOutput,
} from "./commands/UpdateServicePrimaryTaskSetCommand";
import { UpdateTaskSetCommandInput, UpdateTaskSetCommandOutput } from "./commands/UpdateTaskSetCommand";
import { getRuntimeConfig as __getRuntimeConfig } from "./runtimeConfig";
export type ServiceInputTypes =
| CreateCapacityProviderCommandInput
| CreateClusterCommandInput
| CreateServiceCommandInput
| CreateTaskSetCommandInput
| DeleteAccountSettingCommandInput
| DeleteAttributesCommandInput
| DeleteCapacityProviderCommandInput
| DeleteClusterCommandInput
| DeleteServiceCommandInput
| DeleteTaskSetCommandInput
| DeregisterContainerInstanceCommandInput
| DeregisterTaskDefinitionCommandInput
| DescribeCapacityProvidersCommandInput
| DescribeClustersCommandInput
| DescribeContainerInstancesCommandInput
| DescribeServicesCommandInput
| DescribeTaskDefinitionCommandInput
| DescribeTaskSetsCommandInput
| DescribeTasksCommandInput
| DiscoverPollEndpointCommandInput
| ExecuteCommandCommandInput
| ListAccountSettingsCommandInput
| ListAttributesCommandInput
| ListClustersCommandInput
| ListContainerInstancesCommandInput
| ListServicesCommandInput
| ListTagsForResourceCommandInput
| ListTaskDefinitionFamiliesCommandInput
| ListTaskDefinitionsCommandInput
| ListTasksCommandInput
| PutAccountSettingCommandInput
| PutAccountSettingDefaultCommandInput
| PutAttributesCommandInput
| PutClusterCapacityProvidersCommandInput
| RegisterContainerInstanceCommandInput
| RegisterTaskDefinitionCommandInput
| RunTaskCommandInput
| StartTaskCommandInput
| StopTaskCommandInput
| SubmitAttachmentStateChangesCommandInput
| SubmitContainerStateChangeCommandInput
| SubmitTaskStateChangeCommandInput
| TagResourceCommandInput
| UntagResourceCommandInput
| UpdateCapacityProviderCommandInput
| UpdateClusterCommandInput
| UpdateClusterSettingsCommandInput
| UpdateContainerAgentCommandInput
| UpdateContainerInstancesStateCommandInput
| UpdateServiceCommandInput
| UpdateServicePrimaryTaskSetCommandInput
| UpdateTaskSetCommandInput;
export type ServiceOutputTypes =
| CreateCapacityProviderCommandOutput
| CreateClusterCommandOutput
| CreateServiceCommandOutput
| CreateTaskSetCommandOutput
| DeleteAccountSettingCommandOutput
| DeleteAttributesCommandOutput
| DeleteCapacityProviderCommandOutput
| DeleteClusterCommandOutput
| DeleteServiceCommandOutput
| DeleteTaskSetCommandOutput
| DeregisterContainerInstanceCommandOutput
| DeregisterTaskDefinitionCommandOutput
| DescribeCapacityProvidersCommandOutput
| DescribeClustersCommandOutput
| DescribeContainerInstancesCommandOutput
| DescribeServicesCommandOutput
| DescribeTaskDefinitionCommandOutput
| DescribeTaskSetsCommandOutput
| DescribeTasksCommandOutput
| DiscoverPollEndpointCommandOutput
| ExecuteCommandCommandOutput
| ListAccountSettingsCommandOutput
| ListAttributesCommandOutput
| ListClustersCommandOutput
| ListContainerInstancesCommandOutput
| ListServicesCommandOutput
| ListTagsForResourceCommandOutput
| ListTaskDefinitionFamiliesCommandOutput
| ListTaskDefinitionsCommandOutput
| ListTasksCommandOutput
| PutAccountSettingCommandOutput
| PutAccountSettingDefaultCommandOutput
| PutAttributesCommandOutput
| PutClusterCapacityProvidersCommandOutput
| RegisterContainerInstanceCommandOutput
| RegisterTaskDefinitionCommandOutput
| RunTaskCommandOutput
| StartTaskCommandOutput
| StopTaskCommandOutput
| SubmitAttachmentStateChangesCommandOutput
| SubmitContainerStateChangeCommandOutput
| SubmitTaskStateChangeCommandOutput
| TagResourceCommandOutput
| UntagResourceCommandOutput
| UpdateCapacityProviderCommandOutput
| UpdateClusterCommandOutput
| UpdateClusterSettingsCommandOutput
| UpdateContainerAgentCommandOutput
| UpdateContainerInstancesStateCommandOutput
| UpdateServiceCommandOutput
| UpdateServicePrimaryTaskSetCommandOutput
| UpdateTaskSetCommandOutput;
export interface ClientDefaults extends Partial<__SmithyResolvedConfiguration<__HttpHandlerOptions>> {
/**
* The HTTP handler to use. Fetch in browser and Https in Nodejs.
*/
requestHandler?: __HttpHandler;
/**
* A constructor for a class implementing the {@link __Hash} interface
* that computes the SHA-256 HMAC or checksum of a string or binary buffer.
* @internal
*/
sha256?: __HashConstructor;
/**
* The function that will be used to convert strings into HTTP endpoints.
* @internal
*/
urlParser?: __UrlParser;
/**
* A function that can calculate the length of a request body.
* @internal
*/
bodyLengthChecker?: (body: any) => number | undefined;
/**
* A function that converts a stream into an array of bytes.
* @internal
*/
streamCollector?: __StreamCollector;
/**
* The function that will be used to convert a base64-encoded string to a byte array.
* @internal
*/
base64Decoder?: __Decoder;
/**
* The function that will be used to convert binary data to a base64-encoded string.
* @internal
*/
base64Encoder?: __Encoder;
/**
* The function that will be used to convert a UTF8-encoded string to a byte array.
* @internal
*/
utf8Decoder?: __Decoder;
/**
* The function that will be used to convert binary data to a UTF-8 encoded string.
* @internal
*/
utf8Encoder?: __Encoder;
/**
* The runtime environment.
* @internal
*/
runtime?: string;
/**
* Disable dyanamically changing the endpoint of the client based on the hostPrefix
* trait of an operation.
*/
disableHostPrefix?: boolean;
/**
* Value for how many times a request will be made at most in case of retry.
*/
maxAttempts?: number | __Provider<number>;
/**
* Specifies which retry algorithm to use.
*/
retryMode?: string | __Provider<string>;
/**
* Optional logger for logging debug/info/warn/error.
*/
logger?: __Logger;
/**
* Unique service identifier.
* @internal
*/
serviceId?: string;
/**
* The AWS region to which this client will send requests
*/
region?: string | __Provider<string>;
/**
* Default credentials provider; Not available in browser runtime.
* @internal
*/
credentialDefaultProvider?: (input: any) => __Provider<__Credentials>;
/**
* Fetch related hostname, signing name or signing region with given region.
* @internal
*/
regionInfoProvider?: RegionInfoProvider;
/**
* The provider populating default tracking information to be sent with `user-agent`, `x-amz-user-agent` header
* @internal
*/
defaultUserAgentProvider?: Provider<__UserAgent>;
}
type ECSClientConfigType = Partial<__SmithyConfiguration<__HttpHandlerOptions>> &
ClientDefaults &
RegionInputConfig &
EndpointsInputConfig &
RetryInputConfig &
HostHeaderInputConfig &
AwsAuthInputConfig &
UserAgentInputConfig;
/**
* The configuration interface of ECSClient class constructor that set the region, credentials and other options.
*/
export interface ECSClientConfig extends ECSClientConfigType {}
type ECSClientResolvedConfigType = __SmithyResolvedConfiguration<__HttpHandlerOptions> &
Required<ClientDefaults> &
RegionResolvedConfig &
EndpointsResolvedConfig &
RetryResolvedConfig &
HostHeaderResolvedConfig &
AwsAuthResolvedConfig &
UserAgentResolvedConfig;
/**
* The resolved configuration interface of ECSClient class. This is resolved and normalized from the {@link ECSClientConfig | constructor configuration interface}.
*/
export interface ECSClientResolvedConfig extends ECSClientResolvedConfigType {}
/**
* <fullname>Amazon Elastic Container Service</fullname>
* <p>Amazon Elastic Container Service (Amazon ECS) is a highly scalable, fast, container management service that makes
* it easy to run, stop, and manage Docker containers on a cluster. You can host your
* cluster on a serverless infrastructure that is managed by Amazon ECS by launching your
* services or tasks on Fargate. For more control, you can host your tasks on a cluster
* of Amazon Elastic Compute Cloud (Amazon EC2) instances that you manage.</p>
* <p>Amazon ECS makes it easy to launch and stop container-based applications with simple API
* calls, allows you to get the state of your cluster from a centralized service, and gives
* you access to many familiar Amazon EC2 features.</p>
* <p>You can use Amazon ECS to schedule the placement of containers across your cluster based on
* your resource needs, isolation policies, and availability requirements. Amazon ECS eliminates
* the need for you to operate your own cluster management and configuration management
* systems or worry about scaling your management infrastructure.</p>
*/
export class ECSClient extends __Client<
__HttpHandlerOptions,
ServiceInputTypes,
ServiceOutputTypes,
ECSClientResolvedConfig
> {
/**
* The resolved configuration of ECSClient class. This is resolved and normalized from the {@link ECSClientConfig | constructor configuration interface}.
*/
readonly config: ECSClientResolvedConfig;
constructor(configuration: ECSClientConfig) {
const _config_0 = __getRuntimeConfig(configuration);
const _config_1 = resolveRegionConfig(_config_0);
const _config_2 = resolveEndpointsConfig(_config_1);
const _config_3 = resolveRetryConfig(_config_2);
const _config_4 = resolveHostHeaderConfig(_config_3);
const _config_5 = resolveAwsAuthConfig(_config_4);
const _config_6 = resolveUserAgentConfig(_config_5);
super(_config_6);
this.config = _config_6;
this.middlewareStack.use(getRetryPlugin(this.config));
this.middlewareStack.use(getContentLengthPlugin(this.config));
this.middlewareStack.use(getHostHeaderPlugin(this.config));
this.middlewareStack.use(getLoggerPlugin(this.config));
this.middlewareStack.use(getAwsAuthPlugin(this.config));
this.middlewareStack.use(getUserAgentPlugin(this.config));
}
/**
* Destroy underlying resources, like sockets. It's usually not necessary to do this.
* However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed.
* Otherwise, sockets might stay open for quite a long time before the server terminates them.
*/
destroy(): void {
super.destroy();
}
} | the_stack |
declare module "cluster" {
import * as child from "child_process";
import * as events from "events";
import * as net from "net";
// interfaces
interface ClusterSettings {
execArgv?: string[]; // default: process.execArgv
exec?: string;
args?: string[];
silent?: boolean;
stdio?: any[];
uid?: number;
gid?: number;
inspectPort?: number | (() => number);
}
interface Address {
address: string;
port: number;
addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6"
}
class Worker extends events.EventEmitter {
id: number;
process: child.ChildProcess;
send(message: child.Serializable, sendHandle?: child.SendHandle, callback?: (error: Error | null) => void): boolean;
kill(signal?: string): void;
destroy(signal?: string): void;
disconnect(): void;
isConnected(): boolean;
isDead(): boolean;
exitedAfterDisconnect: boolean;
/**
* events.EventEmitter
* 1. disconnect
* 2. error
* 3. exit
* 4. listening
* 5. message
* 6. online
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "disconnect", listener: () => void): this;
addListener(event: "error", listener: (error: Error) => void): this;
addListener(event: "exit", listener: (code: number, signal: string) => void): this;
addListener(event: "listening", listener: (address: Address) => void): this;
addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
addListener(event: "online", listener: () => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "disconnect"): boolean;
emit(event: "error", error: Error): boolean;
emit(event: "exit", code: number, signal: string): boolean;
emit(event: "listening", address: Address): boolean;
emit(event: "message", message: any, handle: net.Socket | net.Server): boolean;
emit(event: "online"): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "disconnect", listener: () => void): this;
on(event: "error", listener: (error: Error) => void): this;
on(event: "exit", listener: (code: number, signal: string) => void): this;
on(event: "listening", listener: (address: Address) => void): this;
on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
on(event: "online", listener: () => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "disconnect", listener: () => void): this;
once(event: "error", listener: (error: Error) => void): this;
once(event: "exit", listener: (code: number, signal: string) => void): this;
once(event: "listening", listener: (address: Address) => void): this;
once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
once(event: "online", listener: () => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "disconnect", listener: () => void): this;
prependListener(event: "error", listener: (error: Error) => void): this;
prependListener(event: "exit", listener: (code: number, signal: string) => void): this;
prependListener(event: "listening", listener: (address: Address) => void): this;
prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
prependListener(event: "online", listener: () => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "disconnect", listener: () => void): this;
prependOnceListener(event: "error", listener: (error: Error) => void): this;
prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this;
prependOnceListener(event: "listening", listener: (address: Address) => void): this;
prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
prependOnceListener(event: "online", listener: () => void): this;
}
interface Cluster extends events.EventEmitter {
Worker: Worker;
disconnect(callback?: () => void): void;
fork(env?: any): Worker;
isMaster: boolean;
isWorker: boolean;
schedulingPolicy: number;
settings: ClusterSettings;
setupMaster(settings?: ClusterSettings): void;
worker?: Worker;
workers?: {
[index: string]: Worker | undefined
};
readonly SCHED_NONE: number;
readonly SCHED_RR: number;
/**
* events.EventEmitter
* 1. disconnect
* 2. exit
* 3. fork
* 4. listening
* 5. message
* 6. online
* 7. setup
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "disconnect", listener: (worker: Worker) => void): this;
addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
addListener(event: "fork", listener: (worker: Worker) => void): this;
addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
addListener(event: "online", listener: (worker: Worker) => void): this;
addListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "disconnect", worker: Worker): boolean;
emit(event: "exit", worker: Worker, code: number, signal: string): boolean;
emit(event: "fork", worker: Worker): boolean;
emit(event: "listening", worker: Worker, address: Address): boolean;
emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean;
emit(event: "online", worker: Worker): boolean;
emit(event: "setup", settings: ClusterSettings): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "disconnect", listener: (worker: Worker) => void): this;
on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
on(event: "fork", listener: (worker: Worker) => void): this;
on(event: "listening", listener: (worker: Worker, address: Address) => void): this;
on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
on(event: "online", listener: (worker: Worker) => void): this;
on(event: "setup", listener: (settings: ClusterSettings) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "disconnect", listener: (worker: Worker) => void): this;
once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
once(event: "fork", listener: (worker: Worker) => void): this;
once(event: "listening", listener: (worker: Worker, address: Address) => void): this;
once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
once(event: "online", listener: (worker: Worker) => void): this;
once(event: "setup", listener: (settings: ClusterSettings) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "disconnect", listener: (worker: Worker) => void): this;
prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
prependListener(event: "fork", listener: (worker: Worker) => void): this;
prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
prependListener(event: "online", listener: (worker: Worker) => void): this;
prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this;
prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
prependOnceListener(event: "fork", listener: (worker: Worker) => void): this;
prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
// the handle is a net.Socket or net.Server object, or undefined.
prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this;
prependOnceListener(event: "online", listener: (worker: Worker) => void): this;
prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
}
const SCHED_NONE: number;
const SCHED_RR: number;
function disconnect(callback?: () => void): void;
function fork(env?: any): Worker;
const isMaster: boolean;
const isWorker: boolean;
let schedulingPolicy: number;
const settings: ClusterSettings;
function setupMaster(settings?: ClusterSettings): void;
const worker: Worker;
const workers: {
[index: string]: Worker | undefined
};
/**
* events.EventEmitter
* 1. disconnect
* 2. exit
* 3. fork
* 4. listening
* 5. message
* 6. online
* 7. setup
*/
function addListener(event: string, listener: (...args: any[]) => void): Cluster;
function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster;
function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
function addListener(event: "fork", listener: (worker: Worker) => void): Cluster;
function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
// the handle is a net.Socket or net.Server object, or undefined.
function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster;
function addListener(event: "online", listener: (worker: Worker) => void): Cluster;
function addListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster;
function emit(event: string | symbol, ...args: any[]): boolean;
function emit(event: "disconnect", worker: Worker): boolean;
function emit(event: "exit", worker: Worker, code: number, signal: string): boolean;
function emit(event: "fork", worker: Worker): boolean;
function emit(event: "listening", worker: Worker, address: Address): boolean;
function emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean;
function emit(event: "online", worker: Worker): boolean;
function emit(event: "setup", settings: ClusterSettings): boolean;
function on(event: string, listener: (...args: any[]) => void): Cluster;
function on(event: "disconnect", listener: (worker: Worker) => void): Cluster;
function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
function on(event: "fork", listener: (worker: Worker) => void): Cluster;
function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined.
function on(event: "online", listener: (worker: Worker) => void): Cluster;
function on(event: "setup", listener: (settings: ClusterSettings) => void): Cluster;
function once(event: string, listener: (...args: any[]) => void): Cluster;
function once(event: "disconnect", listener: (worker: Worker) => void): Cluster;
function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
function once(event: "fork", listener: (worker: Worker) => void): Cluster;
function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined.
function once(event: "online", listener: (worker: Worker) => void): Cluster;
function once(event: "setup", listener: (settings: ClusterSettings) => void): Cluster;
function removeListener(event: string, listener: (...args: any[]) => void): Cluster;
function removeAllListeners(event?: string): Cluster;
function setMaxListeners(n: number): Cluster;
function getMaxListeners(): number;
function listeners(event: string): Function[];
function listenerCount(type: string): number;
function prependListener(event: string, listener: (...args: any[]) => void): Cluster;
function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster;
function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster;
function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
// the handle is a net.Socket or net.Server object, or undefined.
function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster;
function prependListener(event: "online", listener: (worker: Worker) => void): Cluster;
function prependListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster;
function prependOnceListener(event: string, listener: (...args: any[]) => void): Cluster;
function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster;
function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster;
function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
// the handle is a net.Socket or net.Server object, or undefined.
function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster;
function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster;
function prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster;
function eventNames(): string[];
} | the_stack |
const powerOfTwo = [
0x1,
0x2,
0x4,
0x8,
0x10,
0x20,
0x40,
0x80,
0x100,
0x200,
0x400,
0x800,
0x1000,
0x2000,
0x4000,
0x8000,
0x10000,
0x20000,
0x40000,
0x80000,
0x100000,
0x200000,
0x400000,
0x800000,
0x1000000,
0x2000000,
0x4000000,
0x8000000,
0x10000000,
0x20000000,
0x40000000,
0x80000000,
0x100000000,
0x200000000,
0x400000000,
0x800000000,
0x1000000000,
0x2000000000,
0x4000000000,
0x8000000000,
0x10000000000,
0x20000000000,
0x40000000000,
0x80000000000,
0x100000000000,
0x200000000000,
0x400000000000,
0x800000000000,
0x1000000000000,
0x2000000000000,
0x4000000000000,
0x8000000000000,
0x10000000000000 // Math.pow(2, 52), highest bit that can be set correctly.
];
/**
* The `TileKey` instances are used to address a tile in a quadtree.
*
* A tile key is defined by a row, a column, and a level. The tree has a root at level 0, with one
* single tile. On every level, each tile is divided into four children (therefore the name
* quadtree).
*
* Within each [[level]], any particular tile is addressed with [[row]] and [[column]]. The number
* of rows and columns in each level is 2 to the power of the level. This means: On level 0, only
* one tile exists, [[columnsAtLevel]]() and [[rowsAtLevel]]() are both 1. On level 1, 4 tiles
* exist, in 2 rows and 2 columns. On level 2 we have 16 tiles, in 4 rows and 4 columns. And so on.
*
* A tile key is usually created using [[fromRowColumnLevel]]() method.
*
* `TileKey` instances are immutable, all members return new instances of `TileKey` and do not
* modify the original object.
*
* Utility functions like [[parent]](), [[changedLevelBy]](), and [[changedLevelTo]]() allow for
* easy vertical navigation of the tree. The number of available rows and columns in the tile's
* level is given with [[rowCount]]() and [[columnCount]]().
*
* Tile keys can be created from and converted into various alternative formats:
*
* - [[toQuadKey]]() / [[fromQuadKey]]() - string representation 4-based
* - [[toHereTile]]() / [[fromHereTile]]() - string representation 10-based
* - [[mortonCode]]() / [[fromMortonCode]]() - number representation
*
* Note - as JavaScript's number type can hold 53 bits in its mantissa, only levels up to 26 can be
* represented in the number representation returned by [[mortonCode]]().
*/
export class TileKey {
/**
* Creates a tile key.
*
* @param row - The requested row. Must be less than 2 to the power of level.
* @param column - The requested column. Must be less than 2 to the power of level.
* @param level - The requested level.
*/
static fromRowColumnLevel(row: number, column: number, level: number): TileKey {
return new TileKey(row, column, level);
}
/**
* Creates a tile key from a quad string.
*
* The quad string can be created with [[toQuadKey]].
*
* @param quadkey - The quadkey to convert.
* @returns A new instance of `TileKey`.
*/
static fromQuadKey(quadkey: string): TileKey {
const level = quadkey.length;
let row = 0;
let column = 0;
for (let i = 0; i < quadkey.length; ++i) {
const mask = 1 << i;
const d = parseInt(quadkey.charAt(level - i - 1), 10);
if (d & 0x1) {
column |= mask;
}
if (d & 0x2) {
row |= mask;
}
}
return TileKey.fromRowColumnLevel(row, column, level);
}
/**
* Creates a tile key from a numeric Morton code representation.
*
* You can convert a tile key into a numeric Morton code with [[mortonCode]].
*
* @param quadKey64 - The Morton code to be converted.
* @returns A new instance of {@link TileKey}.
*/
static fromMortonCode(quadKey64: number): TileKey {
let level = 0;
let row = 0;
let column = 0;
let quadKey = quadKey64;
while (quadKey > 1) {
const mask: number = 1 << level;
if (quadKey & 0x1) {
column |= mask;
}
if (quadKey & 0x2) {
row |= mask;
}
level++;
quadKey = (quadKey - (quadKey & 0x3)) / 4;
}
const result = TileKey.fromRowColumnLevel(row, column, level);
result.m_mortonCode = quadKey64;
return result;
}
/**
* Creates a tile key from a heretile code string.
*
* The string can be created with [[toHereTile]].
*
* @param quadkey64 - The string representation of the HERE tile key.
* @returns A new instance of `TileKey`.
*/
static fromHereTile(quadkey64: string): TileKey {
const result = TileKey.fromMortonCode(parseInt(quadkey64, 10));
result.m_hereTile = quadkey64;
return result;
}
/**
* Returns the number of available columns at a given level.
*
* This is 2 to the power of the level.
*
* @param level - The level for which to return the number of columns.
* @returns The available columns at the given level.
*/
static columnsAtLevel(level: number): number {
return Math.pow(2, level);
}
/**
* Returns the number of available rows at a given level.
*
* This is 2 to the power of the level.
*
* @param level - The level for which to return the number of rows.
* @returns The available rows at the given level.
*/
static rowsAtLevel(level: number): number {
return Math.pow(2, level);
}
/**
* Returns the closest matching `TileKey` in a cartesian coordinate system.
*
* @param level - The level for the tile key.
* @param coordX - The X coordinate.
* @param coordY - The Y coordinate.
* @param totalWidth - The maximum X coordinate.
* @param totalHeight - The maximum Y coordinate.
* @returns A new tile key at the given level that includes the given coordinates.
*/
static atCoords(
level: number,
coordX: number,
coordY: number,
totalWidth: number,
totalHeight: number
): TileKey {
return TileKey.fromRowColumnLevel(
Math.floor(coordY / (totalHeight / TileKey.rowsAtLevel(level))),
Math.floor(coordX / (totalWidth / TileKey.columnsAtLevel(level))),
level
);
}
/**
* Computes the Morton code of the parent tile key of the given Morton code.
*
* Note: The parent key of the root key is the root key itself.
*
* @param mortonCode - A Morton code, for example, obtained from [[mortonCode]].
* @returns The Morton code of the parent tile.
*/
static parentMortonCode(mortonCode: number): number {
return Math.floor(mortonCode / 4);
}
private m_mortonCode?: number;
private m_hereTile?: string;
/**
* Constructs a new immutable instance of a `TileKey`.
*
* For the better readability, {@link TileKey.fromRowColumnLevel} should be preferred.
*
* Note - row and column must not be greater than the maximum rows/columns for the given level.
*
* @param row - Represents the row in the quadtree.
* @param column - Represents the column in the quadtree.
* @param level - Represents the level in the quadtree.
*/
constructor(readonly row: number, readonly column: number, readonly level: number) {}
/**
* Returns a tile key representing the parent of the tile addressed by this tile key.
*
* Throws an exception is this tile is already the root.
*/
parent(): TileKey {
if (this.level === 0) {
throw new Error("Cannot get the parent of the root tile key");
}
return TileKey.fromRowColumnLevel(this.row >>> 1, this.column >>> 1, this.level - 1);
}
/**
* Returns a new tile key at a level that differs from this tile's level by delta.
*
* Equivalent to `changedLevelTo(level() + delta)`.
*
* Note - root key is returned if `delta` is smaller than the level of this tile key.
*
* @param delta - The numeric difference between the current level and the requested level.
*/
changedLevelBy(delta: number): TileKey {
const level = Math.max(0, this.level + delta);
let row = this.row;
let column = this.column;
if (delta >= 0) {
row <<= delta;
column <<= delta;
} else {
row >>>= -delta;
column >>>= -delta;
}
return TileKey.fromRowColumnLevel(row, column, level);
}
/**
* Returns a new tile key at the requested level.
*
* If the requested level is smaller than the tile's level, then the key of an ancestor of this
* tile is returned. If the requested level is larger than the tile's level, then the key of
* first child or grandchild of this tile is returned, for example, the child with the lowest
* row and column number. If the requested level equals this tile's level, then the tile key
* itself is returned. If the requested level is negative, the root tile key is returned.
*
* @param level - The requested level.
*/
changedLevelTo(level: number): TileKey {
return this.changedLevelBy(level - this.level);
}
/**
* Converts the tile key to a numeric code representation.
*
* You can create a tile key from a numeric Morton code with [[fromMortonCode]].
*
* Note - only levels <= 26 are supported.
*/
mortonCode(): number {
if (this.m_mortonCode === undefined) {
let column = this.column;
let row = this.row;
let result = powerOfTwo[this.level << 1];
for (let i = 0; i < this.level; ++i) {
if (column & 0x1) {
result += powerOfTwo[2 * i];
}
if (row & 0x1) {
result += powerOfTwo[2 * i + 1];
}
column >>>= 1;
row >>>= 1;
}
this.m_mortonCode = result;
}
return this.m_mortonCode;
}
/**
* Converts the tile key into a string for using in REST API calls.
*
* The string is a quadkey Morton code representation as a string.
*
* You can convert back from a quadkey string with [[fromHereTile]].
*/
toHereTile(): string {
if (this.m_hereTile === undefined) {
this.m_hereTile = this.mortonCode().toString();
}
return this.m_hereTile;
}
/**
* Converts the tile key into a string for using in REST API calls.
*
* If the tile is the root tile, the quadkey is '-'. Otherwise the string is a number to the
* base of 4, but without the leading 1, with the following properties:
* 1. the number of digits equals the level.
* 2. removing the last digit gives the parent tile's quadkey string, i.e. appending 0,1,2,3
* to a quadkey string gives the tiles's children.
*
* You can convert back from a quadkey string with [[fromQuadKey]].
*/
toQuadKey(): string {
let result: string = "";
for (let i = this.level; i > 0; --i) {
const mask = 1 << (i - 1);
const col = (this.column & mask) !== 0;
const row = (this.row & mask) !== 0;
if (col && row) {
result += "3";
} else if (row) {
result += "2";
} else if (col) {
result += "1";
} else {
result += "0";
}
}
return result;
}
/**
* Equality operator.
*
* @param qnr - The tile key to compare to.
* @returns `true` if this tile key has identical row, column and level, `false` otherwise.
*/
equals(qnr: TileKey): boolean {
return this.row === qnr.row && this.column === qnr.column && this.level === qnr.level;
}
/**
* Returns the absolute quadkey that is constructed from its sub quadkey.
*
* @param sub - The sub key.
* @returns The absolute tile key in the quadtree.
*/
addedSubKey(sub: string): TileKey {
const subQuad = TileKey.fromQuadKey(sub.length === 0 ? "-" : sub);
const child = this.changedLevelBy(subQuad.level);
return TileKey.fromRowColumnLevel(
child.row + subQuad.row,
child.column + subQuad.column,
child.level
);
}
/**
* Returns the absolute quadkey that is constructed from its sub HERE tile key.
*
* @param sub - The sub HERE key.
* @returns The absolute tile key in the quadtree.
*/
addedSubHereTile(sub: string): TileKey {
const subQuad = TileKey.fromHereTile(sub);
const child = this.changedLevelBy(subQuad.level);
return TileKey.fromRowColumnLevel(
child.row + subQuad.row,
child.column + subQuad.column,
child.level
);
}
/**
* Returns a sub quadkey that is relative to its parent.
*
* This function can be used to generate sub keys that are relative to a parent that is delta
* levels up in the quadtree.
*
* This function can be used to create shortened keys for quads on lower levels if the parent is
* known.
*
* Note - the sub quadkeys fit in a 16-bit unsigned integer if the `delta` is smaller than 8. If
* `delta` is smaller than 16, the sub quadkey fits into an unsigned 32-bit integer.
*
* Deltas larger than 16 are not supported.
*
* @param delta - The number of levels relative to its parent quadkey. Must be greater or equal
* to 0 and smaller than 16.
* @returns The quadkey relative to its parent that is `delta` levels up the tree.
*/
getSubHereTile(delta: number): string {
const key = this.mortonCode();
const msb = 1 << (delta * 2);
const mask = msb - 1;
const result = (key & mask) | msb;
return result.toString();
}
/**
* Returns the number of available rows in the tile's [[level]].
*
* This is 2 to the power of the level.
*/
rowCount(): number {
return TileKey.rowsAtLevel(this.level);
}
/**
* Returns the number of available columns in the tile's [[level]].
*
* This is 2 to the power of the level.
*/
columnCount(): number {
return TileKey.columnsAtLevel(this.level);
}
} | 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 apikeys_v2 {
export interface Options extends GlobalOptions {
version: 'v2';
}
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;
}
/**
* API Keys API
*
* Manages the API keys associated with developer projects.
*
* @example
* ```js
* const {google} = require('googleapis');
* const apikeys = google.apikeys('v2');
* ```
*/
export class Apikeys {
context: APIRequestContext;
keys: Resource$Keys;
operations: Resource$Operations;
projects: Resource$Projects;
constructor(options: GlobalOptions, google?: GoogleConfigurable) {
this.context = {
_options: options || {},
google,
};
this.keys = new Resource$Keys(this.context);
this.operations = new Resource$Operations(this.context);
this.projects = new Resource$Projects(this.context);
}
}
/**
* This resource represents a long-running operation that is the result of a network API call.
*/
export interface Schema$Operation {
/**
* If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.
*/
done?: boolean | null;
/**
* The error result of the operation in case of failure or cancellation.
*/
error?: Schema$Status;
/**
* Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.
*/
metadata?: {[key: string]: any} | null;
/**
* The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id\}`.
*/
name?: string | null;
/**
* The normal response of the operation in case of success. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.
*/
response?: {[key: string]: any} | null;
}
/**
* The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
*/
export interface Schema$Status {
/**
* The status code, which should be an enum value of google.rpc.Code.
*/
code?: number | null;
/**
* A list of messages that carry the error details. There is a common set of message types for APIs to use.
*/
details?: Array<{[key: string]: any}> | null;
/**
* A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.
*/
message?: string | null;
}
/**
* Identifier of an Android application for key use.
*/
export interface Schema$V2AndroidApplication {
/**
* The package name of the application.
*/
packageName?: string | null;
/**
* The SHA1 fingerprint of the application. For example, both sha1 formats are acceptable : DA:39:A3:EE:5E:6B:4B:0D:32:55:BF:EF:95:60:18:90:AF:D8:07:09 or DA39A3EE5E6B4B0D3255BFEF95601890AFD80709. Output format is the latter.
*/
sha1Fingerprint?: string | null;
}
/**
* The Android apps that are allowed to use the key.
*/
export interface Schema$V2AndroidKeyRestrictions {
/**
* A list of Android applications that are allowed to make API calls with this key.
*/
allowedApplications?: Schema$V2AndroidApplication[];
}
/**
* A restriction for a specific service and optionally one or multiple specific methods. Both fields are case insensitive.
*/
export interface Schema$V2ApiTarget {
/**
* Optional. List of one or more methods that can be called. If empty, all methods for the service are allowed. A wildcard (*) can be used as the last symbol. Valid examples: `google.cloud.translate.v2.TranslateService.GetSupportedLanguage` `TranslateText` `Get*` `translate.googleapis.com.Get*`
*/
methods?: string[] | null;
/**
* The service for this restriction. It should be the canonical service name, for example: `translate.googleapis.com`. You can use [`gcloud services list`](/sdk/gcloud/reference/services/list) to get a list of services that are enabled in the project.
*/
service?: string | null;
}
/**
* The HTTP referrers (websites) that are allowed to use the key.
*/
export interface Schema$V2BrowserKeyRestrictions {
/**
* A list of regular expressions for the referrer URLs that are allowed to make API calls with this key.
*/
allowedReferrers?: string[] | null;
}
/**
* Response message for `GetKeyString` method.
*/
export interface Schema$V2GetKeyStringResponse {
/**
* An encrypted and signed value of the key.
*/
keyString?: string | null;
}
/**
* The iOS apps that are allowed to use the key.
*/
export interface Schema$V2IosKeyRestrictions {
/**
* A list of bundle IDs that are allowed when making API calls with this key.
*/
allowedBundleIds?: string[] | null;
}
/**
* The representation of a key managed by the API Keys API.
*/
export interface Schema$V2Key {
/**
* Annotations is an unstructured key-value map stored with a policy that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects.
*/
annotations?: {[key: string]: string} | null;
/**
* Output only. A timestamp identifying the time this key was originally created.
*/
createTime?: string | null;
/**
* Output only. A timestamp when this key was deleted. If the resource is not deleted, this must be empty.
*/
deleteTime?: string | null;
/**
* Human-readable display name of this key that you can modify. The maximum length is 63 characters.
*/
displayName?: string | null;
/**
* Output only. A checksum computed by the server based on the current value of the Key resource. This may be sent on update and delete requests to ensure the client has an up-to-date value before proceeding. See https://google.aip.dev/154.
*/
etag?: string | null;
/**
* Output only. An encrypted and signed value held by this key. This field can be accessed only through the `GetKeyString` method.
*/
keyString?: string | null;
/**
* Output only. The resource name of the key. The `name` has the form: `projects//locations/global/keys/`. For example: `projects/123456867718/locations/global/keys/b7ff1f9f-8275-410a-94dd-3855ee9b5dd2` NOTE: Key is a global resource; hence the only supported value for location is `global`.
*/
name?: string | null;
/**
* Key restrictions.
*/
restrictions?: Schema$V2Restrictions;
/**
* Output only. Unique id in UUID4 format.
*/
uid?: string | null;
/**
* Output only. A timestamp identifying the time this key was last updated.
*/
updateTime?: string | null;
}
/**
* Response message for `ListKeys` method.
*/
export interface Schema$V2ListKeysResponse {
/**
* A list of API keys.
*/
keys?: Schema$V2Key[];
/**
* The pagination token for the next page of results.
*/
nextPageToken?: string | null;
}
/**
* Response message for `LookupKey` method.
*/
export interface Schema$V2LookupKeyResponse {
/**
* The resource name of the API key. If the API key has been purged, resource name is empty.
*/
name?: string | null;
/**
* The project that owns the key with the value specified in the request.
*/
parent?: string | null;
}
/**
* Describes the restrictions on the key.
*/
export interface Schema$V2Restrictions {
/**
* The Android apps that are allowed to use the key.
*/
androidKeyRestrictions?: Schema$V2AndroidKeyRestrictions;
/**
* A restriction for a specific service and optionally one or more specific methods. Requests are allowed if they match any of these restrictions. If no restrictions are specified, all targets are allowed.
*/
apiTargets?: Schema$V2ApiTarget[];
/**
* The HTTP referrers (websites) that are allowed to use the key.
*/
browserKeyRestrictions?: Schema$V2BrowserKeyRestrictions;
/**
* The iOS apps that are allowed to use the key.
*/
iosKeyRestrictions?: Schema$V2IosKeyRestrictions;
/**
* The IP addresses of callers that are allowed to use the key.
*/
serverKeyRestrictions?: Schema$V2ServerKeyRestrictions;
}
/**
* The IP addresses of callers that are allowed to use the key.
*/
export interface Schema$V2ServerKeyRestrictions {
/**
* A list of the caller IP addresses that are allowed to make API calls with this key.
*/
allowedIps?: string[] | null;
}
/**
* Request message for `UndeleteKey` method.
*/
export interface Schema$V2UndeleteKeyRequest {}
export class Resource$Keys {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* Find the parent project and resource name of the API key that matches the key string in the request. If the API key has been purged, resource name will not be set. The service account must have the `apikeys.keys.lookup` permission on the parent project.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/apikeys.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 apikeys = google.apikeys('v2');
*
* 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',
* 'https://www.googleapis.com/auth/cloud-platform.read-only',
* ],
* });
*
* // 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 apikeys.keys.lookupKey({
* // Required. Finds the project that owns the key string value.
* keyString: 'placeholder-value',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "name": "my_name",
* // "parent": "my_parent"
* // }
* }
*
* 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.
*/
lookupKey(
params: Params$Resource$Keys$Lookupkey,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
lookupKey(
params?: Params$Resource$Keys$Lookupkey,
options?: MethodOptions
): GaxiosPromise<Schema$V2LookupKeyResponse>;
lookupKey(
params: Params$Resource$Keys$Lookupkey,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
lookupKey(
params: Params$Resource$Keys$Lookupkey,
options: MethodOptions | BodyResponseCallback<Schema$V2LookupKeyResponse>,
callback: BodyResponseCallback<Schema$V2LookupKeyResponse>
): void;
lookupKey(
params: Params$Resource$Keys$Lookupkey,
callback: BodyResponseCallback<Schema$V2LookupKeyResponse>
): void;
lookupKey(callback: BodyResponseCallback<Schema$V2LookupKeyResponse>): void;
lookupKey(
paramsOrCallback?:
| Params$Resource$Keys$Lookupkey
| BodyResponseCallback<Schema$V2LookupKeyResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$V2LookupKeyResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$V2LookupKeyResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$V2LookupKeyResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback || {}) as Params$Resource$Keys$Lookupkey;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Keys$Lookupkey;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://apikeys.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v2/keys:lookupKey').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: [],
pathParams: [],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$V2LookupKeyResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$V2LookupKeyResponse>(parameters);
}
}
}
export interface Params$Resource$Keys$Lookupkey extends StandardParameters {
/**
* Required. Finds the project that owns the key string value.
*/
keyString?: string;
}
export class Resource$Operations {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/apikeys.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 apikeys = google.apikeys('v2');
*
* 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',
* 'https://www.googleapis.com/auth/cloud-platform.read-only',
* ],
* });
*
* // 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 apikeys.operations.get({
* // The name of the operation resource.
* name: 'operations/my-operation',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "done": false,
* // "error": {},
* // "metadata": {},
* // "name": "my_name",
* // "response": {}
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
get(
params: Params$Resource$Operations$Get,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
get(
params?: Params$Resource$Operations$Get,
options?: MethodOptions
): GaxiosPromise<Schema$Operation>;
get(
params: Params$Resource$Operations$Get,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
get(
params: Params$Resource$Operations$Get,
options: MethodOptions | BodyResponseCallback<Schema$Operation>,
callback: BodyResponseCallback<Schema$Operation>
): void;
get(
params: Params$Resource$Operations$Get,
callback: BodyResponseCallback<Schema$Operation>
): void;
get(callback: BodyResponseCallback<Schema$Operation>): void;
get(
paramsOrCallback?:
| Params$Resource$Operations$Get
| BodyResponseCallback<Schema$Operation>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$Operation>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$Operation>
| BodyResponseCallback<Readable>
): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> {
let params = (paramsOrCallback || {}) as Params$Resource$Operations$Get;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Operations$Get;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://apikeys.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$Operation>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$Operation>(parameters);
}
}
}
export interface Params$Resource$Operations$Get extends StandardParameters {
/**
* The name of the operation resource.
*/
name?: string;
}
export class Resource$Projects {
context: APIRequestContext;
locations: Resource$Projects$Locations;
constructor(context: APIRequestContext) {
this.context = context;
this.locations = new Resource$Projects$Locations(this.context);
}
}
export class Resource$Projects$Locations {
context: APIRequestContext;
keys: Resource$Projects$Locations$Keys;
constructor(context: APIRequestContext) {
this.context = context;
this.keys = new Resource$Projects$Locations$Keys(this.context);
}
}
export class Resource$Projects$Locations$Keys {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* Creates a new API key. NOTE: Key is a global resource; hence the only supported value for location is `global`.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/apikeys.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 apikeys = google.apikeys('v2');
*
* 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 apikeys.projects.locations.keys.create({
* // User specified key id (optional). If specified, it will become the final component of the key resource name. The id must be unique within the project, must conform with RFC-1034, is restricted to lower-cased letters, and has a maximum length of 63 characters. In another word, the id must match the regular expression: `[a-z]([a-z0-9-]{0,61\}[a-z0-9])?`. The id must NOT be a UUID-like string.
* keyId: 'placeholder-value',
* // Required. The project in which the API key is created.
* parent: 'projects/my-project/locations/my-location',
*
* // Request body metadata
* requestBody: {
* // request body parameters
* // {
* // "annotations": {},
* // "createTime": "my_createTime",
* // "deleteTime": "my_deleteTime",
* // "displayName": "my_displayName",
* // "etag": "my_etag",
* // "keyString": "my_keyString",
* // "name": "my_name",
* // "restrictions": {},
* // "uid": "my_uid",
* // "updateTime": "my_updateTime"
* // }
* },
* });
* console.log(res.data);
*
* // Example response
* // {
* // "done": false,
* // "error": {},
* // "metadata": {},
* // "name": "my_name",
* // "response": {}
* // }
* }
*
* 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.
*/
create(
params: Params$Resource$Projects$Locations$Keys$Create,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
create(
params?: Params$Resource$Projects$Locations$Keys$Create,
options?: MethodOptions
): GaxiosPromise<Schema$Operation>;
create(
params: Params$Resource$Projects$Locations$Keys$Create,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
create(
params: Params$Resource$Projects$Locations$Keys$Create,
options: MethodOptions | BodyResponseCallback<Schema$Operation>,
callback: BodyResponseCallback<Schema$Operation>
): void;
create(
params: Params$Resource$Projects$Locations$Keys$Create,
callback: BodyResponseCallback<Schema$Operation>
): void;
create(callback: BodyResponseCallback<Schema$Operation>): void;
create(
paramsOrCallback?:
| Params$Resource$Projects$Locations$Keys$Create
| BodyResponseCallback<Schema$Operation>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$Operation>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$Operation>
| BodyResponseCallback<Readable>
): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Projects$Locations$Keys$Create;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Projects$Locations$Keys$Create;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://apikeys.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v2/{+parent}/keys').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST',
},
options
),
params,
requiredParams: ['parent'],
pathParams: ['parent'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$Operation>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$Operation>(parameters);
}
}
/**
* Deletes an API key. Deleted key can be retrieved within 30 days of deletion. Afterward, key will be purged from the project. NOTE: Key is a global resource; hence the only supported value for location is `global`.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/apikeys.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 apikeys = google.apikeys('v2');
*
* 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 apikeys.projects.locations.keys.delete({
* // Optional. The etag known to the client for the expected state of the key. This is to be used for optimistic concurrency.
* etag: 'placeholder-value',
* // Required. The resource name of the API key to be deleted.
* name: 'projects/my-project/locations/my-location/keys/my-key',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "done": false,
* // "error": {},
* // "metadata": {},
* // "name": "my_name",
* // "response": {}
* // }
* }
*
* 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.
*/
delete(
params: Params$Resource$Projects$Locations$Keys$Delete,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
delete(
params?: Params$Resource$Projects$Locations$Keys$Delete,
options?: MethodOptions
): GaxiosPromise<Schema$Operation>;
delete(
params: Params$Resource$Projects$Locations$Keys$Delete,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
delete(
params: Params$Resource$Projects$Locations$Keys$Delete,
options: MethodOptions | BodyResponseCallback<Schema$Operation>,
callback: BodyResponseCallback<Schema$Operation>
): void;
delete(
params: Params$Resource$Projects$Locations$Keys$Delete,
callback: BodyResponseCallback<Schema$Operation>
): void;
delete(callback: BodyResponseCallback<Schema$Operation>): void;
delete(
paramsOrCallback?:
| Params$Resource$Projects$Locations$Keys$Delete
| BodyResponseCallback<Schema$Operation>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$Operation>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$Operation>
| BodyResponseCallback<Readable>
): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Projects$Locations$Keys$Delete;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Projects$Locations$Keys$Delete;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://apikeys.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'DELETE',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$Operation>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$Operation>(parameters);
}
}
/**
* Gets the metadata for an API key. The key string of the API key isn't included in the response. NOTE: Key is a global resource; hence the only supported value for location is `global`.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/apikeys.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 apikeys = google.apikeys('v2');
*
* 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',
* 'https://www.googleapis.com/auth/cloud-platform.read-only',
* ],
* });
*
* // 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 apikeys.projects.locations.keys.get({
* // Required. The resource name of the API key to get.
* name: 'projects/my-project/locations/my-location/keys/my-key',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "annotations": {},
* // "createTime": "my_createTime",
* // "deleteTime": "my_deleteTime",
* // "displayName": "my_displayName",
* // "etag": "my_etag",
* // "keyString": "my_keyString",
* // "name": "my_name",
* // "restrictions": {},
* // "uid": "my_uid",
* // "updateTime": "my_updateTime"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
get(
params: Params$Resource$Projects$Locations$Keys$Get,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
get(
params?: Params$Resource$Projects$Locations$Keys$Get,
options?: MethodOptions
): GaxiosPromise<Schema$V2Key>;
get(
params: Params$Resource$Projects$Locations$Keys$Get,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
get(
params: Params$Resource$Projects$Locations$Keys$Get,
options: MethodOptions | BodyResponseCallback<Schema$V2Key>,
callback: BodyResponseCallback<Schema$V2Key>
): void;
get(
params: Params$Resource$Projects$Locations$Keys$Get,
callback: BodyResponseCallback<Schema$V2Key>
): void;
get(callback: BodyResponseCallback<Schema$V2Key>): void;
get(
paramsOrCallback?:
| Params$Resource$Projects$Locations$Keys$Get
| BodyResponseCallback<Schema$V2Key>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$V2Key>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$V2Key>
| BodyResponseCallback<Readable>
): void | GaxiosPromise<Schema$V2Key> | GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Projects$Locations$Keys$Get;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Projects$Locations$Keys$Get;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://apikeys.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$V2Key>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$V2Key>(parameters);
}
}
/**
* Get the key string for an API key. NOTE: Key is a global resource; hence the only supported value for location is `global`.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/apikeys.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 apikeys = google.apikeys('v2');
*
* 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',
* 'https://www.googleapis.com/auth/cloud-platform.read-only',
* ],
* });
*
* // 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 apikeys.projects.locations.keys.getKeyString({
* // Required. The resource name of the API key to be retrieved.
* name: 'projects/my-project/locations/my-location/keys/my-key',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "keyString": "my_keyString"
* // }
* }
*
* 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.
*/
getKeyString(
params: Params$Resource$Projects$Locations$Keys$Getkeystring,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
getKeyString(
params?: Params$Resource$Projects$Locations$Keys$Getkeystring,
options?: MethodOptions
): GaxiosPromise<Schema$V2GetKeyStringResponse>;
getKeyString(
params: Params$Resource$Projects$Locations$Keys$Getkeystring,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
getKeyString(
params: Params$Resource$Projects$Locations$Keys$Getkeystring,
options:
| MethodOptions
| BodyResponseCallback<Schema$V2GetKeyStringResponse>,
callback: BodyResponseCallback<Schema$V2GetKeyStringResponse>
): void;
getKeyString(
params: Params$Resource$Projects$Locations$Keys$Getkeystring,
callback: BodyResponseCallback<Schema$V2GetKeyStringResponse>
): void;
getKeyString(
callback: BodyResponseCallback<Schema$V2GetKeyStringResponse>
): void;
getKeyString(
paramsOrCallback?:
| Params$Resource$Projects$Locations$Keys$Getkeystring
| BodyResponseCallback<Schema$V2GetKeyStringResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$V2GetKeyStringResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$V2GetKeyStringResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$V2GetKeyStringResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Projects$Locations$Keys$Getkeystring;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Projects$Locations$Keys$Getkeystring;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://apikeys.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v2/{+name}/keyString').replace(
/([^:]\/)\/+/g,
'$1'
),
method: 'GET',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$V2GetKeyStringResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$V2GetKeyStringResponse>(parameters);
}
}
/**
* Lists the API keys owned by a project. The key string of the API key isn't included in the response. NOTE: Key is a global resource; hence the only supported value for location is `global`.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/apikeys.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 apikeys = google.apikeys('v2');
*
* 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',
* 'https://www.googleapis.com/auth/cloud-platform.read-only',
* ],
* });
*
* // 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 apikeys.projects.locations.keys.list({
* // Optional. Specifies the maximum number of results to be returned at a time.
* pageSize: 'placeholder-value',
* // Optional. Requests a specific page of results.
* pageToken: 'placeholder-value',
* // Required. Lists all API keys associated with this project.
* parent: 'projects/my-project/locations/my-location',
* // Optional. Indicate that keys deleted in the past 30 days should also be returned.
* showDeleted: 'placeholder-value',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "keys": [],
* // "nextPageToken": "my_nextPageToken"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
list(
params: Params$Resource$Projects$Locations$Keys$List,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
list(
params?: Params$Resource$Projects$Locations$Keys$List,
options?: MethodOptions
): GaxiosPromise<Schema$V2ListKeysResponse>;
list(
params: Params$Resource$Projects$Locations$Keys$List,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
list(
params: Params$Resource$Projects$Locations$Keys$List,
options: MethodOptions | BodyResponseCallback<Schema$V2ListKeysResponse>,
callback: BodyResponseCallback<Schema$V2ListKeysResponse>
): void;
list(
params: Params$Resource$Projects$Locations$Keys$List,
callback: BodyResponseCallback<Schema$V2ListKeysResponse>
): void;
list(callback: BodyResponseCallback<Schema$V2ListKeysResponse>): void;
list(
paramsOrCallback?:
| Params$Resource$Projects$Locations$Keys$List
| BodyResponseCallback<Schema$V2ListKeysResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$V2ListKeysResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$V2ListKeysResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$V2ListKeysResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Projects$Locations$Keys$List;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Projects$Locations$Keys$List;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://apikeys.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v2/{+parent}/keys').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: ['parent'],
pathParams: ['parent'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$V2ListKeysResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$V2ListKeysResponse>(parameters);
}
}
/**
* Patches the modifiable fields of an API key. The key string of the API key isn't included in the response. NOTE: Key is a global resource; hence the only supported value for location is `global`.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/apikeys.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 apikeys = google.apikeys('v2');
*
* 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 apikeys.projects.locations.keys.patch({
* // Output only. The resource name of the key. The `name` has the form: `projects//locations/global/keys/`. For example: `projects/123456867718/locations/global/keys/b7ff1f9f-8275-410a-94dd-3855ee9b5dd2` NOTE: Key is a global resource; hence the only supported value for location is `global`.
* name: 'projects/my-project/locations/my-location/keys/my-key',
* // The field mask specifies which fields to be updated as part of this request. All other fields are ignored. Mutable fields are: `display_name`,`restrictions` and `annotations`. If an update mask is not provided, the service treats it as an implied mask equivalent to all allowed fields that are set on the wire. If the field mask has a special value "*", the service treats it equivalent to replace all allowed mutable fields.
* updateMask: 'placeholder-value',
*
* // Request body metadata
* requestBody: {
* // request body parameters
* // {
* // "annotations": {},
* // "createTime": "my_createTime",
* // "deleteTime": "my_deleteTime",
* // "displayName": "my_displayName",
* // "etag": "my_etag",
* // "keyString": "my_keyString",
* // "name": "my_name",
* // "restrictions": {},
* // "uid": "my_uid",
* // "updateTime": "my_updateTime"
* // }
* },
* });
* console.log(res.data);
*
* // Example response
* // {
* // "done": false,
* // "error": {},
* // "metadata": {},
* // "name": "my_name",
* // "response": {}
* // }
* }
*
* 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.
*/
patch(
params: Params$Resource$Projects$Locations$Keys$Patch,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
patch(
params?: Params$Resource$Projects$Locations$Keys$Patch,
options?: MethodOptions
): GaxiosPromise<Schema$Operation>;
patch(
params: Params$Resource$Projects$Locations$Keys$Patch,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
patch(
params: Params$Resource$Projects$Locations$Keys$Patch,
options: MethodOptions | BodyResponseCallback<Schema$Operation>,
callback: BodyResponseCallback<Schema$Operation>
): void;
patch(
params: Params$Resource$Projects$Locations$Keys$Patch,
callback: BodyResponseCallback<Schema$Operation>
): void;
patch(callback: BodyResponseCallback<Schema$Operation>): void;
patch(
paramsOrCallback?:
| Params$Resource$Projects$Locations$Keys$Patch
| BodyResponseCallback<Schema$Operation>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$Operation>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$Operation>
| BodyResponseCallback<Readable>
): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Projects$Locations$Keys$Patch;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Projects$Locations$Keys$Patch;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://apikeys.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'PATCH',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$Operation>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$Operation>(parameters);
}
}
/**
* Undeletes an API key which was deleted within 30 days. NOTE: Key is a global resource; hence the only supported value for location is `global`.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/apikeys.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 apikeys = google.apikeys('v2');
*
* 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 apikeys.projects.locations.keys.undelete({
* // Required. The resource name of the API key to be undeleted.
* name: 'projects/my-project/locations/my-location/keys/my-key',
*
* // Request body metadata
* requestBody: {
* // request body parameters
* // {}
* },
* });
* console.log(res.data);
*
* // Example response
* // {
* // "done": false,
* // "error": {},
* // "metadata": {},
* // "name": "my_name",
* // "response": {}
* // }
* }
*
* 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.
*/
undelete(
params: Params$Resource$Projects$Locations$Keys$Undelete,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
undelete(
params?: Params$Resource$Projects$Locations$Keys$Undelete,
options?: MethodOptions
): GaxiosPromise<Schema$Operation>;
undelete(
params: Params$Resource$Projects$Locations$Keys$Undelete,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
undelete(
params: Params$Resource$Projects$Locations$Keys$Undelete,
options: MethodOptions | BodyResponseCallback<Schema$Operation>,
callback: BodyResponseCallback<Schema$Operation>
): void;
undelete(
params: Params$Resource$Projects$Locations$Keys$Undelete,
callback: BodyResponseCallback<Schema$Operation>
): void;
undelete(callback: BodyResponseCallback<Schema$Operation>): void;
undelete(
paramsOrCallback?:
| Params$Resource$Projects$Locations$Keys$Undelete
| BodyResponseCallback<Schema$Operation>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$Operation>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$Operation>
| BodyResponseCallback<Readable>
): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Projects$Locations$Keys$Undelete;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Projects$Locations$Keys$Undelete;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://apikeys.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v2/{+name}:undelete').replace(
/([^:]\/)\/+/g,
'$1'
),
method: 'POST',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$Operation>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$Operation>(parameters);
}
}
}
export interface Params$Resource$Projects$Locations$Keys$Create
extends StandardParameters {
/**
* User specified key id (optional). If specified, it will become the final component of the key resource name. The id must be unique within the project, must conform with RFC-1034, is restricted to lower-cased letters, and has a maximum length of 63 characters. In another word, the id must match the regular expression: `[a-z]([a-z0-9-]{0,61\}[a-z0-9])?`. The id must NOT be a UUID-like string.
*/
keyId?: string;
/**
* Required. The project in which the API key is created.
*/
parent?: string;
/**
* Request body metadata
*/
requestBody?: Schema$V2Key;
}
export interface Params$Resource$Projects$Locations$Keys$Delete
extends StandardParameters {
/**
* Optional. The etag known to the client for the expected state of the key. This is to be used for optimistic concurrency.
*/
etag?: string;
/**
* Required. The resource name of the API key to be deleted.
*/
name?: string;
}
export interface Params$Resource$Projects$Locations$Keys$Get
extends StandardParameters {
/**
* Required. The resource name of the API key to get.
*/
name?: string;
}
export interface Params$Resource$Projects$Locations$Keys$Getkeystring
extends StandardParameters {
/**
* Required. The resource name of the API key to be retrieved.
*/
name?: string;
}
export interface Params$Resource$Projects$Locations$Keys$List
extends StandardParameters {
/**
* Optional. Specifies the maximum number of results to be returned at a time.
*/
pageSize?: number;
/**
* Optional. Requests a specific page of results.
*/
pageToken?: string;
/**
* Required. Lists all API keys associated with this project.
*/
parent?: string;
/**
* Optional. Indicate that keys deleted in the past 30 days should also be returned.
*/
showDeleted?: boolean;
}
export interface Params$Resource$Projects$Locations$Keys$Patch
extends StandardParameters {
/**
* Output only. The resource name of the key. The `name` has the form: `projects//locations/global/keys/`. For example: `projects/123456867718/locations/global/keys/b7ff1f9f-8275-410a-94dd-3855ee9b5dd2` NOTE: Key is a global resource; hence the only supported value for location is `global`.
*/
name?: string;
/**
* The field mask specifies which fields to be updated as part of this request. All other fields are ignored. Mutable fields are: `display_name`,`restrictions` and `annotations`. If an update mask is not provided, the service treats it as an implied mask equivalent to all allowed fields that are set on the wire. If the field mask has a special value "*", the service treats it equivalent to replace all allowed mutable fields.
*/
updateMask?: string;
/**
* Request body metadata
*/
requestBody?: Schema$V2Key;
}
export interface Params$Resource$Projects$Locations$Keys$Undelete
extends StandardParameters {
/**
* Required. The resource name of the API key to be undeleted.
*/
name?: string;
/**
* Request body metadata
*/
requestBody?: Schema$V2UndeleteKeyRequest;
}
} | the_stack |
import {directions, Direction, SlotDirection, ClaimType, CheckType, Fate} from '../manifest-ast-types/enums.js';
export {directions, Direction, SlotDirection, ClaimType, CheckType, Fate};
/**
* Complete set of tokens used by `manifest-parser.pegjs`. To use this you
* need to follow some simple guidelines:
*
* - Most interfaces should extend `BaseNode`
* - When returning data add `as Token.NewTypeName` to validate your return types.
*
* You may need to check the generated output in runtime/ts/manifest-parser.ts to validate.
*/
// duplicate of definition from pegjs code to avoid circular dependencies
export interface SourcePosition {
offset: number;
line: number;
column: number;
}
// duplicate of definition from pegjs code to avoid circular dependencies
export interface SourceLocation {
filename?: string;
start: SourcePosition;
end: SourcePosition;
text?: string; // Optionally keeps a copy of the raw/unparsed text.
}
/**
* A base token interface for the `kind` and `location` entries. This creates
* a TypeScript Discriminated Union for most tokens.
*/
export class BaseNode {
kind: string;
location: SourceLocation;
}
// PARTICLE TYPES
export interface BigCollectionType extends BaseNode {
kind: 'big-collection-type';
type: ParticleHandleConnectionType;
}
export interface CollectionType extends BaseNode {
kind: 'collection-type';
type: ParticleHandleConnectionType;
}
export interface SingletonType extends BaseNode {
kind: 'singleton-type';
type: ParticleHandleConnectionType;
}
export function isCollectionType(node: BaseNode): node is CollectionType {
return node.kind === 'collection-type';
}
export interface ReferenceType extends BaseNode {
kind: 'reference-type';
type: ParticleHandleConnectionType;
}
export interface MuxType extends BaseNode {
kind: 'mux-type';
type: ParticleHandleConnectionType;
}
export interface TupleType extends BaseNode {
kind: 'tuple-type';
types: ParticleHandleConnectionType[];
}
export interface TypeVariable extends BaseNode {
kind: 'variable-type';
name: string;
constraint: ParticleHandleConnection;
}
export function isTypeVariable(node: BaseNode): node is TypeVariable {
return node.kind === 'variable-type';
}
export interface SlotType extends BaseNode {
kind: 'slot-type';
fields: SlotField[];
}
export function isSlotType(node: BaseNode): node is SlotType {
return node.kind === 'slot-type';
}
export function slandleType(arg: ParticleHandleConnection): SlotType | undefined {
if (isSlotType(arg.type)) {
return arg.type;
}
if (isCollectionType(arg.type) && isSlotType(arg.type.type)) {
return arg.type.type;
}
return undefined;
}
// END PARTICLE TYPES
export interface ParticleHandleDescription extends BaseNode {
kind: 'handle-description';
name: string;
pattern: string;
}
export interface Description extends BaseNode {
kind: 'description';
name: 'pattern';
description: ParticleHandleDescription[];
patterns: (string | ParticleHandleDescription)[];
}
export interface HandleRef extends BaseNode {
kind: 'handle-ref';
id?: string;
name?: string;
tags: TagList;
}
export interface Import extends BaseNode {
kind: 'import';
path: string;
// populated by the manifest-primitive-parser, not by the peg-parser
items?: All[];
}
export interface ManifestStorage extends BaseNode {
kind: 'store';
name: string;
type: ManifestStorageType;
id: string|null;
originalId: string|null;
version: string|null;
tags: TagList;
source: string;
origin: 'file' | 'resource' | 'storage' | 'inline';
description: string|null;
claims: ManifestStorageClaim[];
storageKey: string|null;
entities: ManifestStorageInlineEntity[]|null;
annotationRefs?: AnnotationRefNode[];
}
export type ManifestStorageType = SchemaInline | CollectionType | BigCollectionType | TypeName;
export interface ManifestStorageClaim extends BaseNode {
kind: 'manifest-storage-claim';
fieldPath: string[];
tags: string[];
}
export interface ManifestStorageSource extends BaseNode {
kind: 'manifest-storage-source';
origin: string;
source: string;
}
export interface ManifestStorageFileSource extends ManifestStorageSource {
origin: 'file';
}
export interface ManifestStorageResourceSource extends ManifestStorageSource {
origin: 'resource';
storageKey?: string;
}
export interface ManifestStorageStorageSource extends ManifestStorageSource {
origin: 'storage';
}
export interface ManifestStorageInlineSource extends ManifestStorageSource {
origin: 'inline';
entities: ManifestStorageInlineEntity[];
}
export type ManifestStorageInlineData =
string | number | boolean | Uint8Array | {id: string, entityStorageKey: string};
export interface ManifestStorageInlineEntity extends BaseNode {
kind: 'entity-inline';
fields: {[key: string]:
{kind: 'entity-value', value: ManifestStorageInlineData} |
{kind: 'entity-collection', value: ManifestStorageInlineData[]} |
{kind: 'entity-tuple', value: ManifestStorageInlineData[]}
};
}
export interface Meta extends BaseNode {
kind: 'meta';
items: (MetaName|MetaStorageKey)[];
}
export interface MetaName extends BaseNode {
kind: 'name';
key: string;
value: string;
}
export interface MetaStorageKey extends BaseNode {
key: 'storageKey';
value: string;
kind: 'storage-key';
}
export interface MetaNamespace extends BaseNode {
key: 'namespace';
value: string;
kind: 'namespace';
}
export type MetaItem = MetaStorageKey | MetaName;
export interface Particle extends BaseNode {
kind: 'particle';
name: string;
implFile: string;
implBlobUrl?: string;
verbs: VerbList;
args?: ParticleHandleConnection[];
annotations?: {}[];
annotationRefs?: AnnotationRefNode[];
manifestNamespace?: string;
modality: string[];
slotConnections: ParticleSlotConnection[];
description?: Description;
hasDeprecatedParticleArgument?: boolean;
trustChecks?: CheckStatement[];
trustClaims?: ClaimStatement[];
}
/** A trust claim made by a particle about one of its handles. */
export interface ClaimStatement extends BaseNode {
kind: 'claim';
handle: string;
fieldPath: string[];
expression: ClaimExpression;
}
export type ClaimExpression = Claim[];
export type Claim = ClaimIsTag | ClaimDerivesFrom;
/** A claim made by a particle, saying that one of its outputs has a particular trust tag (e.g. "claim output is foo"). */
export interface ClaimIsTag extends BaseNode {
kind: 'claim-is-tag';
claimType: ClaimType.IsTag;
isNot: boolean;
tag: string;
}
/**
* A claim made by a particle, saying that one of its outputs derives from one/some of its inputs (e.g. "claim output derives from input1 and
* input2").
*/
export interface ClaimDerivesFrom extends BaseNode {
kind: 'claim-derives-from';
claimType: ClaimType.DerivesFrom;
parentHandle: string;
fieldPath: string[];
}
export interface CheckStatement extends BaseNode {
kind: 'check';
target: CheckTarget;
expression: CheckExpression;
}
export interface CheckTarget extends BaseNode {
kind: 'check-target';
targetType: 'handle' | 'slot';
name: string;
fieldPath: string[];
}
export interface CheckBooleanExpression extends BaseNode {
kind: 'check-boolean-expression';
operator: 'and' | 'or';
children: CheckExpression[];
}
export type CheckExpression = CheckBooleanExpression | CheckCondition;
export type CheckCondition = CheckHasTag | CheckIsFromHandle | CheckIsFromOutput | CheckIsFromStore | CheckImplication;
export interface CheckHasTag extends BaseNode {
kind: 'check-has-tag';
checkType: CheckType.HasTag;
isNot: boolean;
tag: string;
}
export interface CheckIsFromHandle extends BaseNode {
kind: 'check-is-from-handle';
checkType: CheckType.IsFromHandle;
isNot: boolean;
parentHandle: string;
}
export interface CheckIsFromOutput extends BaseNode {
kind: 'check-is-from-output';
checkType: CheckType.IsFromOutput;
isNot: boolean;
output: string;
}
export interface CheckIsFromStore extends BaseNode {
kind: 'check-is-from-store';
checkType: CheckType.IsFromStore;
isNot: boolean;
storeRef: StoreReference;
}
export interface CheckImplication extends BaseNode {
kind: 'check-implication';
checkType: CheckType.Implication;
antecedent: CheckCondition;
consequent: CheckCondition;
}
export interface StoreReference extends BaseNode {
kind: 'store-reference';
type: 'name' | 'id';
store: string;
}
export interface ParticleModality extends BaseNode {
kind: 'particle-modality';
modality: string;
}
export interface ParticleHandleConnection extends BaseNode {
kind: 'particle-argument';
direction: Direction;
relaxed: boolean;
type: ParticleHandleConnectionType;
isOptional: boolean;
dependentConnections: ParticleHandleConnection[];
name: string;
tags: TagList;
annotations: AnnotationRefNode[];
expression?: PaxelExpressionNode;
}
export type ParticleItem = ParticleModality | ParticleSlotConnection | Description | ParticleHandleConnection;
export interface ParticleInterface extends BaseNode {
kind: 'interface';
verb: string;
args: ParticleHandleConnection[];
}
export interface ParticleSlotConnection extends BaseNode {
kind: 'particle-slot';
name: string;
tags: TagList;
isRequired: boolean;
isSet: boolean;
formFactor?: string;
provideSlotConnections: ParticleProvidedSlot[];
}
export interface ParticleProvidedSlot extends BaseNode {
kind: 'provided-slot';
name: string;
tags: TagList;
isRequired: boolean;
isSet: boolean;
formFactor?: string;
handles?: string[];
}
export interface ParticleRef extends BaseNode {
kind: 'particle-ref';
name?: string;
verbs: VerbList;
tags: TagList;
}
export interface AnnotationNode extends BaseNode {
kind: 'annotation-node';
name: string;
params: AnnotationParam[];
targets: AnnotationTargetValue[];
retention: AnnotationRetentionValue;
allowMultiple: boolean;
doc: string;
}
export interface AnnotationParam extends BaseNode {
kind: 'annotation-param';
name: string;
type: SchemaPrimitiveTypeValue;
}
export type AnnotationTargetValue =
'Recipe' |
'Particle' |
'Store' |
'Handle' |
'HandleConnection' |
'Schema' |
'SchemaField' |
'PolicyField' |
'PolicyTarget' |
'Policy';
export interface AnnotationTargets extends BaseNode {
kind: 'annotation-targets';
targets: AnnotationTargetValue[];
}
export type AnnotationRetentionValue = 'Source' | 'Runtime';
export interface AnnotationRetention extends BaseNode {
kind: 'annotation-retention';
retention: AnnotationRetentionValue;
}
export interface AnnotationDoc extends BaseNode {
kind: 'annotation-doc';
doc: string;
}
export interface AnnotationMultiple extends BaseNode {
kind: 'annotation-multiple';
allowMultiple: boolean;
}
export interface AnnotationRefNode extends BaseNode {
kind: 'annotation-ref';
name: string;
params: AnnotationRefParam[];
}
export type AnnotationRefParam = AnnotationRefNamedParam | AnnotationRefSimpleParam;
export type AnnotationSimpleParamValue = ManifestStorageInlineData | NumberedUnits;
export interface AnnotationRefNamedParam extends BaseNode {
kind: 'annotation-named-param';
name: string;
value: ManifestStorageInlineData;
}
export interface AnnotationRefSimpleParam extends BaseNode {
kind: 'annotation-simple-param';
value: AnnotationSimpleParamValue;
}
export interface RecipeNode extends BaseNode {
kind: 'recipe';
name: string;
verbs: VerbList;
items: RecipeItem[];
annotationRefs?: AnnotationRefNode[];
}
export interface RecipeParticle extends BaseNode {
kind: 'recipe-particle';
name: string;
ref: ParticleRef;
connections: RecipeParticleConnection[];
slotConnections: RecipeParticleSlotConnection[];
}
export interface RequireHandleSection extends BaseNode {
kind: 'require-handle';
name: string;
ref: HandleRef;
}
export interface RecipeRequire extends BaseNode {
kind: 'require';
items: RecipeItem[];
}
export type RecipeItem = RecipeParticle | RecipeHandle | RecipeSyntheticHandle | RequireHandleSection | RecipeRequire | RecipeSlot | RecipeSearch | RecipeConnection | Description;
export const RELAXATION_KEYWORD = 'someof';
export interface RecipeParticleConnection extends BaseNode {
kind: 'handle-connection';
param: string;
direction: Direction;
relaxed: boolean;
target: ParticleConnectionTargetComponents;
dependentConnections: RecipeParticleConnection[];
}
export type RecipeParticleItem = RecipeParticleSlotConnection | RecipeParticleConnection;
export interface ParticleConnectionTargetComponents extends BaseNode {
kind: 'handle-connection-components';
name: string|null;
particle: string|null;
tags: TagList;
}
export type RecipeHandleFate = string;
export interface RecipeHandle extends BaseNode {
kind: 'handle';
name: string|null;
ref: HandleRef;
fate: Fate;
annotations: AnnotationRefNode[];
}
export interface RecipeSyntheticHandle extends BaseNode {
kind: 'synthetic-handle';
name: string|null;
associations: string[];
}
export interface AppliedAdapter extends BaseNode {
kind: 'adapter-apply-node';
name: string;
params: string[];
}
export interface RecipeParticleSlotConnection extends BaseNode {
kind: 'slot-connection';
param: string;
target: ParticleConnectionTargetComponents;
dependentSlotConnections: RecipeParticleSlotConnection[];
direction: SlotDirection;
}
export interface RecipeSlotConnectionRef extends BaseNode {
kind: 'slot-connection-ref';
param: string;
tags: TagList;
}
export interface RecipeConnection extends BaseNode {
kind: 'connection';
direction: Direction;
relaxed: boolean;
from: ConnectionTarget;
to: ConnectionTarget;
}
export interface RecipeSearch extends BaseNode {
kind: 'search';
phrase: string;
tokens: string[];
}
export interface RecipeSlot extends BaseNode {
kind: 'slot';
ref: HandleRef;
name: string|null;
}
export type ConnectionTarget = VerbConnectionTarget | TagConnectionTarget | NameConnectionTarget | ParticleConnectionTarget;
export interface VerbConnectionTarget extends BaseNode {
kind: 'connection-target';
targetType: 'verb';
verbs: VerbList;
param: string;
tags: TagList;
}
export interface TagConnectionTarget extends BaseNode {
kind: 'connection-target';
targetType: 'tag';
tags: TagList;
}
export interface NameConnectionTarget extends BaseNode {
kind: 'connection-target';
name: string;
targetType: 'localName';
param: string;
tags: TagList;
}
export interface ParticleConnectionTarget extends BaseNode {
kind: 'connection-target';
particle: string;
targetType: 'particle';
param: string;
tags: TagList;
}
export interface ConnectionTargetHandleComponents extends BaseNode {
kind: 'connection-target-handle-components';
param: string;
tags: TagList;
}
export interface Resource extends BaseNode {
kind: 'resource';
name: string;
data: string;
}
export interface Schema extends BaseNode {
kind: 'schema';
items: SchemaItem[];
alias?: string;
}
export interface SchemaSection extends BaseNode {
kind: 'schema-section';
sectionType: string;
fields: SchemaField[];
}
export interface SchemaField extends BaseNode {
kind: 'schema-field';
type: SchemaType;
name: string;
}
export enum SchemaFieldKind {
Primitive = 'schema-primitive',
KotlinPrimitive = 'kotlin-primitive',
Collection = 'schema-collection',
Reference = 'schema-reference',
OrderedList = 'schema-ordered-list',
Union = 'schema-union',
Tuple = 'schema-tuple',
Nested = 'schema-nested',
Inline = 'schema-inline',
InlineField = 'schema-inline-field',
// TypeName is considered a 'partial' of Inline (the type checker will convert to Inline when the
// fields are found during annotation of the AST with type info).
TypeName = 'type-name',
Nullable = 'schema-nullable',
}
export class ExtendedTypeInfo extends BaseNode {
refinement: RefinementNode;
annotations: AnnotationRefNode[];
}
export type SchemaType = (SchemaReferenceType|SchemaCollectionType|
SchemaPrimitiveType|KotlinPrimitiveType|SchemaUnionType|SchemaTupleType|TypeName|SchemaInline|SchemaOrderedListType|NestedSchema|KotlinPrimitiveType|SchemaNullableType) & ExtendedTypeInfo;
export interface SchemaPrimitiveType extends BaseNode {
kind: SchemaFieldKind.Primitive;
type: SchemaPrimitiveTypeValue;
}
export interface KotlinPrimitiveType extends BaseNode {
kind: SchemaFieldKind.KotlinPrimitive;
type: KotlinPrimitiveTypeValue;
}
export interface SchemaCollectionType extends BaseNode {
kind: SchemaFieldKind.Collection;
schema: SchemaType;
}
export interface SchemaOrderedListType extends BaseNode {
kind: SchemaFieldKind.OrderedList;
schema: SchemaType;
}
export interface SchemaNullableType extends BaseNode {
kind: SchemaFieldKind.Nullable;
schema: SchemaType;
}
export interface SchemaReferenceType extends BaseNode {
kind: SchemaFieldKind.Reference;
schema: SchemaType;
}
export interface SchemaUnionType extends BaseNode {
kind: SchemaFieldKind.Union;
types: SchemaType[];
}
export interface SchemaTupleType extends BaseNode {
kind: SchemaFieldKind.Tuple;
types: SchemaType[];
}
export interface RefinementNode extends BaseNode {
kind: 'refinement';
expression: RefinementExpressionNode;
}
export type RefinementExpressionNode = BinaryExpressionNode | UnaryExpressionNode | FieldNode |
QueryNode | BuiltInNode | NumberNode | DiscreteNode | BooleanNode | TextNode | NullNode;
export enum Op {
AND = 'and',
OR = 'or',
LT = '<',
GT = '>',
LTE = '<=',
GTE = '>=',
ADD = '+',
SUB = '-',
MUL = '*',
DIV = '/',
NOT = 'not',
NEG = 'neg',
EQ = '==',
NEQ = '!=',
}
export interface ExpressionNode extends BaseNode {
operator: Op;
}
export interface BinaryExpressionNode extends ExpressionNode {
kind: 'binary-expression-node';
leftExpr: RefinementExpressionNode;
rightExpr: RefinementExpressionNode;
}
export interface UnaryExpressionNode extends ExpressionNode {
kind: 'unary-expression-node';
expr: RefinementExpressionNode;
}
export interface FieldNode extends BaseNode {
kind: 'field-name-node';
value: string;
}
export interface QueryNode extends BaseNode {
kind: 'query-argument-node';
value: string;
}
export enum BuiltInFuncs {
NOW = 'now',
CREATION_TIME = 'creationTime',
EXPIRATION_TIME = 'expirationTime',
}
export interface BuiltInNode extends BaseNode {
kind: 'built-in-node';
value: BuiltInFuncs;
}
export const schemaPrimitiveTypes = [
'Text',
'URL',
'Number',
'BigInt',
'Boolean',
'Bytes',
'Object',
'Instant',
'Duration',
] as const;
// Creates a union of all values in the associated list.
export type SchemaPrimitiveTypeValue = typeof schemaPrimitiveTypes[number];
export const kotlinPrimitiveTypes = [
'Byte',
'Short',
'Int',
'Long',
'Char',
'Float',
'Double',
] as const;
// Creates a union of all values in the associated list.
export type KotlinPrimitiveTypeValue = typeof kotlinPrimitiveTypes[number];
export const discreteTypes = [
'BigInt',
'Long',
'Int',
'Instant',
'Duration',
] as const;
// Creates a union of all values in the associated list.
export type DiscreteType = typeof discreteTypes[number];
export const continuousTypes = [
'Number',
'Float',
'Double',
'Text',
] as const;
export const primitiveTypes = [
'Boolean',
// TODO: Add full support for Boolean as a Discrete value (it currently has it's own primitives).
'~query_arg_type',
...continuousTypes,
...discreteTypes
];
// Creates a union of all values in the associated list.
export type Primitive = typeof primitiveTypes[number];
export const timeUnits = [
'days',
'hours',
'minutes',
'seconds',
'milliseconds'
];
// Creates a union of all values in the associated list.
export type SupportedUnit = typeof timeUnits[number];
export interface NumberNode extends BaseNode {
kind: 'number-node';
value: number;
units: SupportedUnit[];
}
export interface DiscreteNode extends BaseNode {
kind: 'discrete-node';
value: bigint;
type: DiscreteType;
units: SupportedUnit[];
}
export interface BooleanNode extends BaseNode {
kind: 'boolean-node';
value: boolean;
}
export interface TextNode extends BaseNode {
kind: 'text-node';
value: string;
}
export interface NullNode extends BaseNode {
kind: 'null-node';
}
export interface SchemaInline extends BaseNode {
kind: 'schema-inline';
names: string[];
fields: SchemaInlineField[];
}
export interface NestedSchema extends BaseNode {
kind: 'schema-nested';
schema: SchemaInline;
}
export interface SchemaInlineField extends BaseNode {
kind: 'schema-inline-field';
name: string;
type: SchemaType;
}
export interface SchemaSpec extends BaseNode {
kind: 'schema';
names: string[];
parents: string[];
}
export type SchemaItem = SchemaField | Description;
export interface SchemaAlias extends BaseNode {
kind: 'schema';
items: SchemaItem[];
alias: string;
}
export enum PaxelFunctionName {
Now = 'now',
Min = 'min',
Max = 'max',
Average = 'average',
Sum = 'sum',
Count = 'count',
Union = 'union',
First = 'first'
}
interface PaxelFunction {
name: PaxelFunctionName;
arity: number;
returnType: SchemaType;
}
// represents function(args) => number paxel functions
function makePaxelNumericFunction(name: PaxelFunctionName, arity: number, type: SchemaPrimitiveTypeValue) {
return makePaxelFunction(name, arity, {
kind: SchemaFieldKind.Primitive, type, location: INTERNAL_PAXEL_LOCATION, refinement: null, annotations: [],
});
}
// Used for builtin function nodes
const INTERNAL_PAXEL_LOCATION: SourceLocation = {
filename: 'internal_paxel_function_table',
start: {offset: 0, column: 0, line: 0},
end: {offset: 0, column: 0, line: 0}
};
// Represents function(sequence<type>, ...) => sequence<type> paxel functions
function makePaxelCollectionTypeFunction(name: PaxelFunctionName, arity: number) {
return makePaxelFunction(name, arity, {
kind: SchemaFieldKind.Collection,
schema: {
kind: 'type-name',
name: '*', // * denotes a passthrough type, the input type is the same as the output type
location: INTERNAL_PAXEL_LOCATION,
refinement: null,
annotations: [],
},
location: INTERNAL_PAXEL_LOCATION,
refinement: null,
annotations: [],
});
}
// arity = -1 means varargs
function makePaxelFunction(name: PaxelFunctionName, arity: number, returnType: SchemaType) {
return {
name,
arity,
returnType
};
}
export const PAXEL_FUNCTIONS: PaxelFunction[] = [
makePaxelNumericFunction(PaxelFunctionName.Now, 0, 'Number'),
makePaxelNumericFunction(PaxelFunctionName.Min, 1, 'Number'),
makePaxelNumericFunction(PaxelFunctionName.Max, 1, 'Number'),
makePaxelNumericFunction(PaxelFunctionName.Average, 1, 'Number'),
makePaxelNumericFunction(PaxelFunctionName.Count, 1, 'Number'),
makePaxelNumericFunction(PaxelFunctionName.Sum, 1, 'Number'),
makePaxelCollectionTypeFunction(PaxelFunctionName.Union, -1),
makePaxelCollectionTypeFunction(PaxelFunctionName.First, 1)
];
export type PaxelExpressionNode = (FromExpressionNode | WhereExpressionNode | LetExpressionNode |
SelectExpressionNode | NewExpressionNode | FunctionExpressionNode | RefinementExpressionNode) & {
unparsedPaxelExpression?: string;
};
export interface ExpressionEntity extends BaseNode {
kind: 'expression-entity';
names: string[];
fields: ExpressionEntityField[];
}
export interface QualifiedExpression {
qualifier?: PaxelExpressionNode;
}
export interface FromExpressionNode extends QualifiedExpression, BaseNode {
kind: 'paxel-from';
iterationVar: string;
source: PaxelExpressionNode;
}
export interface WhereExpressionNode extends QualifiedExpression, BaseNode {
kind: 'paxel-where';
condition: PaxelExpressionNode;
}
export interface LetExpressionNode extends QualifiedExpression, BaseNode {
kind: 'paxel-let';
varName: string;
expression: PaxelExpressionNode;
}
export interface SelectExpressionNode extends QualifiedExpression, BaseNode {
kind: 'paxel-select';
expression: PaxelExpressionNode;
}
export interface NewExpressionNode extends BaseNode {
kind: 'paxel-new';
schemaNames: string[];
fields: ExpressionEntityField[];
}
export interface FieldExpressionNode extends BaseNode {
kind: 'paxel-field';
scopeExpression?: PaxelExpressionNode;
field: FieldNode;
}
export interface FunctionExpressionNode extends BaseNode {
kind: 'paxel-function';
function: string;
arguments: PaxelExpressionNode[];
}
export interface ExpressionEntityField extends BaseNode {
kind: 'expression-entity-field';
name: string;
expression: PaxelExpressionNode;
}
export interface Interface extends BaseNode {
kind: 'interface';
name: string;
slots: InterfaceSlot[];
interface?: InterfaceInterface[];
args?: InterfaceArgument[];
}
export type InterfaceItem = Interface | InterfaceArgument | InterfaceSlot;
export interface InterfaceArgument extends BaseNode {
kind: 'interface-argument';
direction: Direction;
type: ParticleHandleConnectionType;
name: string;
}
export interface InterfaceInterface extends BaseNode {
kind: 'interface';
verb: string;
args: InterfaceArgument[]; // InterfaceArgumentList?
}
export interface InterfaceSlot extends BaseNode {
kind: 'interface-slot';
name: string|null;
isRequired: boolean;
direction: SlotDirection;
isSet: boolean;
}
export interface SlotField extends BaseNode {
kind: 'slot-field';
name: string;
value: string;
}
export interface SlotFormFactor extends BaseNode {
kind: 'form-factor';
formFactor: string;
}
export type ParticleSlotConnectionItem = SlotFormFactor | ParticleProvidedSlot;
export interface TypeName extends BaseNode {
kind: 'type-name';
name: string;
}
export interface NameAndTagList extends BaseNode {
name: string;
tags: TagList;
}
export interface Annotation extends BaseNode {
kind: 'annotation';
annotationRefs: AnnotationRefNode[];
}
export interface NumberedUnits extends BaseNode {
kind: 'numbered-units';
count: number;
units: string;
}
export interface Policy extends BaseNode {
kind: 'policy';
name: string;
targets: PolicyTarget[];
configs: PolicyConfig[];
annotationRefs: AnnotationRefNode[];
}
export interface PolicyTarget extends BaseNode {
kind: 'policy-target';
schemaName: string;
fields: PolicyField[];
annotationRefs: AnnotationRefNode[];
}
export interface PolicyField extends BaseNode {
kind: 'policy-field';
name: string;
subfields: PolicyField[];
annotationRefs: AnnotationRefNode[];
}
export interface PolicyConfig extends BaseNode {
kind: 'policy-config';
name: string;
metadata: Map<string, string>;
}
// Aliases to simplify ts-pegjs returnTypes requirement in sigh.
export type Triggers = [string, string][][];
export type Indent = number;
export type LocalName = string;
export type Manifest = ManifestItem[];
export type ManifestStorageDescription = string;
export type Modality = string;
export type ReservedWord = string;
export type ResourceStart = string;
export type ResourceBody = string;
export type ResourceLine = string;
export type SameIndent = boolean;
export type SameOrMoreIndent = string;
export type SchemaExtends = string[];
export type SpaceTagList = Tag[];
export type Tag = string;
export type TagList = Tag[];
export type TopLevelAlias = string;
export type Verb = string;
export type VerbList = Verb[];
export type Version = number;
export type backquotedString = string;
export type fieldName = string;
export type id = string;
export type upperIdent = string;
export type lowerIdent = string;
export type whiteSpace = string;
export type eolWhiteSpace = string;
export type eol = string;
export function preSlandlesDirectionToDirection(direction: Direction, isOptional: boolean = false): string {
// TODO(jopra): Remove after syntax unification.
// Use switch for totality checking.
const opt: string = isOptional ? '?' : '';
switch (direction) {
case 'reads':
return `reads${opt}`;
case 'writes':
return `writes${opt}`;
case 'reads writes':
return `reads${opt} writes${opt}`;
case '`consumes':
return `\`consumes${opt}`;
case '`provides':
return `\`provides${opt}`;
case 'hosts':
return `hosts${opt}`;
case 'any':
return `any${opt}`;
default:
// Catch nulls and unsafe values from javascript.
throw new Error(`Bad pre slandles direction ${direction}`);
}
}
export type ParticleHandleConnectionType = TypeVariable|CollectionType|
BigCollectionType|ReferenceType|MuxType|SlotType|SchemaInline|TypeName;
// Note that ManifestStorage* are not here, as they do not have 'kind'
export type All = Import|Meta|MetaName|MetaStorageKey|MetaNamespace|Particle|ParticleHandleConnection|
ParticleInterface|RecipeHandle|Resource|Interface|InterfaceArgument|InterfaceInterface|
InterfaceSlot;
export type ManifestItem =
RecipeNode|Particle|Import|Schema|ManifestStorage|Interface|Meta|Resource;
export function viewAst(ast: unknown, viewLocation = false) {
// Helper function useful for viewing ast information while working on the parser and test code:
// Optionally, strips location information.
console.log(
JSON.stringify(ast, (_key, value) => {
if (!viewLocation && value != null && value['location']) {
delete value['location'];
}
return typeof value === 'bigint'
? value.toString() // Workaround for JSON not supporting bigint.
: value;
}, // return everything else unchanged
2));
}
export function viewLoc(loc: SourceLocation): string {
const filename = loc.filename ? ` in ${loc.filename}` : '';
return `line ${loc.start.line}, col ${loc.start.column}${filename}`;
} | the_stack |
import { Vec2 } from '../math/Vec2';
import { Vec3 } from '../math/Vec3';
const EPSILON = Math.pow(2, -52);
const EDGE_STACK = new Uint32Array(512);
export class Delaunator {
coords: Float64Array;
_triangles: Uint32Array;
_halfedges: Int32Array;
_hashSize: number;
_hullPrev: Uint32Array;
_hullNext: Uint32Array;
_hullTri: Uint32Array;
_hullHash: Int32Array;
_ids: Uint32Array;
_dists: Float64Array;
hull!: Uint32Array;
triangles!: Uint32Array;
halfedges!: any;
_cx: any;
_cy: any;
_hullStart!: number;
trianglesLen!: number;
static from(points: number[]) {
const n = points.length;
const coords = new Float64Array(n);
for (let i = 0; i < n; i++) {
const p = points[i];
coords[i] = p;
}
return new Delaunator(coords);
}
static fromVecs(points: Vec2[] | Vec3[]) {
var ps: number[] = [];
for (let i = 0; i < points.length; i++) {
ps.push(points[i].x, points[i].y)
}
return Delaunator.from(ps)
}
constructor(coords: Float64Array) {
const n = coords.length >> 1;
if (n > 0 && typeof coords[0] !== 'number') throw new Error('Expected coords to contain numbers.');
this.coords = coords;
// arrays that will store the triangulation graph
const maxTriangles = Math.max(2 * n - 5, 0);
this._triangles = new Uint32Array(maxTriangles * 3);
this._halfedges = new Int32Array(maxTriangles * 3);
// temporary arrays for tracking the edges of the advancing convex hull
this._hashSize = Math.ceil(Math.sqrt(n));
this._hullPrev = new Uint32Array(n); // edge to prev edge
this._hullNext = new Uint32Array(n); // edge to next edge
this._hullTri = new Uint32Array(n); // edge to adjacent triangle
this._hullHash = new Int32Array(this._hashSize).fill(-1); // angular edge hash
// temporary arrays for sorting points
this._ids = new Uint32Array(n);
this._dists = new Float64Array(n);
this.update();
}
update() {
const { coords, _hullPrev: hullPrev, _hullNext: hullNext, _hullTri: hullTri, _hullHash: hullHash } = this;
const n = coords.length >> 1;
// populate an array of point indices; calculate input data bbox
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (let i = 0; i < n; i++) {
const x = coords[2 * i];
const y = coords[2 * i + 1];
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
this._ids[i] = i;
}
const cx = (minX + maxX) / 2;
const cy = (minY + maxY) / 2;
let minDist = Infinity;
let i0 = 0, i1 = 0, i2 = 0;
// pick a seed point close to the center
for (let i = 0; i < n; i++) {
const d = dist(cx, cy, coords[2 * i], coords[2 * i + 1]);
if (d < minDist) {
i0 = i;
minDist = d;
}
}
const i0x = coords[2 * i0];
const i0y = coords[2 * i0 + 1];
minDist = Infinity;
// find the point closest to the seed
for (let i = 0; i < n; i++) {
if (i === i0) continue;
const d = dist(i0x, i0y, coords[2 * i], coords[2 * i + 1]);
if (d < minDist && d > 0) {
i1 = i;
minDist = d;
}
}
let i1x = coords[2 * i1];
let i1y = coords[2 * i1 + 1];
let minRadius = Infinity;
// find the third point which forms the smallest circumcircle with the first two
for (let i = 0; i < n; i++) {
if (i === i0 || i === i1) continue;
const r = circumradius(i0x, i0y, i1x, i1y, coords[2 * i], coords[2 * i + 1]);
if (r < minRadius) {
i2 = i;
minRadius = r;
}
}
let i2x = coords[2 * i2];
let i2y = coords[2 * i2 + 1];
if (minRadius === Infinity) {
// order collinear points by dx (or dy if all x are identical)
// and return the list as a hull
for (let i = 0; i < n; i++) {
this._dists[i] = (coords[2 * i] - coords[0]) || (coords[2 * i + 1] - coords[1]);
}
quicksort(this._ids, this._dists, 0, n - 1);
const hull = new Uint32Array(n);
let j = 0;
for (let i = 0, d0 = -Infinity; i < n; i++) {
const id = this._ids[i];
if (this._dists[id] > d0) {
hull[j++] = id;
d0 = this._dists[id];
}
}
this.hull = hull.subarray(0, j);
this.triangles = new Uint32Array(0);
this.halfedges = new Uint32Array(0);
return;
}
// swap the order of the seed points for counter-clockwise orientation
if (orient(i0x, i0y, i1x, i1y, i2x, i2y)) {
const i = i1;
const x = i1x;
const y = i1y;
i1 = i2;
i1x = i2x;
i1y = i2y;
i2 = i;
i2x = x;
i2y = y;
}
const center = circumcenter(i0x, i0y, i1x, i1y, i2x, i2y);
this._cx = center.x;
this._cy = center.y;
for (let i = 0; i < n; i++) {
this._dists[i] = dist(coords[2 * i], coords[2 * i + 1], center.x, center.y);
}
// sort the points by distance from the seed triangle circumcenter
quicksort(this._ids, this._dists, 0, n - 1);
// set up the seed triangle as the starting hull
this._hullStart = i0;
let hullSize = 3;
hullNext[i0] = hullPrev[i2] = i1;
hullNext[i1] = hullPrev[i0] = i2;
hullNext[i2] = hullPrev[i1] = i0;
hullTri[i0] = 0;
hullTri[i1] = 1;
hullTri[i2] = 2;
hullHash.fill(-1);
hullHash[this._hashKey(i0x, i0y)] = i0;
hullHash[this._hashKey(i1x, i1y)] = i1;
hullHash[this._hashKey(i2x, i2y)] = i2;
this.trianglesLen = 0;
this._addTriangle(i0, i1, i2, -1, -1, -1);
for (let k = 0, xp, yp; k < this._ids.length; k++) {
const i = this._ids[k];
const x = coords[2 * i];
const y = coords[2 * i + 1];
// skip near-duplicate points
if (k > 0)
if (xp !== undefined && yp !== undefined) {
if (Math.abs(x - xp) <= EPSILON && Math.abs(y - yp) <= EPSILON) continue;
}
else
continue;
xp = x;
yp = y;
// skip seed triangle points
if (i === i0 || i === i1 || i === i2) continue;
// find a visible edge on the convex hull using edge hash
let start = 0;
for (let j = 0, key = this._hashKey(x, y); j < this._hashSize; j++) {
start = hullHash[(key + j) % this._hashSize];
if (start !== -1 && start !== hullNext[start]) break;
}
start = hullPrev[start];
let e = start, q;
while (q = hullNext[e], !orient(x, y, coords[2 * e], coords[2 * e + 1], coords[2 * q], coords[2 * q + 1])) {
e = q;
if (e === start) {
e = -1;
break;
}
}
if (e === -1) continue; // likely a near-duplicate point; skip it
// add the first triangle from the point
let t = this._addTriangle(e, i, hullNext[e], -1, -1, hullTri[e]);
// recursively flip triangles from the point until they satisfy the Delaunay condition
hullTri[i] = this._legalize(t + 2);
hullTri[e] = t; // keep track of boundary triangles on the hull
hullSize++;
// walk forward through the hull, adding more triangles and flipping recursively
let n = hullNext[e];
while (q = hullNext[n], orient(x, y, coords[2 * n], coords[2 * n + 1], coords[2 * q], coords[2 * q + 1])) {
t = this._addTriangle(n, i, q, hullTri[i], -1, hullTri[n]);
hullTri[i] = this._legalize(t + 2);
hullNext[n] = n; // mark as removed
hullSize--;
n = q;
}
// walk backward from the other side, adding more triangles and flipping
if (e === start) {
while (q = hullPrev[e], orient(x, y, coords[2 * q], coords[2 * q + 1], coords[2 * e], coords[2 * e + 1])) {
t = this._addTriangle(q, i, e, -1, hullTri[e], hullTri[q]);
this._legalize(t + 2);
hullTri[q] = t;
hullNext[e] = e; // mark as removed
hullSize--;
e = q;
}
}
// update the hull indices
this._hullStart = hullPrev[i] = e;
hullNext[e] = hullPrev[n] = i;
hullNext[i] = n;
// save the two new edges in the hash table
hullHash[this._hashKey(x, y)] = i;
hullHash[this._hashKey(coords[2 * e], coords[2 * e + 1])] = e;
}
this.hull = new Uint32Array(hullSize);
for (let i = 0, e = this._hullStart; i < hullSize; i++) {
this.hull[i] = e;
e = hullNext[e];
}
// trim typed triangle mesh arrays
this.triangles = this._triangles.subarray(0, this.trianglesLen);
this.halfedges = this._halfedges.subarray(0, this.trianglesLen);
}
_hashKey(x: number, y: number) {
return Math.floor(pseudoAngle(x - this._cx, y - this._cy) * this._hashSize) % this._hashSize;
}
_legalize(a: number) {
const { _triangles: triangles, _halfedges: halfedges, coords } = this;
let i = 0;
let ar = 0;
// recursion eliminated with a fixed-size stack
while (true) {
const b = halfedges[a];
/* if the pair of triangles doesn't satisfy the Delaunay condition
* (p1 is inside the circumcircle of [p0, pl, pr]), flip them,
* then do the same check/flip recursively for the new pair of triangles
*
* pl pl
* /||\ / \
* al/ || \bl al/ \a
* / || \ / \
* / a||b \ flip /___ar___\
* p0\ || /p1 => p0\---bl---/p1
* \ || / \ /
* ar\ || /br b\ /br
* \||/ \ /
* pr pr
*/
const a0 = a - a % 3;
ar = a0 + (a + 2) % 3;
if (b === -1) { // convex hull edge
if (i === 0) break;
a = EDGE_STACK[--i];
continue;
}
const b0 = b - b % 3;
const al = a0 + (a + 1) % 3;
const bl = b0 + (b + 2) % 3;
const p0 = triangles[ar];
const pr = triangles[a];
const pl = triangles[al];
const p1 = triangles[bl];
const illegal = inCircle(
coords[2 * p0], coords[2 * p0 + 1],
coords[2 * pr], coords[2 * pr + 1],
coords[2 * pl], coords[2 * pl + 1],
coords[2 * p1], coords[2 * p1 + 1]);
if (illegal) {
triangles[a] = p1;
triangles[b] = p0;
const hbl = halfedges[bl];
// edge swapped on the other side of the hull (rare); fix the halfedge reference
if (hbl === -1) {
let e = this._hullStart;
do {
if (this._hullTri[e] === bl) {
this._hullTri[e] = a;
break;
}
e = this._hullPrev[e];
} while (e !== this._hullStart);
}
this._link(a, hbl);
this._link(b, halfedges[ar]);
this._link(ar, bl);
const br = b0 + (b + 1) % 3;
// don't worry about hitting the cap: it can only happen on extremely degenerate input
if (i < EDGE_STACK.length) {
EDGE_STACK[i++] = br;
}
} else {
if (i === 0) break;
a = EDGE_STACK[--i];
}
}
return ar;
}
_link(a: number, b: number) {
this._halfedges[a] = b;
if (b !== -1) this._halfedges[b] = a;
}
// add a new triangle given vertex indices and adjacent half-edge ids
_addTriangle(i0: number, i1: number, i2: number, a: number, b: number, c: number) {
const t = this.trianglesLen;
this._triangles[t] = i0;
this._triangles[t + 1] = i1;
this._triangles[t + 2] = i2;
this._link(t, a);
this._link(t + 1, b);
this._link(t + 2, c);
this.trianglesLen += 3;
return t;
}
}
// monotonically increases with real angle, but doesn't need expensive trigonometry
function pseudoAngle(dx: number, dy: number) {
const p = dx / (Math.abs(dx) + Math.abs(dy));
return (dy > 0 ? 3 - p : 1 + p) / 4; // [0..1]
}
function dist(ax: number, ay: number, bx: number, by: number) {
const dx = ax - bx;
const dy = ay - by;
return dx * dx + dy * dy;
}
// return 2d orientation sign if we're confident in it through J. Shewchuk's error bound check
function orientIfSure(px: number, py: number, rx: number, ry: number, qx: number, qy: number) {
const l = (ry - py) * (qx - px);
const r = (rx - px) * (qy - py);
return Math.abs(l - r) >= 3.3306690738754716e-16 * Math.abs(l + r) ? l - r : 0;
}
// a more robust orientation test that's stable in a given triangle (to fix robustness issues)
function orient(rx: number, ry: number, qx: number, qy: number, px: number, py: number) {
return (orientIfSure(px, py, rx, ry, qx, qy) ||
orientIfSure(rx, ry, qx, qy, px, py) ||
orientIfSure(qx, qy, px, py, rx, ry)) < 0;
}
function inCircle(ax: number, ay: number, bx: number, by: number, cx: number, cy: number, px: number, py: number) {
const dx = ax - px;
const dy = ay - py;
const ex = bx - px;
const ey = by - py;
const fx = cx - px;
const fy = cy - py;
const ap = dx * dx + dy * dy;
const bp = ex * ex + ey * ey;
const cp = fx * fx + fy * fy;
return dx * (ey * cp - bp * fy) -
dy * (ex * cp - bp * fx) +
ap * (ex * fy - ey * fx) < 0;
}
function circumradius(ax: number, ay: number, bx: number, by: number, cx: number, cy: number) {
const dx = bx - ax;
const dy = by - ay;
const ex = cx - ax;
const ey = cy - ay;
const bl = dx * dx + dy * dy;
const cl = ex * ex + ey * ey;
const d = 0.5 / (dx * ey - dy * ex);
const x = (ey * bl - dy * cl) * d;
const y = (dx * cl - ex * bl) * d;
return x * x + y * y;
}
function circumcenter(ax: number, ay: number, bx: number, by: number, cx: number, cy: number) {
const dx = bx - ax;
const dy = by - ay;
const ex = cx - ax;
const ey = cy - ay;
const bl = dx * dx + dy * dy;
const cl = ex * ex + ey * ey;
const d = 0.5 / (dx * ey - dy * ex);
const x = ax + (ey * bl - dy * cl) * d;
const y = ay + (dx * cl - ex * bl) * d;
return { x, y };
}
function quicksort(ids: any[] | Uint32Array, dists: Float64Array, left: number, right: number) {
if (right - left <= 20) {
for (let i = left + 1; i <= right; i++) {
const temp = ids[i];
const tempDist = dists[temp];
let j = i - 1;
while (j >= left && dists[ids[j]] > tempDist) ids[j + 1] = ids[j--];
ids[j + 1] = temp;
}
} else {
const median = (left + right) >> 1;
let i = left + 1;
let j = right;
swap(ids, median, i);
if (dists[ids[left]] > dists[ids[right]]) swap(ids, left, right);
if (dists[ids[i]] > dists[ids[right]]) swap(ids, i, right);
if (dists[ids[left]] > dists[ids[i]]) swap(ids, left, i);
const temp = ids[i];
const tempDist = dists[temp];
while (true) {
do i++; while (dists[ids[i]] < tempDist);
do j--; while (dists[ids[j]] > tempDist);
if (j < i) break;
swap(ids, i, j);
}
ids[left + 1] = ids[j];
ids[j] = temp;
if (right - i + 1 >= j - left) {
quicksort(ids, dists, i, right);
quicksort(ids, dists, left, j - 1);
} else {
quicksort(ids, dists, left, j - 1);
quicksort(ids, dists, i, right);
}
}
}
function swap(arr: { [x: string]: any; }, i: number, j: string | number) {
const tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
} | the_stack |
import { Property, ChildProperty, Collection, ComplexFactory, isBlazor } from '@syncfusion/ej2-base';import { TextDecoration, WhiteSpace, TextWrap, TextAlign, GradientType, TextOverflow } from '../enum/enum';
/**
* Interface for a class Thickness
*/
export interface ThicknessModel {
}
/**
* Interface for a class Margin
*/
export interface MarginModel {
/**
* Sets the space to be left from the left side of the immediate parent of an element
*
* @default 0
*/
left?: number;
/**
* Sets the space to be left from the right side of the immediate parent of an element
*
* @default 0
*/
right?: number;
/**
* Sets the space to be left from the top side of the immediate parent of an element
*
* @default 0
*/
top?: number;
/**
* Sets the space to be left from the bottom side of the immediate parent of an element
*
* @default 0
*/
bottom?: number;
}
/**
* Interface for a class Shadow
*/
export interface ShadowModel {
/**
* Defines the angle of Shadow
*
* @default 45
*/
angle?: number;
/**
* Defines the distance of Shadow
*
* @default 5
*/
distance?: number;
/**
* Defines the opacity of Shadow
*
* @default 0.7
*/
opacity?: number;
/**
* Defines the color of Shadow
*
* @default ''
*/
color?: string;
}
/**
* Interface for a class Stop
*/
export interface StopModel {
/**
* Sets the color to be filled over the specified region
*
* @default ''
*/
color?: string;
/**
* Sets the position where the previous color transition ends and a new color transition starts
*
* @default 0
*/
offset?: number;
/**
* Describes the transparency level of the region
*
* @default 1
*/
opacity?: number;
}
/**
* Interface for a class Gradient
*/
export interface GradientModel {
/**
* Defines the stop collection of gradient
*
* @default []
*/
stops?: StopModel[];
/**
* Defines the type of gradient
* * Linear - Sets the type of the gradient as Linear
* * Radial - Sets the type of the gradient as Radial
*
* @default 'None'
*/
type?: GradientType;
/**
* Defines the id of gradient
*
* @default ''
*/
id?: string;
}
/**
* Interface for a class DiagramGradient
*/
export interface DiagramGradientModel extends GradientModel{
/**
* Defines the x1 value of linear gradient
*
* @default 0
*/
x1?: number;
/**
* Defines the x2 value of linear gradient
*
* @default 0
*/
x2?: number;
/**
* Defines the y1 value of linear gradient
*
* @default 0
*/
y1?: number;
/**
* Defines the y2 value of linear gradient
*
* @default 0
*/
y2?: number;
/**
* Defines the cx value of radial gradient
*
* @default 0
*/
cx?: number;
/**
* Defines the cy value of radial gradient
*
* @default cy
*/
cy?: number;
/**
* Defines the fx value of radial gradient
*
* @default 0
*/
fx?: number;
/**
* Defines the fy value of radial gradient
*
* @default fy
*/
fy?: number;
/**
* Defines the r value of radial gradient
*
* @default 50
*/
r?: number;
}
/**
* Interface for a class LinearGradient
*/
export interface LinearGradientModel extends GradientModel{
/**
* Defines the x1 value of linear gradient
*
* @default 0
*/
x1?: number;
/**
* Defines the x2 value of linear gradient
*
* @default 0
*/
x2?: number;
/**
* Defines the y1 value of linear gradient
*
* @default 0
*/
y1?: number;
/**
* Defines the y2 value of linear gradient
*
* @default 0
*/
y2?: number;
}
/**
* Interface for a class RadialGradient
*/
export interface RadialGradientModel extends GradientModel{
/**
* Defines the cx value of radial gradient
*
* @default 0
*/
cx?: number;
/**
* Defines the cy value of radial gradient
*
* @default cy
*/
cy?: number;
/**
* Defines the fx value of radial gradient
*
* @default 0
*/
fx?: number;
/**
* Defines the fy value of radial gradient
*
* @default fy
*/
fy?: number;
/**
* Defines the r value of radial gradient
*
* @default 50
*/
r?: number;
}
/**
* Interface for a class ShapeStyle
*/
export interface ShapeStyleModel {
/**
* Sets the fill color of a shape/path
*
* @default 'white'
*/
fill?: string;
/**
* Sets the stroke color of a shape/path
*
* @default 'black'
*/
strokeColor?: string;
/**
* Defines the pattern of dashes and spaces to stroke the path/shape
* ```html
* <div id='diagram'></div>
* ```
* ```
* let nodes: NodeModel[] = [{ id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100,
* style: { fill: 'red', strokeColor: 'blue', strokeWidth: 5,
* strokeDashArray: '2 2', opacity: 0.6 } as ShapeStyleModel,
* }];
* let diagram: Diagram = new Diagram({
* ...
* nodes: nodes,
* ...
* });
* diagram.appendTo('#diagram');
* ```
*
* @default ''
*/
strokeDashArray?: string;
/**
* Defines the stroke width of the path/shape
*
* @default 1
*/
strokeWidth?: number;
/**
* Sets the opacity of a shape/path
*
* @default 1
*/
opacity?: number;
/**
* Defines the gradient of a shape/path
*
* @default null
* @aspType object
*/
gradient?: GradientModel | LinearGradientModel | RadialGradientModel | DiagramGradientModel;
}
/**
* Interface for a class StrokeStyle
*/
export interface StrokeStyleModel extends ShapeStyleModel{
/**
* Sets the fill color of a shape/path
*
* @default 'transparent'
*/
fill?: string;
}
/**
* Interface for a class TextStyle
*/
export interface TextStyleModel extends ShapeStyleModel{
/**
* Sets the font color of a text
*
* @default 'black'
*/
color?: string;
/**
* Sets the font type of a text
*
* @default 'Arial'
*/
fontFamily?: string;
/**
* Defines the font size of a text
*
* @default 12
*/
fontSize?: number;
/**
* Enables/disables the italic style of text
*
* @default false
*/
italic?: boolean;
/**
* Enables/disables the bold style of text
*
* @default false
*/
bold?: boolean;
/**
* Defines how the white space and new line characters have to be handled
* * PreserveAll - Preserves all empty spaces and empty lines
* * CollapseSpace - Collapses the consequent spaces into one
* * CollapseAll - Collapses all consequent empty spaces and empty lines
*
* @default 'CollapseSpace'
*/
whiteSpace?: WhiteSpace;
/**
* Defines how the text should be wrapped, when the text size exceeds some specific bounds
* * WrapWithOverflow - Wraps the text so that no word is broken
* * Wrap - Wraps the text and breaks the word, if necessary
* * NoWrap - Text will no be wrapped
*
* @default 'WrapWithOverflow'
*/
textWrapping?: TextWrap;
/**
* Defines how the text should be aligned within its bounds
* * Left - Aligns the text at the left of the text bounds
* * Right - Aligns the text at the right of the text bounds
* * Center - Aligns the text at the center of the text bounds
* * Justify - Aligns the text in a justified manner
*
* @default 'Center'
*/
textAlign?: TextAlign;
/**
* Defines how the text should be decorated. For example, with underline/over line
* * Overline - Decorates the text with a line above the text
* * Underline - Decorates the text with an underline
* * LineThrough - Decorates the text by striking it with a line
* * None - Text will not have any specific decoration
*
* @default 'None'
*/
textDecoration?: TextDecoration;
/**
* Defines how to handle the text when it exceeds the given size.
* * Wrap - Wraps the text to next line, when it exceeds its bounds
* * Ellipsis - It truncates the overflown text and represents the clipping with an ellipsis
* * Clip - It clips the overflow text
*
* @default 'Wrap'
*/
textOverflow?: TextOverflow;
/**
* Sets the fill color of a shape/path
*
* @default 'transparent'
*/
fill?: string;
}
/**
* Interface for a class DiagramShapeStyle
*/
export interface DiagramShapeStyleModel {
/**
* Sets the fill color of a shape/path
*
* @default 'white'
*/
fill?: string;
/**
* Defines how to handle the text when it exceeds the given size.
* * Wrap - Wraps the text to next line, when it exceeds its bounds
* * Ellipsis - It truncates the overflown text and represents the clipping with an ellipsis
* * Clip - It clips the overflow text
*
* @default 'Wrap'
*/
textOverflow?: TextOverflow;
/**
* Defines the stroke width of the path/shape
*
* @default 1
*/
strokeWidth?: number;
/**
* Defines the gradient of a shape/path
*
* @default null
* @aspType object
*/
gradient?: GradientModel | LinearGradientModel | RadialGradientModel;
/**
* Sets the opacity of a shape/path
*
* @default 1
*/
opacity?: number;
/**
* Enables/disables the italic style of text
*
* @default false
*/
italic?: boolean;
/**
* Defines the pattern of dashes and spaces to stroke the path/shape
* ```html
* <div id='diagram'></div>
* ```
* ```
* let nodes: NodeModel[] = [{ id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100,
* style: { fill: 'red', strokeColor: 'blue', strokeWidth: 5,
* strokeDashArray: '2 2', opacity: 0.6 } as ShapeStyleModel,
* }];
* let diagram: Diagram = new Diagram({
* ...
* nodes: nodes,
* ...
* });
* diagram.appendTo('#diagram');
* ```
*
* @default ''
*/
strokeDashArray?: string;
/**
* Sets the font color of a text
*
* @default 'black'
*/
color?: string;
/**
* Defines the font size of a text
*
* @default 12
*/
fontSize?: number;
/**
* Sets the font type of a text
*
* @default 'Arial'
*/
fontFamily?: string;
/**
* Defines how the white space and new line characters have to be handled
* * PreserveAll - Preserves all empty spaces and empty lines
* * CollapseSpace - Collapses the consequent spaces into one
* * CollapseAll - Collapses all consequent empty spaces and empty lines
*
* @default 'CollapseSpace'
*/
whiteSpace?: WhiteSpace;
/**
* Defines how the text should be aligned within its bounds
* * Left - Aligns the text at the left of the text bounds
* * Right - Aligns the text at the right of the text bounds
* * Center - Aligns the text at the center of the text bounds
* * Justify - Aligns the text in a justified manner
*
* @default 'Center'
*/
textAlign?: TextAlign;
/**
* Defines how the text should be decorated. For example, with underline/over line
* * Overline - Decorates the text with a line above the text
* * Underline - Decorates the text with an underline
* * LineThrough - Decorates the text by striking it with a line
* * None - Text will not have any specific decoration
*
* @default 'None'
*/
textDecoration?: TextDecoration;
/**
* Enables/disables the bold style of text
*
* @default false
*/
bold?: boolean;
/**
* Sets the stroke color of a shape/path
*
* @default 'black'
*/
strokeColor?: string;
/**
* Defines how the text should be wrapped, when the text size exceeds some specific bounds
* * WrapWithOverflow - Wraps the text so that no word is broken
* * Wrap - Wraps the text and breaks the word, if necessary
* * NoWrap - Text will no be wrapped
*
* @default 'WrapWithOverflow'
*/
textWrapping?: TextWrap;
} | the_stack |
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset';
import styles from './ModernThemeManagerWebPart.module.scss';
import * as strings from 'ModernThemeManagerWebPartStrings';
import { IDigestCache, DigestCache } from '@microsoft/sp-http';
import { SPHttpClient, SPHttpClientResponse, ISPHttpClientOptions } from '@microsoft/sp-http';
export interface IModernThemeManagerWebPartProps {
description: string;
}
export default class ModernThemeManagerWebPart extends BaseClientSideWebPart<IModernThemeManagerWebPartProps> {
public render(): void {
this.domElement.innerHTML = `
<div class="${ styles.jsGenericWebpartThemeGenerator}">
<div class="${ styles.container}">
<div class="${ styles.row}">
<div class="${ styles.column}">
<div class="${ styles.title}">Modern Experience SharePoint Theme Manager</div>
<a class="${ styles.themeGeneratorURL}" href="https://fabricweb.z5.web.core.windows.net/pr-deploy-site/refs/pull/9318/merge/theming-designer/index.html" target="_blank">
UI Fabric Theme Generator
</a>
<div class="${ styles.hide}">
<p class="${ styles.subTitle}">Theme Actions</p>
<label class="${ styles.radio}"><input type="radio" name="themeAction" value="create"> Create a theme</label>
<label class="${ styles.radio}"><input type="radio" name="themeAction" value="update"> Update a theme</label>
<label class="${ styles.radio}"><input type="radio" name="themeAction" value="delete"> Delete a theme</label>
<label class="${ styles.radio}"><input type="radio" name="themeAction" value="apply"> Apply a theme</label>
</div>
<div>
<p class="${ styles.subTitle}">Theme Actions</p>
<label class="${ styles.radio}"><input type="radio" name="themeAction" value="apply"> Apply a theme</label>
</div>
<div class="${ styles.hide} ${styles.genericWrapper}" id="${styles.themeSelectWrapper}">
<p class="${ styles.subTitle}">Available Themes</p>
<select id="${ styles.availableThemesSelect}" name="availableThemes">
</select>
</div>
<div class="${ styles.hide} ${styles.genericWrapper}" id="${styles.themeNameWrapper}">
<p class="${ styles.subTitle}">Theme Name</p>
<div>
<input id="${ styles.input}" class="${styles.input}">
</div>
</div>
<div class="${ styles.hide} ${styles.genericWrapper}" id="${styles.themePaletteWrapper}">
<p class="${ styles.subTitle}">Theme Palette</p>
<div>
<textarea id="${ styles.textarea}" class="${styles.textarea}"></textarea>
</div>
</div>
<div class="${ styles.hide} ${styles.genericWrapper}" id="${styles.themeSiteURLWrapper}">
<p class="${ styles.subTitle}">Relative Site URL (ex: "/sites/SiteCollectionName")</p>
<div>
<input id="${ styles.siteurl}" class="${styles.siteurl}">
</div>
</div>
<div id="createTheme" class="${ styles.button} ${styles.hide}">
<span class="${ styles.label}">Create Theme</span>
</div>
<div id="updateTheme" class="${ styles.button} ${styles.hide}">
<span class="${ styles.label}">Update Theme</span>
</div>
<div id="deleteTheme" class="${ styles.button} ${styles.hide}">
<span class="${ styles.label}">Delete Theme</span>
</div>
<div id="applyTheme" class="${ styles.button} ${styles.hide}">
<span class="${ styles.label}">Apply Theme</span>
</div>
</div>
</div>
</div>
</div>`;
this.setupClickEvent();
}
/***** *****
Create event listeners for Radio & Buttons
***** *****/
public setupClickEvent(): void {
let btnCreateTheme = document.getElementById("createTheme");
btnCreateTheme.addEventListener("click", (e: Event) => this.createTheme());
let btnUpdateTheme = document.getElementById("updateTheme");
btnUpdateTheme.addEventListener("click", (e: Event) => this.updateTheme());
let btnDeleteTheme = document.getElementById("deleteTheme");
btnDeleteTheme.addEventListener("click", (e: Event) => this.deleteTheme());
let btnApplyTheme = document.getElementById("applyTheme");
btnApplyTheme.addEventListener("click", (e: Event) => this.applyThemeNew());
let radioThemeActions = document.getElementsByName("themeAction");
let parent = this;
for (var i = 0, max = radioThemeActions.length; i < max; i++) {
radioThemeActions[i].onclick = function () {
let selectedValue = (<HTMLInputElement>this).value;
if (selectedValue == 'delete') {
parent.displayDeleteOptions();
}
else if (selectedValue == 'create') {
parent.displayCreateOptions();
}
else if (selectedValue == 'update') {
parent.displayUpdateOptions();
}
else if (selectedValue == 'apply') {
parent.displayApplyOptions();
}
};
};
}
/***** *****
Hide All Wrappers:
Generic method for hiding all of the form elements
***** *****/
public hideAllWrappers(): void {
// Hide any other elements that might have been displayed
document.getElementById(styles.themeNameWrapper).classList.add(styles.hide);
document.getElementById(styles.themePaletteWrapper).classList.add(styles.hide);
let wrappers = document.getElementsByClassName(styles.genericWrapper);
for (let i = 0; i < wrappers.length; i++) {
wrappers[i].classList.add(styles.hide);
}
let buttons = document.getElementsByClassName(styles.button);
for (let i = 0; i < buttons.length; i++) {
buttons[i].classList.add(styles.hide);
}
}
/***** *****
Display Update Options:
This method is used to display the form elements for the Theme Update Options.
***** *****/
public displayUpdateOptions(): void {
// Hide all wrappers
this.hideAllWrappers();
this.populateExistingThemes("/_api/thememanager/GetTenantThemingOptions", {}).then((success: boolean) => {
if (success) {
// Display the dropdown.
document.getElementById(styles.themeSelectWrapper).classList.remove(styles.hide);
document.getElementById(styles.themePaletteWrapper).classList.remove(styles.hide);
document.getElementById('updateTheme').classList.remove(styles.hide);
}
})
};
/***** *****
Display Create Options:
This method is used to display the form elements for the Theme Creation Options.
***** *****/
public displayCreateOptions(): void {
// Hide all wrappers
this.hideAllWrappers();
// Display the dropdown.
document.getElementById(styles.themeNameWrapper).classList.remove(styles.hide);
document.getElementById(styles.themePaletteWrapper).classList.remove(styles.hide);
document.getElementById('createTheme').classList.remove(styles.hide);
}
/***** *****
Display Delete Options:
This method is used to display the form elements for the Theme Deletion Options.
***** *****/
public displayDeleteOptions(): void {
// Hide all wrappers
this.hideAllWrappers();
this.populateExistingThemes("/_api/thememanager/GetTenantThemingOptions", {}).then((success: boolean) => {
if (success) {
// Display the dropdown.
document.getElementById(styles.themeSelectWrapper).classList.remove(styles.hide);
document.getElementById('deleteTheme').classList.remove(styles.hide);
}
});
}
/***** *****
Display Apply Options:
This method is used to display the form elements for the Theme Apply Options.
***** *****/
public displayApplyOptions(): void {
// Hide all wrappers
this.hideAllWrappers();
// Display the dropdown.
document.getElementById(styles.themeNameWrapper).classList.remove(styles.hide);
document.getElementById(styles.themePaletteWrapper).classList.remove(styles.hide);
document.getElementById(styles.themeSiteURLWrapper).classList.remove(styles.hide);
document.getElementById('applyTheme').classList.remove(styles.hide);
}
/***** *****
Populate Existing Themes:
This method retrieves the currently available themes in the tenant and inserts the values into the dropdown.
***** *****/
public populateExistingThemes(url, params): Promise<boolean> {
return this.context.spHttpClient.get("/_api/thememanager/GetTenantThemingOptions", SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
return response.json();
}).then((themeJSON: any) => {
// Clear the select
let themeSelect = <HTMLInputElement>document.getElementById(styles.availableThemesSelect);
themeSelect.innerHTML = "";
for (let i = 0, max = themeJSON.themePreviews.length; i < max; i++) {
let option = document.createElement("option");
option.text = themeJSON.themePreviews[i].name;
(<HTMLInputElement>themeSelect).appendChild(option);
}
return true;
});
}
/***** *****
Create new theme at tenant level:
Collects the data needed to create a new theme at the tenant level and passes it to the creation execution method.
***** *****/
public createTheme(): void {
// Gather the theme properties
let themeTitle: string = (<HTMLInputElement>document.getElementById(styles.input)).value;
let themePalette: JSON = JSON.parse((<HTMLInputElement>document.getElementById(styles.textarea)).value);
let themePaletteJSON = {
"palette": themePalette
};
// Pass the theme properties to themeManagerExecution method
this.themeManagerExecution(this.context.pageContext.site.serverRelativeUrl + "/_api/thememanager/AddTenantTheme", { name: themeTitle, themeJson: JSON.stringify(themePaletteJSON) })
.then((sucess: boolean) => {
if (sucess) {
//it worked
alert('The theme has been successfully created');
}
else {
//it didn't
alert('An error has occurred');
}
});
}
/***** *****
Deletes a theme at tenant level:
Collects the data needed to delete a theme at the tenant level and passes it to the deletion execution method.
***** *****/
public deleteTheme(): void {
// Gather the theme properties
let themeTitle: string = (<HTMLInputElement>document.getElementById(styles.availableThemesSelect)).value;
// Setup the success message
let successMessage: string = 'The theme has been successfully deleted';
// Pass the theme properties to themeManagerExecution method
this.themeManagerExecution(this.context.pageContext.site.serverRelativeUrl + "/_api/thememanager/DeleteTenantTheme", { name: themeTitle })
.then((sucess: boolean) => {
if (sucess) {
//it worked
alert('The theme has been successfully deleted');
}
else {
//it didn't
alert('An error has occurred');
}
});
}
/***** *****
Updates a theme at tenant level:
Collects the data needed to update a theme at the tenant level and passes it to the update execution method.
***** *****/
public updateTheme(): void {
// Gather the theme properties
let themeTitle: string = (<HTMLInputElement>document.getElementById(styles.availableThemesSelect)).value;
let themePalette: JSON = JSON.parse((<HTMLInputElement>document.getElementById(styles.textarea)).value);
let themePaletteJSON = {
"palette": themePalette
}
// Pass the theme properties to themeManagerExecution method
this.themeManagerExecution(this.context.pageContext.site.serverRelativeUrl + "/_api/thememanager/UpdateTenantTheme", { name: themeTitle, themeJson: JSON.stringify(themePaletteJSON) })
.then((sucess: boolean) => {
if (sucess) {
//it worked
alert('The theme has been successfully updated');
}
else {
//it didn't
alert('An error has occurred');
}
});
}
/***** *****
Apply a theme to a site collection:
Collects the data needed to apply a theme directly to a site colleciton.
NOTE: This does NOT create a theme choice at the tenant level. It will directly apply the theme to a site collection.
***** *****/
public applyThemeNew(): void {
// Gather the theme properties
let themeURL: string = (<HTMLInputElement>document.getElementById(styles.siteurl)).value;
let themeTitle: string = (<HTMLInputElement>document.getElementById(styles.input)).value;
let themePalette: JSON = JSON.parse((<HTMLInputElement>document.getElementById(styles.textarea)).value);
let themePaletteJSON = {
"palette": themePalette
}
const digestCache: IDigestCache = this.context.serviceScope.consume(DigestCache.serviceKey);
digestCache.fetchDigest(themeURL).then((digest: string): void => {
// Pass the theme properties to themeManagerExecution method
this.themeManagerExecution(themeURL + "/_api/thememanager/ApplyTheme", { name: themeTitle, themeJson: JSON.stringify(themePaletteJSON) })
.then((sucess: boolean) => {
if (sucess) {
//it worked
alert('The theme has been successfully applied');
}
else {
//it didn't
alert('An error has occurred');
}
});
});
}
/***** *****
Generic method for creating, updating, deleting and applying a theme.
***** *****/
public themeManagerExecution(url: string, params: any): Promise<boolean> {
let options: ISPHttpClientOptions = {
body: JSON.stringify(params)
}
return this.context.spHttpClient.post(url, SPHttpClient.configurations.v1, options)
.then((response: SPHttpClientResponse) => {
return response.ok
});
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
})
]
}
]
}
]
};
}
} | the_stack |
import { EventEmitter } from 'events';
import MultiFormat from '@requestnetwork/multi-format';
import {
AdvancedLogicTypes,
EncryptionTypes,
IdentityTypes,
RequestLogicTypes,
SignatureProviderTypes,
TransactionTypes,
} from '@requestnetwork/types';
import Utils from '@requestnetwork/utils';
import RequestLogicCore from './requestLogicCore';
/**
* Implementation of Request Logic
*/
export default class RequestLogic implements RequestLogicTypes.IRequestLogic {
private advancedLogic: AdvancedLogicTypes.IAdvancedLogic | undefined;
private transactionManager: TransactionTypes.ITransactionManager;
private signatureProvider: SignatureProviderTypes.ISignatureProvider | undefined;
public constructor(
transactionManager: TransactionTypes.ITransactionManager,
signatureProvider?: SignatureProviderTypes.ISignatureProvider,
advancedLogic?: AdvancedLogicTypes.IAdvancedLogic,
) {
this.transactionManager = transactionManager;
this.signatureProvider = signatureProvider;
this.advancedLogic = advancedLogic;
}
/**
* Creates a request and persists it on the transaction manager layer
*
* @param ICreateParameters parameters to create a request
* @param signerIdentity Identity of the signer
* @param topics list of string to topic the request
*
* @returns the request id and the meta data
*/
public async createRequest(
requestParameters: RequestLogicTypes.ICreateParameters,
signerIdentity: IdentityTypes.IIdentity,
topics: any[] = [],
): Promise<RequestLogicTypes.IReturnCreateRequest> {
const { action, requestId, hashedTopics } = await this.createCreationActionRequestIdAndTopics(
requestParameters,
signerIdentity,
topics,
);
// Validate the action, the apply will throw in case of error
RequestLogicCore.applyActionToRequest(null, action, Date.now(), this.advancedLogic);
const resultPersistTx = await this.transactionManager.persistTransaction(
JSON.stringify(action),
requestId,
hashedTopics,
);
const result = Object.assign(new EventEmitter(), {
meta: { transactionManagerMeta: resultPersistTx.meta },
result: { requestId },
});
// When receive the confirmation from transaction manager propagate it
resultPersistTx
.on('confirmed', (resultPersistTxConfirmed: TransactionTypes.IReturnPersistTransaction) => {
result.emit('confirmed', {
meta: { transactionManagerMeta: resultPersistTxConfirmed.meta },
result: { requestId },
});
})
.on('error', (error) => {
result.emit('error', error);
});
return result;
}
/**
* Creates an encrypted request and persists it on the transaction manager layer
*
* @param requestParameters parameters to create a request
* @param signerIdentity Identity of the signer
* @param encryptionParams list of encryption parameters to encrypt the channel key with
* @param topics list of string to topic the request
*
* @returns the request id and the meta data
*/
public async createEncryptedRequest(
requestParameters: RequestLogicTypes.ICreateParameters,
signerIdentity: IdentityTypes.IIdentity,
encryptionParams: EncryptionTypes.IEncryptionParameters[],
topics: any[] = [],
): Promise<RequestLogicTypes.IReturnCreateRequest> {
if (encryptionParams.length === 0) {
throw new Error(
'You must give at least one encryption parameter to create an encrypted request',
);
}
const { action, requestId, hashedTopics } = await this.createCreationActionRequestIdAndTopics(
requestParameters,
signerIdentity,
topics,
);
// Validate the action, the apply will throw in case of error
RequestLogicCore.applyActionToRequest(null, action, Date.now(), this.advancedLogic);
const resultPersistTx = await this.transactionManager.persistTransaction(
JSON.stringify(action),
requestId,
hashedTopics,
encryptionParams,
);
const result = Object.assign(new EventEmitter(), {
meta: { transactionManagerMeta: resultPersistTx.meta },
result: { requestId },
});
// When receive the confirmation from transaction manager propagate it
resultPersistTx
.on('confirmed', (resultPersistTxConfirmed: TransactionTypes.IReturnPersistTransaction) => {
result.emit('confirmed', {
meta: { transactionManagerMeta: resultPersistTxConfirmed.meta },
result: { requestId },
});
})
.on('error', (error) => {
result.emit('error', error);
});
return result;
}
/**
* Function to compute the id of a request without creating it
*
* @param requestParameters ICreateParameters parameters to create a request
* @param IIdentity signerIdentity Identity of the signer
*
* @returns Promise<RequestLogicTypes.RequestId> the request id
*/
public async computeRequestId(
requestParameters: RequestLogicTypes.ICreateParameters,
signerIdentity: IdentityTypes.IIdentity,
): Promise<RequestLogicTypes.RequestId> {
if (!this.signatureProvider) {
throw new Error('You must give a signature provider to create actions');
}
const action = await RequestLogicCore.formatCreate(
requestParameters,
signerIdentity,
this.signatureProvider,
);
// Validate the action, the apply will throw in case of error
RequestLogicCore.applyActionToRequest(null, action, Date.now(), this.advancedLogic);
return RequestLogicCore.getRequestIdFromAction(action);
}
/**
* Function to accept a request it on through the transaction manager layer
*
* @param IAcceptParameters acceptParameters parameters to accept a request
* @param IIdentity signerIdentity Identity of the signer
* @param boolean validate specifies if a validation should be done before persisting the transaction. Requires a full load of the Request.
*
* @returns Promise<IRequestLogicReturn> the meta data
*/
public async acceptRequest(
requestParameters: RequestLogicTypes.IAcceptParameters,
signerIdentity: IdentityTypes.IIdentity,
validate = false,
): Promise<RequestLogicTypes.IRequestLogicReturnWithConfirmation> {
if (!this.signatureProvider) {
throw new Error('You must give a signature provider to create actions');
}
const action = await RequestLogicCore.formatAccept(
requestParameters,
signerIdentity,
this.signatureProvider,
);
const requestId = RequestLogicCore.getRequestIdFromAction(action);
if (validate) {
await this.validateAction(requestId, action);
}
const resultPersistTx = await this.transactionManager.persistTransaction(
JSON.stringify(action),
requestId,
);
const result = Object.assign(new EventEmitter(), {
meta: { transactionManagerMeta: resultPersistTx.meta },
});
// When receive the confirmation from transaction manager propagate it
resultPersistTx
.on('confirmed', (resultPersistTxConfirmed: TransactionTypes.IReturnPersistTransaction) => {
result.emit('confirmed', {
meta: { transactionManagerMeta: resultPersistTxConfirmed.meta },
});
})
.on('error', (error) => {
result.emit('error', error);
});
return result;
}
/**
* Function to cancel a request and persist it on through the transaction manager layer
*
* @param ICancelParameters cancelParameters parameters to cancel a request
* @param IIdentity signerIdentity Identity of the signer
* @param boolean validate specifies if a validation should be done before persisting the transaction. Requires a full load of the Request.
*
* @returns Promise<IRequestLogicReturn> the meta data
*/
public async cancelRequest(
requestParameters: RequestLogicTypes.ICancelParameters,
signerIdentity: IdentityTypes.IIdentity,
validate = false,
): Promise<RequestLogicTypes.IRequestLogicReturnWithConfirmation> {
if (!this.signatureProvider) {
throw new Error('You must give a signature provider to create actions');
}
const action = await RequestLogicCore.formatCancel(
requestParameters,
signerIdentity,
this.signatureProvider,
);
const requestId = RequestLogicCore.getRequestIdFromAction(action);
if (validate) {
await this.validateAction(requestId, action);
}
const resultPersistTx = await this.transactionManager.persistTransaction(
JSON.stringify(action),
requestId,
);
const result = Object.assign(new EventEmitter(), {
meta: { transactionManagerMeta: resultPersistTx.meta },
});
// When receive the confirmation from transaction manager propagate it
resultPersistTx
.on('confirmed', (resultPersistTxConfirmed: TransactionTypes.IReturnPersistTransaction) => {
result.emit('confirmed', {
meta: { transactionManagerMeta: resultPersistTxConfirmed.meta },
});
})
.on('error', (error) => {
result.emit('error', error);
});
return result;
}
/**
* Function to increase expected amount of a request and persist it on through the transaction manager layer
*
* @param IIncreaseExpectedAmountParameters increaseAmountParameters parameters to increase expected amount of a request
* @param IIdentity signerIdentity Identity of the signer
* @param boolean validate specifies if a validation should be done before persisting the transaction. Requires a full load of the Request.
*
* @returns Promise<IRequestLogicReturn> the meta data
*/
public async increaseExpectedAmountRequest(
requestParameters: RequestLogicTypes.IIncreaseExpectedAmountParameters,
signerIdentity: IdentityTypes.IIdentity,
validate = false,
): Promise<RequestLogicTypes.IRequestLogicReturnWithConfirmation> {
if (!this.signatureProvider) {
throw new Error('You must give a signature provider to create actions');
}
const action = await RequestLogicCore.formatIncreaseExpectedAmount(
requestParameters,
signerIdentity,
this.signatureProvider,
);
const requestId = RequestLogicCore.getRequestIdFromAction(action);
if (validate) {
await this.validateAction(requestId, action);
}
const resultPersistTx = await this.transactionManager.persistTransaction(
JSON.stringify(action),
requestId,
);
const result = Object.assign(new EventEmitter(), {
meta: { transactionManagerMeta: resultPersistTx.meta },
});
// When receive the confirmation from transaction manager propagate it
resultPersistTx
.on('confirmed', (resultPersistTxConfirmed: TransactionTypes.IReturnPersistTransaction) => {
result.emit('confirmed', {
meta: { transactionManagerMeta: resultPersistTxConfirmed.meta },
});
})
.on('error', (error) => {
result.emit('error', error);
});
return result;
}
/**
* Function to reduce expected amount of a request and persist it on through the transaction manager layer
*
* @param IReduceExpectedAmountParameters reduceAmountParameters parameters to reduce expected amount of a request
* @param IIdentity signerIdentity Identity of the signer
* @param boolean validate specifies if a validation should be done before persisting the transaction. Requires a full load of the Request.
*
* @returns Promise<IRequestLogicReturn> the meta data
*/
public async reduceExpectedAmountRequest(
requestParameters: RequestLogicTypes.IReduceExpectedAmountParameters,
signerIdentity: IdentityTypes.IIdentity,
validate = false,
): Promise<RequestLogicTypes.IRequestLogicReturnWithConfirmation> {
if (!this.signatureProvider) {
throw new Error('You must give a signature provider to create actions');
}
const action = await RequestLogicCore.formatReduceExpectedAmount(
requestParameters,
signerIdentity,
this.signatureProvider,
);
const requestId = RequestLogicCore.getRequestIdFromAction(action);
if (validate) {
await this.validateAction(requestId, action);
}
const resultPersistTx = await this.transactionManager.persistTransaction(
JSON.stringify(action),
requestId,
);
const result = Object.assign(new EventEmitter(), {
meta: { transactionManagerMeta: resultPersistTx.meta },
});
// When receive the confirmation from transaction manager propagate it
resultPersistTx
.on('confirmed', (resultPersistTxConfirmed: TransactionTypes.IReturnPersistTransaction) => {
result.emit('confirmed', {
meta: { transactionManagerMeta: resultPersistTxConfirmed.meta },
});
})
.on('error', (error) => {
result.emit('error', error);
});
return result;
}
/**
* Function to add extensions data to a request and persist it through the transaction manager layer
*
* @param IAddExtensionsDataParameters requestParameters parameters to add extensions Data to a request
* @param IIdentity signerIdentity Identity of the signer
* @param boolean validate specifies if a validation should be done before persisting the transaction. Requires a full load of the Request.
*
* @returns Promise<IRequestLogicReturn> the meta data
*/
public async addExtensionsDataRequest(
requestParameters: RequestLogicTypes.IAddExtensionsDataParameters,
signerIdentity: IdentityTypes.IIdentity,
validate = false,
): Promise<RequestLogicTypes.IRequestLogicReturnWithConfirmation> {
if (!this.signatureProvider) {
throw new Error('You must give a signature provider to create actions');
}
const action = await RequestLogicCore.formatAddExtensionsData(
requestParameters,
signerIdentity,
this.signatureProvider,
);
const requestId = RequestLogicCore.getRequestIdFromAction(action);
if (validate) {
await this.validateAction(requestId, action);
}
const resultPersistTx = await this.transactionManager.persistTransaction(
JSON.stringify(action),
requestId,
);
const result = Object.assign(new EventEmitter(), {
meta: { transactionManagerMeta: resultPersistTx.meta },
});
// When receive the confirmation from transaction manager propagate it
resultPersistTx
.on('confirmed', (resultPersistTxConfirmed: TransactionTypes.IReturnPersistTransaction) => {
result.emit('confirmed', {
meta: { transactionManagerMeta: resultPersistTxConfirmed.meta },
});
})
.on('error', (error) => {
result.emit('error', error);
});
return result;
}
/**
* Function to get a request from the request id from the actions in the data-access layer
*
* @param requestId the requestId of the request to retrieve
*
* @returns the request constructed from the actions
*/
public async getRequestFromId(
requestId: string,
): Promise<RequestLogicTypes.IReturnGetRequestFromId> {
const {
ignoredTransactions,
confirmedRequestState,
pendingRequestState,
transactionManagerMeta,
} = await this.computeRequestFromRequestId(requestId);
const pending = this.computeDiffBetweenPendingAndConfirmedRequestState(
confirmedRequestState,
pendingRequestState,
);
return {
meta: {
ignoredTransactions,
transactionManagerMeta,
},
result: { request: confirmedRequestState, pending },
};
}
/**
* Gets the requests indexed by a topic from the transactions of transaction-manager layer
*
* @param topic
* @returns all the requests indexed by topic
*/
public async getRequestsByTopic(
topic: string,
updatedBetween?: RequestLogicTypes.ITimestampBoundaries,
): Promise<RequestLogicTypes.IReturnGetRequestsByTopic> {
// hash all the topics
const hashedTopic = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(topic));
const getChannelsResult = await this.transactionManager.getChannelsByTopic(
hashedTopic,
updatedBetween,
);
return this.computeMultipleRequestFromChannels(getChannelsResult);
}
/**
* Gets the requests indexed by multiple topics from the transactions of transaction-manager layer
*
* @param topics
* @returns all the requests indexed by topics
*/
public async getRequestsByMultipleTopics(
topics: string[],
updatedBetween?: RequestLogicTypes.ITimestampBoundaries,
): Promise<RequestLogicTypes.IReturnGetRequestsByTopic> {
// hash all the topics
const hashedTopics = topics.map((topic) =>
MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(topic)),
);
const getChannelsResult = await this.transactionManager.getChannelsByMultipleTopics(
hashedTopics,
updatedBetween,
);
return this.computeMultipleRequestFromChannels(getChannelsResult);
}
/**
* Creates the creation action and the requestId of a request
*
* @param requestParameters parameters to create a request
* @param signerIdentity Identity of the signer
*
* @returns the request id, the action and the hashed topics
*/
private async createCreationActionRequestIdAndTopics(
requestParameters: RequestLogicTypes.ICreateParameters,
signerIdentity: IdentityTypes.IIdentity,
topics: any[],
): Promise<{
action: RequestLogicTypes.IAction;
hashedTopics: string[];
requestId: RequestLogicTypes.RequestId;
}> {
if (!this.signatureProvider) {
throw new Error('You must give a signature provider to create actions');
}
const action = await RequestLogicCore.formatCreate(
requestParameters,
signerIdentity,
this.signatureProvider,
);
const requestId = RequestLogicCore.getRequestIdFromAction(action);
// hash all the topics
const hashedTopics = topics.map((topic) =>
MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(topic)),
);
return {
action,
hashedTopics,
requestId,
};
}
/**
* Interprets a request from requestId
*
* @param requestId the requestId of the request to compute
* @returns the request, the pending state of the request and the ignored transactions
*/
private async computeRequestFromRequestId(
requestId: RequestLogicTypes.RequestId,
): Promise<{
confirmedRequestState: RequestLogicTypes.IRequest | null;
pendingRequestState: RequestLogicTypes.IRequest | null;
ignoredTransactions: any[];
transactionManagerMeta: any;
}> {
const resultGetTx = await this.transactionManager.getTransactionsByChannelId(requestId);
const actions = resultGetTx.result.transactions
// filter the actions ignored by the previous layers
.filter(Utils.notNull)
.sort((a, b) => a.timestamp - b.timestamp);
// eslint-disable-next-line prefer-const
let { ignoredTransactions, keptTransactions } = this.removeOldPendingTransactions(actions);
// array of transaction without duplicates to avoid replay attack
const timestampedActionsWithoutDuplicates = Utils.uniqueByProperty(
keptTransactions
.filter(Utils.notNull)
.map((t) => {
try {
return {
action: JSON.parse(t.transaction.data || ''),
state: t.state,
timestamp: t.timestamp,
};
} catch (e) {
// We ignore the transaction.data that cannot be parsed
ignoredTransactions.push({
reason: 'JSON parsing error',
transaction: t,
});
return;
}
})
.filter(Utils.notNull),
'action',
);
// Keeps the transaction ignored
ignoredTransactions = ignoredTransactions.concat(
timestampedActionsWithoutDuplicates.duplicates.map((tx) => {
return {
reason: 'Duplicated transaction',
transaction: tx,
};
}),
);
const {
confirmedRequestState,
pendingRequestState,
ignoredTransactionsByApplication,
} = await this.computeRequestFromTransactions(timestampedActionsWithoutDuplicates.uniqueItems);
ignoredTransactions = ignoredTransactions.concat(ignoredTransactionsByApplication);
return {
confirmedRequestState,
ignoredTransactions,
pendingRequestState,
transactionManagerMeta: resultGetTx.meta,
};
}
/**
* Interprets a request from transactions
*
* @param transactions transactions to compute the request from
* @returns the request and the ignoredTransactions
*/
private async computeRequestFromTransactions(
transactions: RequestLogicTypes.IConfirmedAction[],
): Promise<{
confirmedRequestState: RequestLogicTypes.IRequest | null;
pendingRequestState: RequestLogicTypes.IRequest | null;
ignoredTransactionsByApplication: RequestLogicTypes.IIgnoredTransaction[];
}> {
const ignoredTransactionsByApplication: RequestLogicTypes.IIgnoredTransaction[] = [];
// second parameter is null, because the first action must be a creation (no state expected)
const confirmedRequestState = transactions
.filter((action) => action.state === TransactionTypes.TransactionState.CONFIRMED)
.reduce((requestState, actionConfirmed) => {
try {
return RequestLogicCore.applyActionToRequest(
requestState,
actionConfirmed.action,
actionConfirmed.timestamp,
this.advancedLogic,
);
} catch (e) {
// if an error occurs while applying we ignore the action
ignoredTransactionsByApplication.push({
reason: e.message,
transaction: actionConfirmed,
});
return requestState;
}
}, null as RequestLogicTypes.IRequest | null);
const pendingRequestState = transactions
.filter((action) => action.state === TransactionTypes.TransactionState.PENDING)
.reduce((requestState, actionConfirmed) => {
try {
return RequestLogicCore.applyActionToRequest(
requestState,
actionConfirmed.action,
actionConfirmed.timestamp,
this.advancedLogic,
);
} catch (e) {
// if an error occurs while applying we ignore the action
ignoredTransactionsByApplication.push({
reason: e.message,
transaction: actionConfirmed,
});
return requestState;
}
}, confirmedRequestState);
return {
confirmedRequestState,
ignoredTransactionsByApplication,
pendingRequestState,
};
}
/**
* Interprets multiple requests from channels
*
* @param channelsRawData returned value by getChannels function
* @returns the requests and meta data
*/
private async computeMultipleRequestFromChannels(
channelsRawData: TransactionTypes.IReturnGetTransactionsByChannels,
): Promise<RequestLogicTypes.IReturnGetRequestsByTopic> {
const transactionsByChannel = channelsRawData.result.transactions;
const transactionManagerMeta = channelsRawData.meta.dataAccessMeta;
// Gets all the requests from the transactions
const allRequestAndMetaPromises = Object.keys(channelsRawData.result.transactions).map(
// Parses and removes corrupted or duplicated transactions
async (channelId) => {
// eslint-disable-next-line prefer-const
let { ignoredTransactions, keptTransactions } = this.removeOldPendingTransactions(
transactionsByChannel[channelId],
);
const timestampedActionsWithoutDuplicates = Utils.uniqueByProperty(
keptTransactions
// filter the actions ignored by the previous layers
.filter(Utils.notNull)
.map((t) => {
try {
return {
action: JSON.parse(t.transaction.data || ''),
state: t.state,
timestamp: t.timestamp,
};
} catch (e) {
// We ignore the transaction.data that cannot be parsed
ignoredTransactions.push({
reason: 'JSON parsing error',
transaction: t,
});
return;
}
})
.filter(Utils.notNull),
'action',
);
// Keeps the ignored transactions
ignoredTransactions = ignoredTransactions.concat(
timestampedActionsWithoutDuplicates.duplicates.map((tx) => ({
reason: 'Duplicated transaction',
transaction: tx,
})),
);
// Computes the request from the transactions
const {
confirmedRequestState,
pendingRequestState,
ignoredTransactionsByApplication,
} = await this.computeRequestFromTransactions(
timestampedActionsWithoutDuplicates.uniqueItems,
);
ignoredTransactions = ignoredTransactions.concat(ignoredTransactionsByApplication);
const pending = this.computeDiffBetweenPendingAndConfirmedRequestState(
confirmedRequestState,
pendingRequestState,
);
return {
ignoredTransactions,
pending,
request: confirmedRequestState,
transactionManagerMeta: transactionManagerMeta[channelId],
};
},
);
const allRequestAndMeta = await Promise.all(allRequestAndMetaPromises);
// Merge all the requests and meta in one object
return allRequestAndMeta.reduce(
(finalResult: RequestLogicTypes.IReturnGetRequestsByTopic, requestAndMeta: any) => {
if (requestAndMeta.request || requestAndMeta.pending) {
finalResult.result.requests.push({
pending: requestAndMeta.pending,
request: requestAndMeta.request,
});
// workaround to quiet the error "finalResult.meta.ignoredTransactions can be undefined" (but defined in the initialization value of the accumulator)
(finalResult.meta.ignoredTransactions || []).push(requestAndMeta.ignoredTransactions);
// add the transactionManagerMeta
(finalResult.meta.transactionManagerMeta || []).push(
requestAndMeta.transactionManagerMeta,
);
}
return finalResult;
},
{
meta: {
ignoredTransactions: [],
transactionManagerMeta: [],
},
result: { requests: [] },
},
);
}
/**
* Validates an action, throws if the action is invalid
*
* @param requestId the requestId of the request to retrieve
* @param action the action to validate
*
* @returns void, throws if the action is invalid
*/
private async validateAction(
requestId: RequestLogicTypes.RequestId,
action: RequestLogicTypes.IAction,
): Promise<void> {
const { confirmedRequestState, pendingRequestState } = await this.computeRequestFromRequestId(
requestId,
);
try {
// Check if the action doesn't fail with the request state
RequestLogicCore.applyActionToRequest(
confirmedRequestState,
action,
Date.now(),
this.advancedLogic,
);
} catch (error) {
// Check if the action works with the pending state
if (pendingRequestState) {
RequestLogicCore.applyActionToRequest(
pendingRequestState,
action,
Date.now(),
this.advancedLogic,
);
}
}
}
/**
* Computes the diff between the confirmed and pending request
*
* @param confirmedRequestState the confirmed request state
* @param pendingRequestState the pending request state
* @returns an object with the pending state attributes that are different from the confirmed one
*/
private computeDiffBetweenPendingAndConfirmedRequestState(
confirmedRequestState: any,
pendingRequestState: any,
): RequestLogicTypes.IPendingRequest | null {
// Compute the diff between the confirmed and pending request
let pending: any = null;
if (!confirmedRequestState) {
pending = pendingRequestState;
} else if (pendingRequestState) {
for (const key in pendingRequestState) {
if (key in pendingRequestState) {
// TODO: Should find a better way to do that
if (
Utils.crypto.normalizeKeccak256Hash(pendingRequestState[key]).value !==
Utils.crypto.normalizeKeccak256Hash(confirmedRequestState[key]).value
) {
if (!pending) {
pending = {};
}
// eslint-disable-next-line
if (key === 'events') {
// keep only the new events in pending
pending[key] = pendingRequestState[key].slice(confirmedRequestState[key].length);
} else {
pending[key] = pendingRequestState[key];
}
}
}
}
}
return pending as RequestLogicTypes.IPendingRequest | null;
}
/**
* Sorts out the transactions pending older than confirmed ones
*
* @param actions list of the actions
* @returns an object with the ignoredTransactions and the kept actions
*/
private removeOldPendingTransactions(
transactions: Array<TransactionTypes.ITimestampedTransaction | null>,
): {
ignoredTransactions: any[];
keptTransactions: Array<TransactionTypes.ITimestampedTransaction | null>;
} {
const ignoredTransactions: any[] = [];
// ignored the transactions pending older than confirmed ones
let confirmedFound = false;
const keptTransactions = transactions
.reverse()
.filter((action) => {
if (!action) {
return false;
}
// Have we already found confirmed transactions
confirmedFound =
confirmedFound || action.state === TransactionTypes.TransactionState.CONFIRMED;
// keep the transaction if confirmed or pending but no confirmed found before
if (
action.state === TransactionTypes.TransactionState.CONFIRMED ||
(action.state === TransactionTypes.TransactionState.PENDING && !confirmedFound)
) {
return true;
} else {
// Keeps the ignored transactions
ignoredTransactions.push({
reason: 'Confirmed transaction newer than this pending transaction',
transaction: action,
});
return false;
}
})
.reverse();
return { ignoredTransactions, keptTransactions };
}
} | the_stack |
import dynamicProto from "@microsoft/dynamicproto-js";
import { ITelemetryItem, IProcessTelemetryContext, IAppInsightsCore, isString, objKeys, hasWindow, _InternalLogMessage, setValue, getSetValue, IDistributedTraceContext } from "@microsoft/applicationinsights-core-js";
import { Session, _SessionManager } from "./Context/Session";
import { Extensions, IOperatingSystem, ITelemetryTrace, IWeb, CtxTagKeys, PageView, IApplication, IDevice, ILocation, IUserContext, IInternal, ISession } from "@microsoft/applicationinsights-common";
import { Application } from "./Context/Application";
import { Device } from "./Context/Device";
import { Internal } from "./Context/Internal";
import { User } from "./Context/User";
import { Location } from "./Context/Location";
import { ITelemetryConfig } from "./Interfaces/ITelemetryConfig";
import { TelemetryTrace } from "./Context/TelemetryTrace";
import { IPropTelemetryContext } from "./Interfaces/IPropTelemetryContext";
const strExt = "ext";
const strTags = "tags";
function _removeEmpty(target: any, name: string) {
if (target && target[name] && objKeys(target[name]).length === 0) {
delete target[name];
}
}
export class TelemetryContext implements IPropTelemetryContext {
public application: IApplication; // The object describing a component tracked by this object - legacy
public device: IDevice; // The object describing a device tracked by this object.
public location: ILocation; // The object describing a location tracked by this object -legacy
public telemetryTrace: ITelemetryTrace; // The object describing a operation tracked by this object.
public user: IUserContext; // The object describing a user tracked by this object.
public internal: IInternal; // legacy
public session: ISession; // The object describing a session tracked by this object.
public sessionManager: _SessionManager; // The session manager that manages session on the base of cookies.
public os: IOperatingSystem;
public web: IWeb;
public appId: () => string;
public getSessionId: () => string;
constructor(core: IAppInsightsCore, defaultConfig: ITelemetryConfig, previousTraceCtx?: IDistributedTraceContext) {
let logger = core.logger
this.appId = () => null;
this.getSessionId = () => null;
dynamicProto(TelemetryContext, this, (_self) => {
_self.application = new Application();
_self.internal = new Internal(defaultConfig);
if (hasWindow()) {
_self.sessionManager = new _SessionManager(defaultConfig, core);
_self.device = new Device();
_self.location = new Location();
_self.user = new User(defaultConfig, core);
let traceId: string;
let parentId: string;
let name: string;
if (previousTraceCtx) {
traceId = previousTraceCtx.getTraceId();
parentId = previousTraceCtx.getSpanId();
name = previousTraceCtx.getName();
}
_self.telemetryTrace = new TelemetryTrace(traceId, parentId, name, logger);
_self.session = new Session();
}
_self.getSessionId = () => {
let session = _self.session;
let sesId = null;
// If customer set session info, apply their context; otherwise apply context automatically generated
if (session && isString(session.id)) {
sesId = session.id;
} else {
// Gets the automatic session if it exists or an empty object
let autoSession = (_self.sessionManager || {} as _SessionManager).automaticSession;
sesId = autoSession && isString(autoSession.id) ? autoSession.id : null;
}
return sesId;
}
_self.applySessionContext = (evt: ITelemetryItem, itemCtx?: IProcessTelemetryContext) => {
setValue(getSetValue(evt.ext, Extensions.AppExt), "sesId", _self.getSessionId(), isString);
}
_self.applyOperatingSystemContxt = (evt: ITelemetryItem, itemCtx?: IProcessTelemetryContext) => {
setValue(evt.ext, Extensions.OSExt, _self.os);
};
_self.applyApplicationContext = (evt: ITelemetryItem, itemCtx?: IProcessTelemetryContext) => {
let application = _self.application;
if (application) {
// evt.ext.app
let tags = getSetValue(evt, strTags);
setValue(tags, CtxTagKeys.applicationVersion, application.ver, isString);
setValue(tags, CtxTagKeys.applicationBuild, application.build, isString)
}
};
_self.applyDeviceContext = (evt: ITelemetryItem, itemCtx?: IProcessTelemetryContext) => {
let device = _self.device;
if (device) {
// evt.ext.device
let extDevice = getSetValue(getSetValue(evt, strExt), Extensions.DeviceExt);
setValue(extDevice, "localId", device.id, isString);
setValue(extDevice, "ip", device.ip, isString);
setValue(extDevice, "model", device.model, isString);
setValue(extDevice, "deviceClass", device.deviceClass, isString);
}
};
_self.applyInternalContext = (evt: ITelemetryItem, itemCtx?: IProcessTelemetryContext) => {
let internal = _self.internal;
if (internal) {
let tags = getSetValue(evt, strTags);
setValue(tags, CtxTagKeys.internalAgentVersion, internal.agentVersion, isString); // not mapped in CS 4.0
setValue(tags, CtxTagKeys.internalSdkVersion, internal.sdkVersion, isString);
if (evt.baseType === _InternalLogMessage.dataType || evt.baseType === PageView.dataType) {
setValue(tags, CtxTagKeys.internalSnippet, internal.snippetVer, isString);
setValue(tags, CtxTagKeys.internalSdkSrc, internal.sdkSrc, isString);
}
}
};
_self.applyLocationContext = (evt: ITelemetryItem, itemCtx?: IProcessTelemetryContext) => {
let location = this.location;
if (location) {
setValue(getSetValue(evt, strTags, []), CtxTagKeys.locationIp, location.ip, isString);
}
};
_self.applyOperationContext = (evt: ITelemetryItem, itemCtx?: IProcessTelemetryContext) => {
let telemetryTrace = _self.telemetryTrace;
if (telemetryTrace) {
const extTrace = getSetValue(getSetValue(evt, strExt), Extensions.TraceExt, { traceID: undefined, parentID: undefined } as ITelemetryTrace);
setValue(extTrace, "traceID", telemetryTrace.traceID, isString);
setValue(extTrace, "name", telemetryTrace.name, isString);
setValue(extTrace, "parentID", telemetryTrace.parentID, isString);
}
};
_self.applyWebContext = (evt: ITelemetryItem, itemCtx?: IProcessTelemetryContext) => {
let web = this.web;
if (web) {
setValue(getSetValue(evt, strExt), Extensions.WebExt, web);
}
}
_self.applyUserContext = (evt: ITelemetryItem, itemCtx?: IProcessTelemetryContext) => {
let user = _self.user;
if (user) {
let tags = getSetValue(evt, strTags, []);
// stays in tags
setValue(tags, CtxTagKeys.userAccountId, user.accountId, isString);
// CS 4.0
let extUser = getSetValue(getSetValue(evt, strExt), Extensions.UserExt);
setValue(extUser, "id", user.id, isString);
setValue(extUser, "authId", user.authenticatedId, isString);
}
}
_self.cleanUp = (evt:ITelemetryItem, itemCtx?: IProcessTelemetryContext) => {
let ext = evt.ext;
if (ext) {
_removeEmpty(ext, Extensions.DeviceExt);
_removeEmpty(ext, Extensions.UserExt);
_removeEmpty(ext, Extensions.WebExt);
_removeEmpty(ext, Extensions.OSExt);
_removeEmpty(ext, Extensions.AppExt);
_removeEmpty(ext, Extensions.TraceExt);
}
}
});
}
public applySessionContext(evt: ITelemetryItem, itemCtx?: IProcessTelemetryContext) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public applyOperatingSystemContxt(event: ITelemetryItem, itemCtx?: IProcessTelemetryContext) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public applyApplicationContext(event: ITelemetryItem, itemCtx?: IProcessTelemetryContext) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public applyDeviceContext(event: ITelemetryItem, itemCtx?: IProcessTelemetryContext) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public applyInternalContext(event: ITelemetryItem, itemCtx?: IProcessTelemetryContext) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public applyLocationContext(event: ITelemetryItem, itemCtx?: IProcessTelemetryContext) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public applyOperationContext(event: ITelemetryItem, itemCtx?: IProcessTelemetryContext) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public applyWebContext(event: ITelemetryItem, itemCtx?: IProcessTelemetryContext) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public applyUserContext(event: ITelemetryItem, itemCtx?: IProcessTelemetryContext) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public cleanUp(event:ITelemetryItem, itemCtx?: IProcessTelemetryContext): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
} | the_stack |
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
import {
buildOtherBucketAgg,
mergeOtherBucketAggResponse,
updateMissingBucket,
} from './_terms_other_bucket_helper';
import { AggConfigs, CreateAggConfigParams } from '../agg_configs';
import { BUCKET_TYPES } from './bucket_agg_types';
import { IBucketAggConfig } from './bucket_agg_type';
import { mockAggTypesRegistry } from '../test_helpers';
const indexPattern = {
id: '1234',
title: 'logstash-*',
fields: [
{
name: 'field',
},
],
} as any;
const singleTerm = {
aggs: [
{
id: '1',
type: BUCKET_TYPES.TERMS,
params: {
field: {
name: 'machine.os.raw',
indexPattern,
filterable: true,
},
otherBucket: true,
missingBucket: true,
},
},
],
};
const nestedTerm = {
aggs: [
{
id: '1',
type: BUCKET_TYPES.TERMS,
params: {
field: {
name: 'geo.src',
indexPattern,
filterable: true,
},
size: 2,
otherBucket: false,
missingBucket: false,
},
},
{
id: '2',
type: BUCKET_TYPES.TERMS,
params: {
field: {
name: 'machine.os.raw',
indexPattern,
filterable: true,
},
size: 2,
otherBucket: true,
missingBucket: true,
},
},
],
};
const singleTermResponse = {
took: 10,
timed_out: false,
_shards: {
total: 1,
successful: 1,
skipped: 0,
failed: 0,
},
hits: {
total: 14005,
max_score: 0,
hits: [],
},
aggregations: {
'1': {
doc_count_error_upper_bound: 0,
sum_other_doc_count: 8325,
buckets: [
{ key: 'ios', doc_count: 2850 },
{ key: 'win xp', doc_count: 2830 },
{ key: '__missing__', doc_count: 1430 },
],
},
},
status: 200,
};
const nestedTermResponse = {
took: 10,
timed_out: false,
_shards: {
total: 1,
successful: 1,
skipped: 0,
failed: 0,
},
hits: {
total: 14005,
max_score: 0,
hits: [],
},
aggregations: {
'1': {
doc_count_error_upper_bound: 0,
sum_other_doc_count: 8325,
buckets: [
{
'2': {
doc_count_error_upper_bound: 0,
sum_other_doc_count: 8325,
buckets: [
{ key: 'ios', doc_count: 2850 },
{ key: 'win xp', doc_count: 2830 },
{ key: '__missing__', doc_count: 1430 },
],
},
key: 'US',
doc_count: 2850,
},
{
'2': {
doc_count_error_upper_bound: 0,
sum_other_doc_count: 8325,
buckets: [
{ key: 'ios', doc_count: 1850 },
{ key: 'win xp', doc_count: 1830 },
{ key: '__missing__', doc_count: 130 },
],
},
key: 'IN',
doc_count: 2830,
},
],
},
},
status: 200,
};
const nestedTermResponseNoResults = {
took: 10,
timed_out: false,
_shards: {
total: 1,
successful: 1,
skipped: 0,
failed: 0,
},
hits: {
total: 0,
max_score: null,
hits: [],
},
aggregations: {
'1': {
doc_count_error_upper_bound: 0,
sum_other_doc_count: 0,
buckets: [],
},
},
status: 200,
};
const singleOtherResponse = {
took: 3,
timed_out: false,
_shards: { total: 1, successful: 1, skipped: 0, failed: 0 },
hits: { total: 14005, max_score: 0, hits: [] },
aggregations: {
'other-filter': {
buckets: { '': { doc_count: 2805 } },
},
},
status: 200,
};
const nestedOtherResponse = {
took: 3,
timed_out: false,
_shards: { total: 1, successful: 1, skipped: 0, failed: 0 },
hits: { total: 14005, max_score: 0, hits: [] },
aggregations: {
'other-filter': {
buckets: { '-US': { doc_count: 2805 }, '-IN': { doc_count: 2804 } },
},
},
status: 200,
};
describe('Terms Agg Other bucket helper', () => {
const typesRegistry = mockAggTypesRegistry();
const getAggConfigs = (aggs: CreateAggConfigParams[] = []) => {
return new AggConfigs(indexPattern, [...aggs], { typesRegistry });
};
describe('buildOtherBucketAgg', () => {
test('returns a function', () => {
const aggConfigs = getAggConfigs(singleTerm.aggs);
const agg = buildOtherBucketAgg(
aggConfigs,
aggConfigs.aggs[0] as IBucketAggConfig,
singleTermResponse
);
expect(typeof agg).toBe('function');
});
test('correctly builds query with single terms agg', () => {
const aggConfigs = getAggConfigs(singleTerm.aggs);
const agg = buildOtherBucketAgg(
aggConfigs,
aggConfigs.aggs[0] as IBucketAggConfig,
singleTermResponse
);
const expectedResponse = {
aggs: undefined,
filters: {
filters: {
'': {
bool: {
must: [],
filter: [{ exists: { field: 'machine.os.raw' } }],
should: [],
must_not: [
{ match_phrase: { 'machine.os.raw': 'ios' } },
{ match_phrase: { 'machine.os.raw': 'win xp' } },
],
},
},
},
},
};
expect(agg).toBeDefined();
if (agg) {
expect(agg()['other-filter']).toEqual(expectedResponse);
}
});
test('correctly builds query for nested terms agg', () => {
const aggConfigs = getAggConfigs(nestedTerm.aggs);
const agg = buildOtherBucketAgg(
aggConfigs,
aggConfigs.aggs[1] as IBucketAggConfig,
nestedTermResponse
);
const expectedResponse = {
'other-filter': {
aggs: undefined,
filters: {
filters: {
'-IN': {
bool: {
must: [],
filter: [
{ match_phrase: { 'geo.src': 'IN' } },
{ exists: { field: 'machine.os.raw' } },
],
should: [],
must_not: [
{ match_phrase: { 'machine.os.raw': 'ios' } },
{ match_phrase: { 'machine.os.raw': 'win xp' } },
],
},
},
'-US': {
bool: {
must: [],
filter: [
{ match_phrase: { 'geo.src': 'US' } },
{ exists: { field: 'machine.os.raw' } },
],
should: [],
must_not: [
{ match_phrase: { 'machine.os.raw': 'ios' } },
{ match_phrase: { 'machine.os.raw': 'win xp' } },
],
},
},
},
},
},
};
expect(agg).toBeDefined();
if (agg) {
expect(agg()).toEqual(expectedResponse);
}
});
test('excludes exists filter for scripted fields', () => {
const aggConfigs = getAggConfigs(nestedTerm.aggs);
aggConfigs.aggs[1].params.field.scripted = true;
const agg = buildOtherBucketAgg(
aggConfigs,
aggConfigs.aggs[1] as IBucketAggConfig,
nestedTermResponse
);
const expectedResponse = {
'other-filter': {
aggs: undefined,
filters: {
filters: {
'-IN': {
bool: {
must: [],
filter: [{ match_phrase: { 'geo.src': 'IN' } }],
should: [],
must_not: [
{
script: {
script: {
lang: undefined,
params: { value: 'ios' },
source: '(undefined) == value',
},
},
},
{
script: {
script: {
lang: undefined,
params: { value: 'win xp' },
source: '(undefined) == value',
},
},
},
],
},
},
'-US': {
bool: {
must: [],
filter: [{ match_phrase: { 'geo.src': 'US' } }],
should: [],
must_not: [
{
script: {
script: {
lang: undefined,
params: { value: 'ios' },
source: '(undefined) == value',
},
},
},
{
script: {
script: {
lang: undefined,
params: { value: 'win xp' },
source: '(undefined) == value',
},
},
},
],
},
},
},
},
},
};
expect(agg).toBeDefined();
if (agg) {
expect(agg()).toEqual(expectedResponse);
}
});
test('returns false when nested terms agg has no buckets', () => {
const aggConfigs = getAggConfigs(nestedTerm.aggs);
const agg = buildOtherBucketAgg(
aggConfigs,
aggConfigs.aggs[1] as IBucketAggConfig,
nestedTermResponseNoResults
);
expect(agg).toEqual(false);
});
});
describe('mergeOtherBucketAggResponse', () => {
test('correctly merges other bucket with single terms agg', () => {
const aggConfigs = getAggConfigs(singleTerm.aggs);
const otherAggConfig = buildOtherBucketAgg(
aggConfigs,
aggConfigs.aggs[0] as IBucketAggConfig,
singleTermResponse
);
expect(otherAggConfig).toBeDefined();
if (otherAggConfig) {
const mergedResponse = mergeOtherBucketAggResponse(
aggConfigs,
singleTermResponse,
singleOtherResponse,
aggConfigs.aggs[0] as IBucketAggConfig,
otherAggConfig()
);
expect(mergedResponse.aggregations['1'].buckets[3].key).toEqual('__other__');
}
});
test('correctly merges other bucket with nested terms agg', () => {
const aggConfigs = getAggConfigs(nestedTerm.aggs);
const otherAggConfig = buildOtherBucketAgg(
aggConfigs,
aggConfigs.aggs[1] as IBucketAggConfig,
nestedTermResponse
);
expect(otherAggConfig).toBeDefined();
if (otherAggConfig) {
const mergedResponse = mergeOtherBucketAggResponse(
aggConfigs,
nestedTermResponse,
nestedOtherResponse,
aggConfigs.aggs[1] as IBucketAggConfig,
otherAggConfig()
);
expect(mergedResponse.aggregations['1'].buckets[1]['2'].buckets[3].key).toEqual(
'__other__'
);
}
});
});
describe('updateMissingBucket', () => {
test('correctly updates missing bucket key', () => {
const aggConfigs = getAggConfigs(nestedTerm.aggs);
const updatedResponse = updateMissingBucket(
singleTermResponse,
aggConfigs,
aggConfigs.aggs[0] as IBucketAggConfig
);
expect(
updatedResponse.aggregations['1'].buckets.find(
(bucket: Record<string, any>) => bucket.key === '__missing__'
)
).toBeDefined();
});
});
}); | the_stack |
import { off as removeEvent, on as addEvent } from 'dom-helpers/events';
import { isFunction } from 'lodash';
import { runnable } from 'toxic-decorators';
import { isMustListenVideoDomEvent, mustListenVideoDomEvents } from '../const/event';
import Bus from '../dispatcher/bus';
import Dispatcher from '../dispatcher/index';
import ChimeeKernel from '../dispatcher/kernel';
import { getEventInfo, isEventEmitalbe, prettifyEventParameter } from '../helper/binder';
import { BinderTarget, EventStage, RawEventInfo } from '../typings/base';
export default class Binder {
private bindedEventInfo: { [key in BinderTarget]: Array<[string, (...args: any[]) => any]> };
private bindedEventNames: { [key in BinderTarget]: string[] };
private buses: { [key in BinderTarget ]: Bus };
private dispatcher: Dispatcher;
private kinds: BinderTarget [];
private pendingEventsInfo: { [key in BinderTarget ]: Array<[string, string]> };
constructor(dispatcher: Dispatcher) {
this.dispatcher = dispatcher;
this.kinds = [
'kernel',
'container',
'wrapper',
'video',
'video-dom',
'plugin',
'esFullscreen',
];
this.buses = ({} as { [key in BinderTarget ]: Bus });
this.bindedEventNames = ({} as { [key in BinderTarget ]: string[] });
this.bindedEventInfo = ({} as { [key in BinderTarget ]: Array<[string, (...args: any[]) => any]> });
this.pendingEventsInfo = ({} as { [key in BinderTarget ]: Array<[string, string]> });
for (const kind of this.kinds) {
this.bindedEventNames[kind] = [];
this.bindedEventInfo[kind] = [];
this.pendingEventsInfo[kind] = [];
this.buses[kind] = new Bus(dispatcher, kind);
}
}
public addPendingEvent(target: BinderTarget , name: string, id: string) {
this.pendingEventsInfo[target].push([ name, id ]);
}
public applyPendingEvents(target: BinderTarget ) {
const pendingEvents = this.pendingEventsInfo[target];
const pendingEventsCopy = pendingEvents.splice(0, pendingEvents.length);
while (pendingEventsCopy.length) {
const [ name, id ] = pendingEventsCopy.pop();
this.addEventListenerOnTarget({ name, target, id });
}
}
// when we create a penetrate plugin, we need to rebind video events on it
public bindEventOnPenetrateNode(node: Element, remove: boolean = false) {
this.bindedEventInfo['video-dom']
.forEach(([ name, fn ]) => {
remove
? removeEvent(node, name, fn)
: addEvent(node, name, fn);
});
}
// when we switch kernel, we will create a new video.
// we need to transfer the event from the oldvideo to it.
public bindEventOnVideo(node: Element, remove: boolean = false) {
this.bindedEventInfo['video-dom']
.concat(this.bindedEventInfo.video)
.forEach(([ name, fn ]) => {
remove
? removeEvent(node, name, fn)
: addEvent(node, name, fn);
});
}
// when we destroy, we remove all binder
public destroy() {
this.kinds.forEach((target) => {
if (target === 'kernel') {
this.bindedEventInfo.kernel.forEach(([ name, fn ]) => {
this.dispatcher.kernel.off(name, fn);
});
} else {
const targetDom = this.getTargetDom(target);
this.bindedEventInfo[target].forEach(([ name, fn ]) => {
removeEvent(targetDom, name, fn);
if (target === 'video-dom') {
this.dispatcher.dom.videoExtendedNodes.forEach((node) => removeEvent(node, name, fn));
}
});
}
this.bindedEventInfo.kernel = [];
this.bindedEventNames.kernel = [];
});
}
@runnable(isEventEmitalbe)
public emit(
{
name,
stage,
target: rawTarget,
}: {
id: string;
name: string;
stage?: EventStage;
target?: BinderTarget | void;
},
...args: any[]) {
const { target } = getEventInfo({ name, target: rawTarget, stage });
return this.buses[target].emit(name, ...args);
}
@runnable(isEventEmitalbe, { backup() { return false; } })
public emitSync(
{
name,
stage,
target: rawTarget,
}: {
id: string;
name: string;
stage?: EventStage;
target?: BinderTarget | void;
},
...args: any[]) {
const { target } = getEventInfo({ name, target: rawTarget, stage });
return this.buses[target].emitSync(name, ...args);
}
// As penetrate plugin is considered to be part of video
// we need to transfer event for it
// so we need some specail event handler
public listenOnMouseMoveEvent(node: Element) {
const dom = this.dispatcher.dom;
const target = 'video-dom';
const id = '_vm';
mustListenVideoDomEvents.forEach((name) => {
const fn = (...args: any[]) => {
const { toElement, currentTarget, relatedTarget, type } = args[0];
const to = toElement || relatedTarget;
// As we support penetrate plugin, the video dom event may be differnet.
if (dom.mouseInVideo && type === 'mouseleave' && !dom.isNodeInsideVideo(to)) {
dom.mouseInVideo = false;
return this.triggerSync({
id,
name,
target,
}, ...args);
}
if (!dom.mouseInVideo && type === 'mouseenter' && dom.isNodeInsideVideo(currentTarget)) {
dom.mouseInVideo = true;
return this.triggerSync({
id,
name,
target,
}, ...args);
}
};
addEvent(node, name, fn);
// this function is only used once now
// so we do not cover this branch
// but we still keep this judegement
/* istanbul ignore else */
if (this.bindedEventNames[target].indexOf(name) < 0) {
this.bindedEventNames[target].push(name);
this.bindedEventInfo[target].push([ name, fn ]);
}
});
}
// When we switch kernel, we need to rebind the events
public migrateKernelEvent(oldKernel: ChimeeKernel, newKernel: ChimeeKernel) {
const bindedEventInfoList = this.bindedEventInfo.kernel;
bindedEventInfoList.forEach(([ name, fn ]) => {
oldKernel.off(name, fn);
newKernel.on(name, fn);
});
}
public off(info: RawEventInfo) {
const { id, name, fn, stage, target } = prettifyEventParameter(info);
const ret = this.buses[target].off(id, name, fn, stage);
this.removeEventListenerOnTargetWhenIsUseless({ name, target });
return ret;
}
public on(info: RawEventInfo) {
const { id, name, fn, stage, target } = prettifyEventParameter(info);
this.addEventListenerOnTarget({
id,
name,
target,
});
return this.buses[target].on(id, name, fn, stage);
}
public once(info: RawEventInfo) {
const { id, name, fn, stage, target } = prettifyEventParameter(info);
return this.buses[target].once(id, name, fn, stage);
}
@runnable(isEventEmitalbe)
public trigger(
{
name,
stage,
target: rawTarget,
}: {
id: string;
name: string;
stage?: EventStage;
target?: BinderTarget | void;
},
...args: any[]) {
const { target } = getEventInfo({ name, target: rawTarget, stage });
return this.buses[target].trigger(name, ...args);
}
@runnable(isEventEmitalbe, { backup() { return false; } })
public triggerSync(
{
name,
stage,
target: rawTarget,
}: {
id: string;
name: string;
stage?: EventStage;
target?: BinderTarget | void;
},
...args: any[]) {
const { target } = getEventInfo({ name, target: rawTarget, stage });
return this.buses[target].triggerSync(name, ...args);
}
// Some event needs us to transfer it from the real target
// such as dom event
private addEventListenerOnTarget({
name,
target,
id,
}: {
id: string,
name: string,
target: BinderTarget ,
}) {
if (!this.isEventNeedToBeHandled(target, name)) { return; }
let fn: (...args: any[]) => any;
// if this event has been binded, return;
if (this.bindedEventNames[target].indexOf(name) > -1) { return; }
const targetDom = this.getTargetDom(target);
// choose the correspond method to bind
if (target === 'kernel') {
if (!this.dispatcher.kernel) {
this.addPendingEvent(target, name, id);
return;
}
fn = (...args) => this.triggerSync({ target, name, id: 'kernel' }, ...args);
this.dispatcher.kernel.on(name, fn);
} else if (target === 'container' || target === 'wrapper') {
fn = (...args) => this.triggerSync({ target, name, id: target }, ...args);
addEvent(targetDom, name, fn);
} else if (target === 'video') {
fn = (...args) => this.trigger({ target, name, id: target }, ...args);
addEvent(targetDom, name, fn);
} else if (target === 'video-dom') {
fn = (...args) => this.triggerSync({ target, name, id: target }, ...args);
this.dispatcher.dom.videoExtendedNodes.forEach((node) => addEvent(node, name, fn));
addEvent(targetDom, name, fn);
}
this.bindedEventNames[target].push(name);
this.bindedEventInfo[target].push([ name, fn ]);
}
private getTargetDom(target: BinderTarget ): Element {
let targetDom;
switch (target) {
case 'container':
case 'wrapper':
targetDom = this.dispatcher.dom[target];
break;
default:
targetDom = this.dispatcher.dom.videoElement;
break;
}
return targetDom;
}
private isEventNeedToBeHandled(target: BinderTarget , name: string): boolean {
// the plugin target do not need us to transfer
// we have listened on esFullscreen in dom
// we have listened mustListenVideoDomEvents
// so the events above do not need to rebind
return target !== 'plugin' &&
target !== 'esFullscreen' &&
(!isMustListenVideoDomEvent(name) || target !== 'video');
}
// when we off one event, we can remove the useless binder
// actually we should remove on once event too
// but it seems ugliy
// TODO: add this function on once event too
private removeEventListenerOnTargetWhenIsUseless({
name,
target,
}: {
name: string,
target: BinderTarget ,
}) {
if (!this.isEventNeedToBeHandled(target, name)) { return; }
const eventNamesList = this.bindedEventNames[target];
const nameIndex = eventNamesList.indexOf(name);
// if we have not bind this event before, we omit it
if (nameIndex < 0) { return; }
// if the buses still have another function on bind, we do not need to remove the binder
if (this.buses[target].hasEvents()) { return; }
// we fetch the binded function from bindedEventInfo
const bindedEventInfoList = this.bindedEventInfo[target];
let fn: (...args: any[]) => any;
let index;
for (index = 0; index < bindedEventInfoList.length; index++) {
if (bindedEventInfoList[index][0] === name) {
fn = bindedEventInfoList[index][1];
break;
}
}
if (!isFunction(fn)) { return; }
if (target === 'kernel') {
this.dispatcher.kernel.off(name, fn);
} else {
const targetDom = this.getTargetDom(target);
removeEvent(targetDom, name, fn);
// When we remove something on video dom, we also need to remove event on penetrate plugin
if (target === 'video-dom') {
this.dispatcher.dom.videoExtendedNodes.forEach((node) => {
removeEvent(node, name, fn);
});
}
}
bindedEventInfoList.splice(index, 1);
eventNamesList.splice(nameIndex, 1);
}
} | the_stack |
import { Component, Input, Output, Pipe, PipeTransform, ViewChild, EventEmitter, OnInit } from '@angular/core';
import { Validators, FormGroup, FormArray, FormBuilder } from '@angular/forms';
import { ModalDirective,ModalOptions} from 'ngx-bootstrap';
import { SnmpDeviceService } from '../snmpdevice/snmpdevicecfg.service';
import { SnmpMetricService } from '../snmpmetric/snmpmetriccfg.service';
import { MeasurementService } from '../measurement/measurementcfg.service';
import { OidConditionService } from '../oidcondition/oidconditioncfg.service';
import { IMultiSelectOption, IMultiSelectSettings, IMultiSelectTexts } from './multiselect-dropdown';
import {SpinnerComponent} from '../common/spinner';
import { Subscription } from "rxjs";
@Component({
selector: 'test-connection-modal',
template: `
<div bsModal #childModal="bs-modal" [config]="{'keyboard' : false, backdrop: 'static'}" class="modal fade" tabindex="-1" role="dialog" arisa-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" style="width: 80%">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" (click)="hide()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" *ngIf="formValues != null">{{titleName}} <b>{{ formValues.ID }}</b></h4>
</div>
<div class="modal-body">
<!--System Info Panel-->
<div class="panel panel-primary" *ngIf = "maximized === false">
<div class="panel-heading">System Info</div>
<my-spinner [isRunning]="isRequesting && !isConnected"></my-spinner>
<div [ngClass]="['panel-body', 'bg-'+alertHandler.type]">
{{alertHandler.msg}}
</div>
</div>
<div class="row" *ngIf="isConnected && maximized === false" >
<!--System Info Panel-->
<div class="col-md-6">
<div class="panel panel-primary">
<div class="panel-heading">Source from OID</div>
<div class="panel-body">
<div class="col-md-2" *ngFor="let selector of selectors; let i=index">
<label class="checkbox-inline">
<input type="radio" class="" (click)="selectOption(selector.option,i)" [checked]="selectedOption === selector.option">{{selector.title}}
</label>
<ss-multiselect-dropdown *ngIf="selectedOption === selector.option && selector.option !== 'Direct'" [options]="selector.Array" [texts]="myTexts" [settings]="mySettings" ngModel (ngModelChange)="selectItem($event,selector.Array,i)"></ss-multiselect-dropdown>
</div>
</div>
</div>
</div>
<form [formGroup]="testForm" class="form-horizontal">
<div class="col-md-6">
<div class="panel panel-primary">
<div class="panel-heading">Connection data</div>
<div class="panel-body">
<div class="col-md-6">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading" style="padding: 0px">History</div>
<ul class="list-group">
<li class="list-group-item" style="padding: 3px" *ngIf="histArray.length === 0"> Empty history</li>
<li class="list-group-item" style="padding: 3px" *ngFor="let hist of histArray">
<div>
<span style="padding: 0px; margin-right: 10px" role=button class="glyphicon glyphicon-plus" (click)="selectedOID = hist"></span>
<span> {{hist}} </span>
</div>
</li>
</ul>
</div>
</div>
<div class="col-md-5">
<!--MODE-->
<div class="form-group">
<label for="Mode" class="col-sm-4 control-label">Mode</label>
<div class="col-sm-8">
<select class="form-control" formControlName="Mode" id="Mode" [(ngModel)]="setMode">
<option *ngFor="let mode of modeGo" >{{mode}}</option>
</select>
</div>
</div>
<!--OID-->
<div class="form-group">
<label for="OID" class="col-sm-4 control-label">OID</label>
<div class="col-sm-8">
<input type="text" class="form-control" placeholder="Text input" [ngModel]="selectedOID" formControlName="OID" id="OID">
</div>
</div>
<button type="button" class="btn btn-primary pull-right" style="margin-top:10px" [disabled]="!testForm.valid" (click)="sendQuery()">Send query</button>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="row">
<div class="col-md-12">
<div *ngIf="!queryResult">
<my-spinner *ngIf="isRequesting && isConnected" [isRunning]="isRequesting"></my-spinner>
</div>
<div *ngIf="queryResult" class="panel panel-default">
<div class="panel-heading">
<h4>
Query OID: {{queryResult.OID}}
<label *ngIf="queryResult.QueryResult.length != 0" [ngClass]="(queryResult.QueryResult[0].Type != 'ERROR' && queryResult.QueryResult[0].Type != 'NoSuchObject' && queryResult.QueryResult[0].Type != 'NoSuchInstance') ? ['label label-primary'] : ['label label-danger']" style="padding-top: 0.5em; margin:0px">
{{queryResult.QueryResult[0].Type != 'ERROR' && queryResult.QueryResult[0].Type != 'NoSuchObject' && queryResult.QueryResult[0].Type != 'NoSuchInstance' ? queryResult.QueryResult.length +' results': '0 results - '+queryResult.QueryResult[0].Type}}
</label>
<label style="padding-top: 0.5em; margin:0px" *ngIf="queryResult.QueryResult.length == 0" class="label label-danger">
0 results
</label>
<span style="margin-left: 15px">
Filter value: <input type=text [(ngModel)]="filter" placeholder="Filter..." (ngModelChange)="onChange($event)">
</span>
<i [ngClass]="maximized ? ['pull-right glyphicon glyphicon-resize-small']: ['pull-right glyphicon glyphicon-resize-full']" style="margin-left: 10px;" (click)="maximizeQueryResults()"></i>
<span class="pull-right"> elapsed: {{queryResult.TimeTaken}} s </span>
</h4>
</div>
<div class="panel-body" [ngStyle]="maximized ? {'max-height' : '100%' } : {'max-height.px' : 300 , 'overflow-y' : 'scroll'}">
<my-spinner *ngIf="isRequesting && isConnected" [isRunning]="isRequesting"></my-spinner>
<table class="table table-hover table-striped table-condensed" style="width:100%" *ngIf="isRequesting === false">
<thead>
<tr>
<th>OID</th>
<th>Type</th>
<th>Value</th>
</tr>
</thead>
<tr *ngFor="let entry of queryResult.QueryResult; let i = index">
<td>{{entry.Name}} </td>
<td> {{entry.Type}}</td>
<td>{{entry.Value}}</td>
</tr>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" (click)="hide()">Close</button>
</div>
</div>
</div>
</div>`,
providers: [SnmpDeviceService, SnmpMetricService, MeasurementService, OidConditionService, SpinnerComponent],
})
export class TestConnectionModal implements OnInit {
@ViewChild('childModal') public childModal: ModalDirective;
//@Input() formValues : any;
@Input() titleName : any;
@Input() systemInfo: any;
@Output() public validationClicked:EventEmitter<any> = new EventEmitter();
public validationClick(myId: string):void {
this.validationClicked.emit(myId);
}
constructor(private builder: FormBuilder, public metricMeasService: SnmpMetricService, public measurementService: MeasurementService, public oidConditionService : OidConditionService,public snmpDeviceService: SnmpDeviceService) {
}
ngOnInit () {
this.testForm = this.builder.group({
Mode: ['get', Validators.required],
OID: ['', Validators.required]
});
}
//ConnectionForm
testForm : any;
setMode : string = 'get';
//History OIDs
histArray : Array<string> = [];
formValues: any;
//Sysinfo
alertHandler : any = {};
isRequesting : boolean ;
isConnected: boolean;
myObservable : Subscription;
//Panel OID source
selectedOption : any = 'OID';
selectedOID : any;
//Selector object:
public selectors : Object = [
{ option : 'Direct', title : 'Direct OID', forceMode : 'get'},
{ option : 'IndexMeas', title : 'Direct Index. Measurements', forceMode : 'walk', Array: []},
{ option : 'IIndexMeas', title : 'Indirect Index. Measurements', forceMode : 'walk', Array: []},
{ option : 'Metric', title : 'Metric Base OID', forceMode : 'get', Array: []},
{ option : 'OIDCond', title : 'OID Conditions', forceMode : 'walk', Array: []}
];
//Panel connection
modeGo : Array<string> = [
'get',
'walk'
];
//Result params
queryResult : any;
maximized : boolean = false;
dataArray : any = [];
filter : any = null;
private mySettings: IMultiSelectSettings = {
singleSelect: true,
};
selectOption(id : string, index : number) {
this.selectedOption = id;
this.setMode = this.selectors[index].forceMode;
switch (id) {
case 'Metric':
this.getMetricsforModal(index);
break;
case 'IndexMeas':
this.getMeasforModal('indexed', index);
break;
case 'IIndexMeas':
this.getMeasforModal('indexed_it', index)
break;
case 'OIDCond':
this.getOidConditionforModal(index);
default: ;
}
;
}
selectItem(selectedItem : string, forceMode : boolean, index: number) : void {
for (let item of this.selectors[index].Array) {
if (item.id === selectedItem) {
this.selectedOID = item.OID;
break;
}
}
}
maximizeQueryResults () {
this.maximized = !this.maximized;
}
show(_formValues) {
//reset var values
this.formValues = _formValues;
this.alertHandler = {};
this.queryResult = null;
this.maximized = false;
this.isConnected = false;
this.isRequesting = true;
this.pingDevice(this.formValues);
this.childModal.show();
}
hide() {
if (this.myObservable) this.myObservable.unsubscribe();
this.childModal.hide();
}
getMetricsforModal(index : number){
this.myObservable = this.metricMeasService.getMetrics(null)
.subscribe(
data => {
this.selectors[index].Array = [];
for (let entry of data) {
this.selectors[index].Array.push({'id' : entry.ID , 'name': entry.ID, 'OID' : entry.BaseOID});
}
},
err => console.error(err),
() => console.log('DONE')
);
}
getMeasforModal(type : string, index : number){
this.myObservable = this.measurementService.getMeasByType(type)
.subscribe(
data => {
this.selectors[index].Array = [];
for (let entry of data) {
if (entry.MultiIndexCfg != null) {
for (let mi of entry.MultiIndexCfg) {
if (mi.GetMode === type) {
this.selectors[index].Array.push({ 'id': entry.ID+".."+mi.Label, 'name': entry.ID+".."+mi.Label, 'OID': mi.IndexOID});
}
}
} else {
this.selectors[index].Array.push({ 'id': entry.ID, 'name': entry.ID, 'OID': entry.IndexOID});
}
}
},
err => console.error(err),
() => console.log('DONE')
);
}
getOidConditionforModal(index : number){
this.myObservable = this.oidConditionService.getConditions(null)
.subscribe(
data => {
this.selectors[index].Array = [];
for (let entry of data) {
if (!entry.IsMultiple) {
this.selectors[index].Array.push({'id' : entry.ID , 'name': entry.ID, 'OID' : entry.OIDCond});
}
}
},
err => console.error(err),
() => console.log('DONE')
);
}
onChange(event){
let tmpArray = this.dataArray.filter((item: any) => {
return item['Value'].toString().match(event);
});
this.queryResult.QueryResult = tmpArray;
}
sendQuery() {
//Clean other request
this.myObservable.unsubscribe();
this.isRequesting = true;
this.filter = null;
this.histArray.push(this.testForm.value.OID);
if (this.histArray.length > 5 ) this.histArray.shift();
this.myObservable = this.snmpDeviceService.sendQuery(this.formValues,this.testForm.value.Mode, this.testForm.value.OID, true)
.subscribe(data => {
this.queryResult = data;
this.dataArray = this.queryResult.QueryResult;
this.queryResult.OID = this.testForm.value.OID;
this.isRequesting = false;
},
err => {
console.error(err);
},
() => {console.log("DONE")}
);
}
//WAIT
pingDevice(formValues){
this.myObservable = this.snmpDeviceService.pingDevice(formValues, true)
.subscribe(data => {
this.alertHandler = {msg: 'Test succesfull '+data['SysDescr'], type: 'success', closable: true};
this.isConnected = true;
this.isRequesting = false
},
err => {
console.error(err);
this.alertHandler = {msg: 'Test failed! '+err['_body'], type: 'danger', closable: true};
this.isConnected = false;
this.isRequesting = false
},
() => {console.log("OK") ;
}
);
}
ngOnDestroy() {
if (this.myObservable) this.myObservable.unsubscribe();
}
} | the_stack |
import * as assert from 'assert';
import {status} from '@grpc/grpc-js';
import * as sinon from 'sinon';
import {describe, it, beforeEach} from 'mocha';
import {BundleDescriptor} from '../../src/bundlingCalls/bundleDescriptor';
import {
BundleExecutor,
BundleOptions,
} from '../../src/bundlingCalls/bundleExecutor';
import {computeBundleId} from '../../src/bundlingCalls/bundlingUtils';
import {deepCopyForResponse, Task} from '../../src/bundlingCalls/task';
import {GoogleError} from '../../src/googleError';
import {createApiCall} from './utils';
import {SimpleCallbackFunction, RequestType} from '../../src/apitypes';
function createOuter(value: {}, otherValue?: {}) {
if (otherValue === undefined) {
otherValue = value;
}
return {inner: {field1: value, field2: otherValue}, field1: value};
}
function byteLength(obj: {}) {
return JSON.stringify(obj).length;
}
describe('computeBundleId', () => {
describe('computes the bundle identifier', () => {
const testCases = [
{
message: 'single field value',
object: {field1: 'dummy_value'},
fields: ['field1'],
want: '["dummy_value"]',
},
{
message: 'composite value with missing field2',
object: {field1: 'dummy_value'},
fields: ['field1', 'field2'],
want: '["dummy_value",null]',
},
{
message: 'a composite value',
object: {field1: 'dummy_value', field2: 'other_value'},
fields: ['field1', 'field2'],
want: '["dummy_value","other_value"]',
},
{
message: 'null',
object: {field1: null},
fields: ['field1'],
want: '[null]',
},
{
message: 'partially nonexisting fields',
object: {field1: 'dummy_value', field2: 'other_value'},
fields: ['field1', 'field3'],
want: '["dummy_value",null]',
},
{
message: 'numeric',
object: {field1: 42},
fields: ['field1'],
want: '[42]',
},
{
message: 'structured data',
object: {field1: {foo: 'bar', baz: 42}},
fields: ['field1'],
want: '[{"foo":"bar","baz":42}]',
},
{
message: 'a simple dotted value',
object: createOuter('this is dotty'),
fields: ['inner.field1'],
want: '["this is dotty"]',
},
{
message: 'a complex case',
object: createOuter('what!?'),
fields: ['inner.field1', 'inner.field2', 'field1'],
want: '["what!?","what!?","what!?"]',
},
];
testCases.forEach(t => {
it(t.message, () => {
assert.strictEqual(
computeBundleId(t.object as unknown as RequestType, t.fields),
t.want
);
});
});
});
describe('returns undefined if failed', () => {
const testCases = [
{
message: 'empty discriminator fields',
object: {field1: 'dummy_value'},
fields: [],
},
{
message: 'nonexisting fields',
object: {field1: 'dummy_value'},
fields: ['field3'],
},
{
message: 'fails to look up in the middle',
object: createOuter('this is dotty'),
fields: ['inner.field3'],
},
];
testCases.forEach(t => {
it(t.message, () => {
assert.strictEqual(computeBundleId(t.object, t.fields), undefined);
});
});
});
});
describe('deepCopyForResponse', () => {
it('copies deeply', () => {
const input = {foo: {bar: [1, 2]}};
const output = deepCopyForResponse(input, null);
assert.deepStrictEqual(output, input);
assert.notStrictEqual(output.foo, input.foo);
assert.notStrictEqual(output.foo.bar, input.foo.bar);
});
it('respects subresponseInfo', () => {
const input = {foo: [1, 2, 3, 4], bar: {foo: [1, 2, 3, 4]}};
const output = deepCopyForResponse(input, {
field: 'foo',
start: 0,
end: 2,
});
assert.deepStrictEqual(output, {foo: [1, 2], bar: {foo: [1, 2, 3, 4]}});
assert.notStrictEqual(output.bar, input.bar);
const output2 = deepCopyForResponse(input, {
field: 'foo',
start: 2,
end: 4,
});
assert.deepStrictEqual(output2, {foo: [3, 4], bar: {foo: [1, 2, 3, 4]}});
assert.notStrictEqual(output2.bar, input.bar);
});
it('deep copies special values', () => {
class Copyable {
constructor(public id: {}) {}
copy() {
return new Copyable(this.id);
}
}
const input = {
copyable: new Copyable(0),
arraybuffer: new ArrayBuffer(10),
nullvalue: null,
array: [1, 2, 3],
number: 1,
boolean: false,
obj: {
foo: 1,
},
};
const output = deepCopyForResponse(input, null);
assert.deepStrictEqual(output, input);
assert.notStrictEqual(output.copyable, input.copyable);
assert.notStrictEqual(output.arraybuffer, input.arraybuffer);
assert.notStrictEqual(output.array, input.array);
});
it('ignores erroneous subresponseInfo', () => {
const input = {foo: 1, bar: {foo: [1, 2, 3, 4]}};
const output = deepCopyForResponse(input, {
field: 'foo',
start: 0,
end: 2,
});
assert.deepStrictEqual(output, input);
});
});
describe('Task', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function testTask(apiCall?: any) {
return new Task(apiCall, {}, 'field1', null);
}
let id = 0;
function extendElements(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
task: any,
elements: string[] | number[],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
callback?: any
) {
if (!callback) {
callback = () => {};
}
callback.id = id++;
let bytes = 0;
elements.forEach((element: string | number) => {
bytes += byteLength(element);
});
task.extend(elements, bytes, callback);
}
describe('extend', () => {
const data = 'a simple msg';
const testCases = [
{
data: [],
message: 'no messages added',
want: 0,
},
{
data: [data],
message: 'a single message added',
want: 1,
},
{
data: [data, data, data, data, data],
message: '5 messages added',
want: 5,
},
];
describe('increases the element count', () => {
testCases.forEach(t => {
it(t.message, () => {
const task = testTask();
const baseCount = task.getElementCount();
extendElements(task, t.data);
assert.strictEqual(
task.getElementCount(),
baseCount! + t.want,
t.message
);
});
});
});
describe('increases the byte size', () => {
const sizePerData = JSON.stringify(data).length;
testCases.forEach(t => {
it(t.message, () => {
const task = testTask();
const baseSize = task.getRequestByteSize();
extendElements(task, t.data);
assert.strictEqual(
task.getRequestByteSize(),
baseSize! + t.want * sizePerData
);
});
});
});
});
describe('run', () => {
const data = 'test message';
const testCases = [
{
data: [],
message: 'no messages added',
expected: null,
},
{
data: [[data]],
message: 'a single message added',
expected: [data],
},
{
data: [
[data, data],
[data, data, data],
],
message: 'a single message added',
expected: [data, data, data, data, data],
},
{
data: [[data, data, data, data, data]],
message: '5 messages added',
expected: [data, data, data, data, data],
},
];
function createApiCall(expected: {}) {
return function apiCall(req: {field1: {}}, callback: Function) {
assert.deepStrictEqual(req.field1, expected);
return callback(null, req);
};
}
describe('sends bundled elements', () => {
testCases.forEach(t => {
it(t.message, done => {
const apiCall = sinon.spy(createApiCall(t.expected!));
const task = testTask(apiCall as unknown as SimpleCallbackFunction);
const callback = sinon.spy((err, data) => {
assert.strictEqual(err, null);
assert(data instanceof Object);
if (callback.callCount === t.data.length) {
assert.strictEqual(apiCall.callCount, 1);
done();
}
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(t as any).data.forEach((d: string[]) => {
extendElements(task!, d, callback);
});
task!.run();
if (t.expected === null) {
assert.strictEqual(callback.callCount, 0);
assert.strictEqual(apiCall.callCount, 0);
done();
}
});
});
});
describe('calls back with the subresponse fields', () => {
testCases.forEach(t => {
it(t.message, done => {
const apiCall = sinon.spy(createApiCall(t.expected!));
const task = testTask(apiCall as unknown as SimpleCallbackFunction);
task!._subresponseField = 'field1';
let callbackCount = 0;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(t as any).data.forEach((d: string[]) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
extendElements(task!, d, (err: any, data: {field1: []}) => {
assert.strictEqual(err, null);
assert.strictEqual(data.field1.length, d.length);
callbackCount++;
if (callbackCount === t.data.length) {
assert.strictEqual(apiCall.callCount, 1);
done();
}
});
});
task!.run();
if (t.expected === null) {
assert.strictEqual(callbackCount, 0);
assert.strictEqual(apiCall.callCount, 0);
done();
}
});
});
});
describe('calls back with fail if API fails', () => {
testCases.slice(1).forEach(t => {
it(t.message, done => {
const err = new Error('failure');
const apiCall = sinon.spy((resp, callback) => {
callback(err);
});
const task = testTask(apiCall as unknown as SimpleCallbackFunction);
task!._subresponseField = 'field1';
const callback = sinon.spy((e, data) => {
assert.strictEqual(e, err);
assert.strictEqual(data, undefined);
if (callback.callCount === t.data.length) {
assert.strictEqual(apiCall.callCount, 1);
done();
}
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(t as any).data.forEach((d: string[]) => {
extendElements(task!, d, callback);
});
task!.run();
});
});
});
});
it('cancels existing data', done => {
const apiCall = sinon.spy((resp, callback) => {
callback(null, resp);
});
const task = testTask(apiCall as unknown as SimpleCallbackFunction);
task!._subresponseField = 'field1';
const callback = sinon.spy(() => {
if (callback.callCount === 2) {
done();
}
});
extendElements(task!, [1, 2, 3], (err: {}, resp: {field1: number[]}) => {
assert.deepStrictEqual(resp.field1, [1, 2, 3]);
callback();
});
extendElements(task!, [4, 5, 6], (err: GoogleError) => {
assert(err instanceof GoogleError);
assert.strictEqual(err!.code, status.CANCELLED);
});
const cancelId = task!._data[task!._data.length - 1].callback.id;
extendElements(task!, [7, 8, 9], (err: {}, resp: {field1: number[]}) => {
assert.deepStrictEqual(resp.field1, [7, 8, 9]);
callback();
});
task!.cancel(cancelId!);
task!.run();
});
it('cancels ongoing API call', done => {
const apiCall = sinon.spy((resp, callback) => {
const timeoutId = setTimeout(() => {
callback(null, resp);
}, 100);
return {
cancel() {
clearTimeout(timeoutId);
callback(new Error('cancelled'));
},
};
});
const task = testTask(apiCall);
const callback = sinon.spy(() => {
if (callback.callCount === 2) {
done();
}
});
extendElements(task, [1, 2, 3], (err: GoogleError) => {
assert(err instanceof GoogleError);
assert.strictEqual(err!.code, status.CANCELLED);
callback();
});
extendElements(task, [1, 2, 3], (err: GoogleError) => {
assert(err instanceof GoogleError);
assert.strictEqual(err!.code, status.CANCELLED);
callback();
});
task.run();
task._data.forEach(data => {
task.cancel(data.callback.id!);
});
});
it('partially cancels ongoing API call', done => {
const apiCall = sinon.spy((resp, callback) => {
const timeoutId = setTimeout(() => {
callback(null, resp);
}, 100);
return {
cancel: () => {
clearTimeout(timeoutId);
callback(new Error('cancelled'));
},
};
});
const task = testTask(apiCall);
task._subresponseField = 'field1';
const callback = sinon.spy(() => {
if (callback.callCount === 2) {
done();
}
});
extendElements(task, [1, 2, 3], (err: GoogleError) => {
assert(err instanceof GoogleError);
assert.strictEqual(err!.code, status.CANCELLED);
callback();
});
const cancelId = task._data[task._data.length - 1].callback.id;
extendElements(task, [4, 5, 6], (err: {}, resp: {field1: number[]}) => {
assert.deepStrictEqual(resp.field1, [4, 5, 6]);
callback();
});
task.run();
task.cancel(cancelId!);
});
});
describe('Executor', () => {
function apiCall(request: {}, callback: Function) {
callback(null, request);
return {cancel: () => {}};
}
function failing(request: {}, callback: Function) {
callback(new Error('failure'));
return {cancel: () => {}};
}
function newExecutor(options: BundleOptions) {
const descriptor = new BundleDescriptor(
'field1',
['field2'],
'field1',
byteLength
);
return new BundleExecutor(options, descriptor);
}
it('groups api calls by the id', () => {
const executor = newExecutor({delayThreshold: 10});
executor.schedule(apiCall, {field1: [1, 2], field2: 'id1'});
executor.schedule(apiCall, {field1: [3], field2: 'id2'});
executor.schedule(apiCall, {field1: [4, 5], field2: 'id1'});
executor.schedule(apiCall, {field1: [6], field2: 'id2'});
assert(executor._tasks.hasOwnProperty('["id1"]'));
assert(executor._tasks.hasOwnProperty('["id2"]'));
assert.strictEqual(Object.keys(executor._tasks).length, 2);
let task = executor._tasks['["id1"]'];
assert.strictEqual(task._data.length, 2);
assert.deepStrictEqual(task._data[0].elements, [1, 2]);
assert.deepStrictEqual(task._data[1].elements, [4, 5]);
task = executor._tasks['["id2"]'];
assert.strictEqual(task._data.length, 2);
assert.deepStrictEqual(task._data[0].elements, [3]);
assert.deepStrictEqual(task._data[1].elements, [6]);
for (const bundleId in executor._timers) {
clearTimeout(executor._timers[bundleId]);
}
});
it('emits errors when the api call fails', done => {
const executor = newExecutor({delayThreshold: 10});
const callback = sinon.spy(err => {
assert(err instanceof Error);
if (callback.callCount === 2) {
done();
}
});
executor.schedule(failing, {field1: [1], field2: 'id'}, callback);
executor.schedule(failing, {field1: [2], field2: 'id'}, callback);
});
it('runs unbundleable tasks immediately', done => {
const executor = newExecutor({delayThreshold: 10});
const spy = sinon.spy(apiCall);
let counter = 0;
let unbundledCallCounter = 0;
function onEnd() {
assert.strictEqual(spy.callCount, 3);
done();
}
executor.schedule(spy, {field1: [1, 2], field2: 'id1'}, (err, resp) => {
// @ts-ignore unknown field
assert.deepStrictEqual(resp.field1, [1, 2]);
assert.strictEqual(unbundledCallCounter, 2);
counter++;
if (counter === 4) {
onEnd();
}
});
executor.schedule(spy, {field1: [3]}, (err, resp) => {
// @ts-ignore unknown field
assert.deepStrictEqual(resp.field1, [3]);
unbundledCallCounter++;
counter++;
});
executor.schedule(spy, {field1: [4], field2: 'id1'}, (err, resp) => {
// @ts-ignore unknown field
assert.deepStrictEqual(resp.field1, [4]);
assert.strictEqual(unbundledCallCounter, 2);
counter++;
if (counter === 4) {
onEnd();
}
});
executor.schedule(spy, {field1: [5, 6]}, (err, resp) => {
// @ts-ignore unknown field
assert.deepStrictEqual(resp.field1, [5, 6]);
unbundledCallCounter++;
counter++;
});
});
describe('callback', () => {
const executor = newExecutor({delayThreshold: 10});
let spyApi = sinon.spy(apiCall);
function timedAPI(request: {}, callback: Function) {
let canceled = false;
// This invokes callback asynchronously by using setTimeout with 0msec, so
// the callback invocation can be canceled in the same event loop of this
// API is called.
setTimeout(() => {
if (!canceled) {
callback(null, request);
}
}, 0);
return () => {
canceled = true;
callback(new Error('canceled'));
};
}
beforeEach(() => {
spyApi = sinon.spy(apiCall);
});
it("shouldn't block next event after cancellation", done => {
const canceller = executor.schedule(
spyApi,
{field1: [1, 2], field2: 'id'},
err => {
assert(err instanceof GoogleError);
assert.strictEqual(err!.code, status.CANCELLED);
assert.strictEqual(spyApi.callCount, 0);
executor.schedule(
spyApi,
{field1: [3, 4], field2: 'id'},
(err, resp) => {
// @ts-ignore unknown field
assert.deepStrictEqual(resp.field1, [3, 4]);
assert.strictEqual(spyApi.callCount, 1);
done();
}
);
}
);
assert.strictEqual(spyApi.callCount, 0);
canceller.cancel();
});
it('distinguishes a running task and a scheduled one', done => {
let counter = 0;
// @ts-ignore cancellation logic is broken here
executor.schedule(timedAPI, {field1: [1, 2], field2: 'id'}, err => {
assert.strictEqual(err, null);
counter++;
// counter should be 2 because event2 callback should be called
// earlier (it should be called immediately on cancel).
assert.strictEqual(counter, 2);
done();
});
executor._runNow('id');
const canceller =
// @ts-ignore cancellation logic is broken here
executor.schedule(timedAPI, {field1: [1, 2], field2: 'id'}, err => {
assert(err instanceof GoogleError);
assert.strictEqual(err!.code, status.CANCELLED);
counter++;
});
canceller.cancel();
});
});
it('respects element count', () => {
const threshold = 5;
const executor = newExecutor({elementCountThreshold: threshold});
const spy = sinon.spy((request, callback) => {
assert.strictEqual(request.field1.length, threshold);
callback(null, request);
return {cancel: () => {}};
});
for (let i = 0; i < threshold - 1; ++i) {
executor.schedule(spy, {field1: [1], field2: 'id1'});
executor.schedule(spy, {field1: [2], field2: 'id2'});
}
assert.strictEqual(spy.callCount, 0);
executor.schedule(spy, {field1: [1], field2: 'id1'});
assert.strictEqual(spy.callCount, 1);
executor.schedule(spy, {field1: [2], field2: 'id2'});
assert.strictEqual(spy.callCount, 2);
assert.strictEqual(Object.keys(executor._tasks).length, 0);
});
it('respects bytes count', () => {
const unitSize = byteLength(1);
const count = 5;
const threshold = unitSize * count;
const executor = newExecutor({requestByteThreshold: threshold});
const spy = sinon.spy((request, callback) => {
assert.strictEqual(request.field1.length, count);
assert(byteLength(request.field1) >= threshold);
callback(null, request);
return {cancel: () => {}};
});
for (let i = 0; i < count - 1; ++i) {
executor.schedule(spy, {field1: [1], field2: 'id1'});
executor.schedule(spy, {field1: [2], field2: 'id2'});
}
assert.strictEqual(spy.callCount, 0);
executor.schedule(spy, {field1: [1], field2: 'id1'});
assert.strictEqual(spy.callCount, 1);
executor.schedule(spy, {field1: [2], field2: 'id2'});
assert.strictEqual(spy.callCount, 2);
assert.strictEqual(Object.keys(executor._tasks).length, 0);
});
it('respects element limit', done => {
const threshold = 5;
const limit = 7;
const executor = newExecutor({
elementCountThreshold: threshold,
elementCountLimit: limit,
});
const spy = sinon.spy((request, callback) => {
assert(Array.isArray(request.field1));
callback(null, request);
return {cancel: () => {}};
});
executor.schedule(spy, {field1: [1, 2], field2: 'id'});
executor.schedule(spy, {field1: [3, 4], field2: 'id'});
assert.strictEqual(spy.callCount, 0);
assert.strictEqual(Object.keys(executor._tasks).length, 1);
executor.schedule(spy, {field1: [5, 6, 7], field2: 'id'});
assert.strictEqual(spy.callCount, 1);
assert.strictEqual(Object.keys(executor._tasks).length, 1);
executor.schedule(spy, {field1: [8, 9, 10, 11, 12], field2: 'id'});
assert.strictEqual(spy.callCount, 3);
assert.strictEqual(Object.keys(executor._tasks).length, 0);
executor.schedule(
spy,
{field1: [1, 2, 3, 4, 5, 6, 7, 8], field2: 'id'},
err => {
assert(err instanceof GoogleError);
assert.strictEqual(err!.code, status.INVALID_ARGUMENT);
done();
}
);
});
it('respects bytes limit', done => {
const unitSize = byteLength(1);
const threshold = 5;
const limit = 7;
const executor = newExecutor({
requestByteThreshold: threshold * unitSize,
requestByteLimit: limit * unitSize,
});
const spy = sinon.spy((request, callback) => {
assert(Array.isArray(request.field1));
callback(null, request);
return {cancel: () => {}};
});
executor.schedule(spy, {field1: [1, 2], field2: 'id'});
executor.schedule(spy, {field1: [3, 4], field2: 'id'});
assert.strictEqual(spy.callCount, 0);
assert.strictEqual(Object.keys(executor._tasks).length, 1);
executor.schedule(spy, {field1: [5, 6, 7], field2: 'id'});
assert.strictEqual(spy.callCount, 1);
assert.strictEqual(Object.keys(executor._tasks).length, 1);
executor.schedule(spy, {field1: [8, 9, 0, 1, 2], field2: 'id'});
assert.strictEqual(spy.callCount, 3);
assert.strictEqual(Object.keys(executor._tasks).length, 0);
executor.schedule(
spy,
{field1: [1, 2, 3, 4, 5, 6, 7], field2: 'id'},
err => {
assert(err instanceof GoogleError);
assert.strictEqual(err!.code, status.INVALID_ARGUMENT);
done();
}
);
});
it('does not invoke runNow twice', done => {
const threshold = 2;
const executor = newExecutor({
elementCountThreshold: threshold,
delayThreshold: 10,
});
executor._runNow = sinon.spy(executor._runNow.bind(executor));
const spy = sinon.spy((request, callback) => {
assert.strictEqual(request.field1.length, threshold);
callback(null, request);
return {cancel: () => {}};
});
executor.schedule(spy, {field1: [1, 2], field2: 'id1'});
setTimeout(() => {
assert.strictEqual(spy.callCount, 1);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assert.strictEqual((executor._runNow as any).callCount, 1);
done();
}, 20);
});
describe('timer', () => {
it('waits on the timer', done => {
const executor = newExecutor({delayThreshold: 50});
const spy = sinon.spy(apiCall);
const start = new Date().getTime();
function onEnd() {
assert.strictEqual(spy.callCount, 1);
const now = new Date().getTime();
assert(now - start >= 49);
done();
}
const tasks = 5;
const callback = sinon.spy(() => {
if (callback.callCount === tasks) {
onEnd();
}
});
for (let i = 0; i < tasks; i++) {
executor.schedule(spy, {field1: [i], field2: 'id'}, callback);
}
});
it('reschedules after timer', done => {
const executor = newExecutor({delayThreshold: 50});
const spy = sinon.spy(apiCall);
const start = new Date().getTime();
executor.schedule(spy, {field1: [0], field2: 'id'}, () => {
assert.strictEqual(spy.callCount, 1);
const firstEnded = new Date().getTime();
assert(firstEnded - start >= 49);
executor.schedule(spy, {field1: [1], field2: 'id'}, () => {
assert.strictEqual(spy.callCount, 2);
const secondEnded = new Date().getTime();
assert(secondEnded - firstEnded >= 49);
done();
});
});
});
});
});
describe('bundleable', () => {
function func(argument: {}, metadata: {}, options: {}, callback: Function) {
callback(null, argument);
}
const bundleOptions = {elementCountThreshold: 12, delayThreshold: 10};
const descriptor = new BundleDescriptor(
'field1',
['field2'],
'field1',
byteLength
);
const settings = {
settings: {bundleOptions},
descriptor,
};
it('bundles requests', done => {
const spy = sinon.spy(func);
const callback = sinon.spy(obj => {
assert(Array.isArray(obj));
assert.deepStrictEqual(obj[0].field1, [1, 2, 3]);
if (callback.callCount === 2) {
assert.strictEqual(spy.callCount, 1);
done();
}
});
const apiCall = createApiCall(spy, settings);
apiCall({field1: [1, 2, 3], field2: 'id'}, undefined, (err, obj) => {
if (err) {
done(err);
} else {
callback([obj]);
}
});
apiCall({field1: [1, 2, 3], field2: 'id'}, undefined)
.then(callback)
.catch(done);
});
it('does not fail if bundle field is not set', done => {
const spy = sinon.spy(func);
const warnStub = sinon.stub(process, 'emitWarning');
const callback = sinon.spy(obj => {
assert(Array.isArray(obj));
assert.strictEqual(obj[0].field1, undefined);
if (callback.callCount === 2) {
assert.strictEqual(spy.callCount, 2);
assert.strictEqual(warnStub.callCount, 1);
warnStub.restore();
done();
}
});
const apiCall = createApiCall(spy, settings);
function error(err: Error) {
warnStub.restore();
done(err);
}
apiCall({field2: 'id1'}, undefined).then(callback, error);
apiCall({field2: 'id2'}, undefined).then(callback, error);
});
it('suppresses bundling behavior by call options', done => {
const spy = sinon.spy(func);
let callbackCount = 0;
function bundledCallback(obj: Array<{field1: number[]}>) {
assert(Array.isArray(obj));
callbackCount++;
assert.deepStrictEqual(obj[0].field1, [1, 2, 3]);
if (callbackCount === 3) {
assert.strictEqual(spy.callCount, 2);
done();
}
}
function unbundledCallback(obj: Array<{field1: number[]}>) {
assert(Array.isArray(obj));
callbackCount++;
assert.strictEqual(callbackCount, 1);
assert.deepStrictEqual(obj[0].field1, [1, 2, 3]);
}
const apiCall = createApiCall(spy, settings);
apiCall({field1: [1, 2, 3], field2: 'id'}, undefined)
//@ts-ignore
.then(bundledCallback)
.catch(done);
apiCall({field1: [1, 2, 3], field2: 'id'}, {isBundling: false})
//@ts-ignore
.then(unbundledCallback)
.catch(done);
apiCall({field1: [1, 2, 3], field2: 'id'}, undefined)
//@ts-ignore
.then(bundledCallback)
.catch(done);
});
it('cancels partially on bundling method', done => {
const apiCall = createApiCall(func, settings);
let expectedSuccess = false;
let expectedFailure = false;
apiCall({field1: [1, 2, 3], field2: 'id'}, undefined)
.then(obj => {
assert(Array.isArray(obj));
// @ts-ignore response type
assert.deepStrictEqual(obj[0].field1, [1, 2, 3]);
expectedSuccess = true;
if (expectedSuccess && expectedFailure) {
done();
}
})
.catch(done);
const p = apiCall({field1: [1, 2, 3], field2: 'id'}, undefined);
p.then(() => {
done(new Error('should not succeed'));
}).catch(err => {
assert(err instanceof GoogleError);
assert.strictEqual(err!.code, status.CANCELLED);
expectedFailure = true;
if (expectedSuccess && expectedFailure) {
done();
}
});
p.cancel();
});
it('properly processes camel case fields', done => {
const descriptor = new BundleDescriptor(
'data',
['log_name'],
'data',
byteLength
);
const settings = {
settings: {bundleOptions},
descriptor,
};
const spy = sinon.spy(func);
const callback = sinon.spy(() => {
if (callback.callCount === 4) {
assert.strictEqual(spy.callCount, 2); // we expect two requests, each has two items
done();
}
});
const apiCall = createApiCall(spy, settings);
apiCall({data: ['data1'], logName: 'log1'}, undefined, err => {
if (err) {
done(err);
} else {
callback();
}
});
apiCall({data: ['data1'], logName: 'log2'}, undefined, err => {
if (err) {
done(err);
} else {
callback();
}
});
apiCall({data: ['data2'], logName: 'log1'}, undefined, err => {
if (err) {
done(err);
} else {
callback();
}
});
apiCall({data: ['data2'], logName: 'log2'}, undefined, err => {
if (err) {
done(err);
} else {
callback();
}
});
});
}); | the_stack |
import bluebird from 'bluebird'
import _ from 'lodash'
import { nanoid } from 'nanoid'
import { createQueryBuilder, getRepository, In } from 'typeorm'
import { Block } from '../core/block'
import { SmartQueryBlock } from '../core/block/smartQuery'
import { getLinksFromSql, LinkWithStoryId, loadLinkEntitiesByBlockIds } from '../core/link'
import { getIPermission, IPermission } from '../core/permission'
import { translateSmartQuery } from '../core/translator/smartQuery'
import BlockEntity from '../entities/block'
import { BlockDTO, BlockParentType, BlockType, ExportedBlock } from '../types/block'
import { OperationCmdType, OperationTableType } from '../types/operation'
import { defaultPermissions } from '../types/permission'
import { QueryBuilderSpec } from '../types/queryBuilder'
import { isLinkToken, Token } from '../types/token'
import { canGetBlockData, canGetWorkspaceData } from '../utils/permission'
import { OperationService } from './operation'
export class BlockService {
private permission: IPermission
constructor(p: IPermission) {
this.permission = p
}
/**
* get all blocks of a story which in story's children and parent block's children
*/
async listAccessibleBlocksByStoryId(
operatorId: string,
workspaceId: string,
storyId: string,
): Promise<Block[]> {
await canGetBlockData(this.permission, operatorId, workspaceId, storyId)
const blockEntities = await this.listEntitiesByStoryId(storyId)
const blocks = _(blockEntities)
.map((b) => Block.fromEntity(b))
.map((b) => {
if (!b.alive) {
this.overrideContent(b)
}
return b
})
.filter((b1) => {
if (b1.parentTable === BlockParentType.WORKSPACE) {
return true
}
const parentBlock = _(blockEntities).find((b2) => b1.parentId === b2.id)
return (parentBlock?.children ?? []).includes(b1.id)
})
.value()
// Getting external blocks
// Since external block ids will be only in the children of the story, we can only examine the story block
// if such a property is generalized to all blocks, we have to do a recursive cte query
const story = _(blockEntities).find((i) => i.parentTable === BlockParentType.WORKSPACE)
if (story) {
const externalBlockIds = _(story.children ?? [])
.difference(_(blocks).map('id').value())
.value()
const externalBlockEntities = await getRepository(BlockEntity).find({
id: In(externalBlockIds),
})
const externalBlocks = _(externalBlockEntities)
.map((b) => Block.fromEntity(b))
.value()
return [...blocks, ...externalBlocks]
}
return blocks
}
async mget(operatorId: string, workspaceId: string, ids: string[]): Promise<BlockDTO[]> {
await canGetWorkspaceData(this.permission, operatorId, workspaceId)
const models = await getRepository(BlockEntity).find({ id: In(ids) })
const dtos = await bluebird.map(models, async (model) => {
const can = await this.permission.canGetBlockData(operatorId, model)
const dto = Block.fromEntitySafely(model)?.toDTO()
if (dto) {
if (!can) {
// unset content, format and children
this.overrideContent(dto)
// unset permissions
dto.permissions = []
}
}
return dto
})
return _(dtos).compact().value()
}
listEntitiesByStoryId(storyId: string, alive?: boolean): Promise<BlockEntity[]> {
return getRepository(BlockEntity).find(_({ storyId, alive }).omitBy(_.isUndefined).value())
}
async mgetLinks(
operatorId: string,
workspaceId: string,
ids: string[],
): Promise<
{ blockId: string; forwardRefs: LinkWithStoryId[]; backwardRefs: LinkWithStoryId[] }[]
> {
await canGetWorkspaceData(this.permission, operatorId, workspaceId)
// to ensure that the following constructed sql is well-formed
if (ids.length === 0) {
return []
}
const models = await loadLinkEntitiesByBlockIds(ids)
// ignore models without permissions
const filters = await bluebird.filter(models, async (m) => {
const [source, target] = await Promise.all(
_([m.sourceBlock, m.targetBlock])
.map((b) =>
canGetBlockData(this.permission, operatorId, workspaceId, b)
.then(() => true)
.catch(() => false),
)
.value(),
)
return source && target
})
return _(ids)
.map((id) => ({
blockId: id,
forwardRefs: _(filters)
.filter((m) => m.sourceBlockId === id)
.map((m) => ({
storyId: m.targetBlock.storyId,
blockId: m.targetBlock.id,
type: m.type,
}))
.value(),
backwardRefs: _(filters)
.filter((m) => m.targetBlockId === id)
.map((m) => ({
storyId: m.sourceBlock.storyId,
blockId: m.sourceBlock.id,
type: m.type,
}))
.value(),
}))
.value()
}
/* eslint-disable no-param-reassign */
private overrideContent(block: Block | BlockDTO) {
block.content = {}
block.format = undefined
block.children = []
}
/* eslint-enable no-param-reassign */
/**
* Downgrade a query builder to regular SQL query
* searching for its downstream smartQuery, and translate them to SQL query, then change their type
* TODO: use a cache to replace getting queryBuilderSpec from the connector
* operationService is exposed for testing
*/
async downgradeQueryBuilder(
operatorId: string,
workspaceId: string,
queryBuilderId: string,
queryBuilderSpec: QueryBuilderSpec,
operationService: OperationService,
): Promise<void> {
await canGetWorkspaceData(this.permission, operatorId, workspaceId)
const downstreamSmartQueries = _(
await createQueryBuilder(BlockEntity, 'blocks')
.where('type = :type', { type: BlockType.SMART_QUERY })
.andWhere("content ->> 'queryBuilderId' = :id", { id: queryBuilderId })
.andWhere('alive = true')
.getMany(),
)
.map((b) => Block.fromEntity(b) as SmartQueryBlock)
.value()
const translatedSmartQueries = await bluebird.map(
downstreamSmartQueries,
async (b) => {
const content = b.getContent()
const sql = await translateSmartQuery(content, queryBuilderSpec)
return [b.id, { ...content, sql }] as [string, Record<string, unknown>]
},
{ concurrency: 10 },
)
const opBuilder = (id: string, path: string, args: any) => ({
cmd: OperationCmdType.SET,
id,
path: [path],
table: OperationTableType.BLOCK,
args,
})
const ops = [
_(translatedSmartQueries)
.map(([id, content]) => opBuilder(id, 'content', content))
.value(),
_(translatedSmartQueries)
// take the first
.map(0)
.concat([queryBuilderId])
.map((id) => opBuilder(id, 'type', BlockType.SQL))
.value(),
]
const failures = await operationService.saveTransactions(
operatorId,
_(ops)
.map((operations) => ({
id: nanoid(),
workspaceId,
operations,
}))
.value(),
{ skipPermissionCheck: true },
)
if (!_.isEmpty(failures)) {
throw failures[0].error
}
}
async exportStories(
operatorId: string,
workspaceId: string,
storyIds: string[],
): Promise<ExportedBlock[]> {
const allBlocks = await bluebird.map(
storyIds,
async (id) => this.listAccessibleBlocksByStoryId(operatorId, workspaceId, id),
{ concurrency: 10 },
)
return _(allBlocks)
.flatMap((bs) =>
bs.map((b) => {
return _.pick(b.toDTO(), [
'id',
'type',
'parentId',
'parentTable',
'storyId',
'content',
'format',
'children',
])
}),
)
.value()
}
async importStories(
operatorId: string,
workspaceId: string,
blocks: ExportedBlock[],
): Promise<string[]> {
const idMap = new Map(blocks.map((it) => [it.id, nanoid()]))
const importedBlockDTOs = blocks.map((b) =>
this.explodeExportedBlock(operatorId, workspaceId, b, idMap),
)
const entities = _(importedBlockDTOs)
.map((b) => Block.fromArgs(b).toModel(workspaceId))
.value()
await getRepository(BlockEntity).save(entities)
return _(entities).map('id').value()
}
handleContent(content: any, idMap: Map<string, string>) {
// check title first
if (content.title) {
_.range(content.title.length).forEach((index) => {
const token = content.title[index] as Token
if (isLinkToken(token)) {
content.title[index][1][0][2] = idMap.get(token[1][0][2])!
}
})
}
if (content.sql) {
const links = getLinksFromSql(content.sql)
content.sql = _(links)
.map('blockId')
.reduce(
(acc, val) => acc.replace(new RegExp(val, 'g'), idMap.get(val)!),
content.sql as string,
)
}
return content
}
explodeExportedBlock(
operatorId: string,
workspaceId: string,
body: ExportedBlock,
idMap: Map<string, string>,
): BlockDTO {
const newDate = Date.now()
const {
id: oldId,
type,
parentId: oldParentId,
storyId: oldStoryId,
parentTable,
content: oldContent,
format,
children: oldChildren,
} = body
return {
id: idMap.get(oldId)!,
type,
parentId: parentTable === BlockParentType.WORKSPACE ? workspaceId : idMap.get(oldParentId)!,
parentTable,
storyId: idMap.get(oldStoryId)!,
permissions: defaultPermissions,
content: this.handleContent(oldContent, idMap),
format,
children: (oldChildren ?? []).map((i) => idMap.get(i)!),
alive: true,
version: 1,
createdById: operatorId,
lastEditedById: operatorId,
createdAt: newDate,
updatedAt: newDate,
}
}
}
const service = new BlockService(getIPermission())
export default service | the_stack |
import type { Rule } from "eslint"
import type {
ArrowFunctionExpression,
CallExpression,
Expression,
FunctionExpression,
Literal,
MemberExpression,
Pattern,
RestElement,
} from "estree"
import type { ReadonlyFlags } from "regexp-ast-analysis"
import type { KnownMethodCall, PropertyReference } from "./ast-utils"
import {
getParent,
parseReplacements,
getStaticValue,
extractPropertyReferences,
extractExpressionReferences,
isKnownMethodCall,
} from "./ast-utils"
import { extractPropertyReferencesForPattern } from "./ast-utils/extract-property-references"
import { parseReplacementsForString } from "./replacements-utils"
import type { TypeTracker } from "./type-tracker"
export type UnknownUsage = {
type: "UnknownUsage"
node: Expression
on?: "replace" | "replaceAll" | "matchAll"
}
export type WithoutRef = {
type: "WithoutRef"
node: Expression
on:
| "search"
| "test"
| "match"
| "replace"
| "replaceAll"
| "matchAll"
| "exec"
}
export type ArrayRef =
| {
type: "ArrayRef"
kind: "index"
ref: number | null /* null for unknown index access. */
prop: PropertyReference & { type: "member" | "destructuring" }
}
| {
type: "ArrayRef"
kind: "name"
ref: string
prop: PropertyReference & { type: "member" | "destructuring" }
}
| {
type: "ArrayRef"
kind: "name"
ref: null /* null for unknown name access. */
prop: PropertyReference & { type: "unknown" | "iteration" }
}
export type ReplacementRef =
| {
type: "ReplacementRef"
kind: "index"
ref: number
range?: [number, number]
}
| {
type: "ReplacementRef"
kind: "name"
ref: string
range?: [number, number]
}
export type ReplacerFunctionRef =
| {
type: "ReplacerFunctionRef"
kind: "index"
ref: number
arg: Pattern
}
| {
type: "ReplacerFunctionRef"
kind: "name"
ref: string
prop: PropertyReference & { type: "member" | "destructuring" }
}
| {
type: "ReplacerFunctionRef"
kind: "name"
ref: null /* null for unknown name access. */
prop: PropertyReference & { type: "unknown" | "iteration" }
arg: null
}
| {
type: "ReplacerFunctionRef"
kind: "name"
ref: null /* null for unknown name access. */
prop: null
arg: Pattern
}
| {
type: "ReplacerFunctionRef"
kind: "unknown"
ref: null /* null for unknown access. */
arg: Pattern
}
export type Split = {
type: "Split"
node: CallExpression
}
export type UnknownRef =
| {
type: "UnknownRef"
kind: "array"
prop: PropertyReference & { type: "unknown" | "iteration" }
}
| {
type: "UnknownRef"
kind: "replacerFunction"
arg: RestElement
}
export type CapturingGroupReference =
| ArrayRef
| ReplacementRef
| ReplacerFunctionRef
| UnknownRef
| WithoutRef
| Split
| UnknownUsage
type ExtractCapturingGroupReferencesContext = {
flags: ReadonlyFlags
countOfCapturingGroup: number
context: Rule.RuleContext
isString: (node: Expression) => boolean
}
/**
* Extracts the usage of the capturing group.
*/
export function* extractCapturingGroupReferences(
node: Expression,
flags: ReadonlyFlags,
typeTracer: TypeTracker,
countOfCapturingGroup: number,
context: Rule.RuleContext,
options: {
strictTypes: boolean
},
): Iterable<CapturingGroupReference> {
const ctx: ExtractCapturingGroupReferencesContext = {
flags,
countOfCapturingGroup,
context,
isString: options.strictTypes
? (n) => typeTracer.isString(n)
: (n) => typeTracer.maybeString(n),
}
for (const ref of extractExpressionReferences(node, context)) {
if (ref.type === "argument") {
yield* iterateForArgument(ref.callExpression, ref.node, ctx)
} else if (ref.type === "member") {
yield* iterateForMember(ref.memberExpression, ref.node, ctx)
} else {
yield {
type: "UnknownUsage",
node: ref.node,
}
}
}
}
/** Iterate the capturing group references for given argument expression node. */
function* iterateForArgument(
callExpression: CallExpression,
argument: Expression,
ctx: ExtractCapturingGroupReferencesContext,
): Iterable<CapturingGroupReference> {
if (
!isKnownMethodCall(callExpression, {
match: 1,
search: 1,
replace: 2,
replaceAll: 2,
matchAll: 1,
split: 1,
})
) {
return
}
if (callExpression.arguments[0] !== argument) {
return
}
if (!ctx.isString(callExpression.callee.object)) {
yield {
type: "UnknownUsage",
node: argument,
}
return
}
if (callExpression.callee.property.name === "match") {
yield* iterateForStringMatch(callExpression, argument, ctx)
} else if (callExpression.callee.property.name === "search") {
yield {
type: "WithoutRef",
node: argument,
on: "search",
}
} else if (
callExpression.callee.property.name === "replace" ||
callExpression.callee.property.name === "replaceAll"
) {
yield* iterateForStringReplace(
callExpression,
argument,
ctx,
callExpression.callee.property.name,
)
} else if (callExpression.callee.property.name === "matchAll") {
yield* iterateForStringMatchAll(callExpression, argument, ctx)
} else if (callExpression.callee.property.name === "split") {
yield {
type: "Split",
node: callExpression,
}
}
}
/** Iterate the capturing group references for given member expression node. */
function* iterateForMember(
memberExpression: MemberExpression,
object: Expression,
ctx: ExtractCapturingGroupReferencesContext,
): Iterable<CapturingGroupReference> {
const parent = getParent(memberExpression)
if (
!parent ||
parent.type !== "CallExpression" ||
parent.callee !== memberExpression ||
!isKnownMethodCall(parent, {
test: 1,
exec: 1,
})
) {
return
}
if (parent.callee.property.name === "test") {
yield {
type: "WithoutRef",
node: object,
on: "test",
}
} else if (parent.callee.property.name === "exec") {
yield* iterateForRegExpExec(parent, object, ctx)
}
}
/** Iterate the capturing group references for String.prototype.match(). */
function* iterateForStringMatch(
node: KnownMethodCall,
argument: Expression,
ctx: ExtractCapturingGroupReferencesContext,
): Iterable<CapturingGroupReference> {
if (ctx.flags.global) {
// String.prototype.match() with g flag
yield {
type: "WithoutRef",
node: argument,
on: "match",
}
} else {
// String.prototype.match() without g flag
let useRet = false
for (const ref of iterateForExecResult(node, ctx)) {
useRet = true
yield ref
}
if (!useRet) {
yield {
type: "WithoutRef",
node: argument,
on: "match",
}
}
}
}
/** Iterate the capturing group references for String.prototype.replace() and String.prototype.replaceAll(). */
function* iterateForStringReplace(
node: KnownMethodCall,
argument: Expression,
ctx: ExtractCapturingGroupReferencesContext,
on: "replace" | "replaceAll",
): Iterable<CapturingGroupReference> {
const replacementNode = node.arguments[1]
if (
replacementNode.type === "FunctionExpression" ||
replacementNode.type === "ArrowFunctionExpression"
) {
// replacer function
yield* iterateForReplacerFunction(replacementNode, argument, on, ctx)
} else {
const replacement = node.arguments[1]
if (!replacement) {
yield {
type: "UnknownUsage",
node: argument,
on,
}
return
}
if (replacement.type === "Literal") {
yield* verifyForReplaceReplacementLiteral(
replacement,
argument,
on,
ctx,
)
} else {
const evaluated = getStaticValue(ctx.context, replacement)
if (!evaluated || typeof evaluated.value !== "string") {
yield {
type: "UnknownUsage",
node: argument,
on,
}
return
}
yield* verifyForReplaceReplacement(evaluated.value, argument, on)
}
}
}
/** Iterate the capturing group references for String.prototype.matchAll(). */
function* iterateForStringMatchAll(
node: KnownMethodCall,
argument: Expression,
ctx: ExtractCapturingGroupReferencesContext,
): Iterable<CapturingGroupReference> {
let useRet = false
for (const iterationRef of extractPropertyReferences(node, ctx.context)) {
if (!iterationRef.extractPropertyReferences) {
useRet = true
yield {
type: "UnknownUsage",
node: argument,
on: "matchAll",
}
return
}
if (hasNameRef(iterationRef)) {
if (Number.isNaN(Number(iterationRef.name))) {
// Not aimed to iteration.
continue
}
}
for (const ref of iterationRef.extractPropertyReferences()) {
if (hasNameRef(ref)) {
if (ref.name === "groups") {
for (const namedRef of ref.extractPropertyReferences()) {
useRet = true
yield getNamedArrayRef(namedRef)
}
} else {
if (
ref.name === "input" ||
ref.name === "index" ||
ref.name === "indices"
) {
continue
}
useRet = true
yield getIndexArrayRef(ref)
}
} else {
useRet = true
yield {
type: "UnknownRef",
kind: "array",
prop: ref,
}
return
}
}
}
if (!useRet) {
yield {
type: "WithoutRef",
node: argument,
on: "matchAll",
}
}
}
/** Iterate the capturing group references for RegExp.prototype.exec() . */
function* iterateForRegExpExec(
node: KnownMethodCall,
object: Expression,
ctx: ExtractCapturingGroupReferencesContext,
): Iterable<CapturingGroupReference> {
let useRet = false
for (const ref of iterateForExecResult(node, ctx)) {
useRet = true
yield ref
}
if (!useRet) {
yield {
type: "WithoutRef",
node: object,
on: "exec",
}
}
}
/** Iterate the capturing group references for RegExp.prototype.exec() and String.prototype.match() result */
function* iterateForExecResult(
node: KnownMethodCall,
ctx: ExtractCapturingGroupReferencesContext,
): Iterable<CapturingGroupReference> {
for (const ref of extractPropertyReferences(node, ctx.context)) {
if (hasNameRef(ref)) {
if (ref.name === "groups") {
for (const namedRef of ref.extractPropertyReferences()) {
yield getNamedArrayRef(namedRef)
}
} else {
if (
ref.name === "input" ||
ref.name === "index" ||
ref.name === "indices"
) {
continue
}
yield getIndexArrayRef(ref)
}
} else {
yield {
type: "UnknownRef",
kind: "array",
prop: ref,
}
return
}
}
}
/** Iterate the capturing group references for String.prototype.replace(regexp, "str") and String.prototype.replaceAll(regexp, "str") */
function* verifyForReplaceReplacementLiteral(
substr: Literal,
argument: Expression,
on: "replace" | "replaceAll",
ctx: ExtractCapturingGroupReferencesContext,
): Iterable<CapturingGroupReference> {
let useReplacement = false
for (const replacement of parseReplacements(ctx.context, substr)) {
if (replacement.type === "ReferenceElement") {
useReplacement = true
if (typeof replacement.ref === "number") {
yield {
type: "ReplacementRef",
kind: "index",
ref: replacement.ref,
range: replacement.range,
}
} else {
yield {
type: "ReplacementRef",
kind: "name",
ref: replacement.ref,
range: replacement.range,
}
}
}
}
if (!useReplacement) {
yield {
type: "WithoutRef",
node: argument,
on,
}
}
}
/** Iterate the capturing group references for String.prototype.replace(regexp, str) and String.prototype.replaceAll(regexp, str) */
function* verifyForReplaceReplacement(
substr: string,
argument: Expression,
on: "replace" | "replaceAll",
): Iterable<CapturingGroupReference> {
let useReplacement = false
for (const replacement of parseReplacementsForString(substr)) {
if (replacement.type === "ReferenceElement") {
useReplacement = true
if (typeof replacement.ref === "number") {
yield {
type: "ReplacementRef",
kind: "index",
ref: replacement.ref,
}
} else {
yield {
type: "ReplacementRef",
kind: "name",
ref: replacement.ref,
}
}
}
}
if (!useReplacement) {
yield {
type: "WithoutRef",
node: argument,
on,
}
}
}
/** Iterate the capturing group references for String.prototype.replace(regexp, fn) and String.prototype.replaceAll(regexp, fn) */
function* iterateForReplacerFunction(
replacementNode: FunctionExpression | ArrowFunctionExpression,
argument: Expression,
on: "replace" | "replaceAll",
ctx: ExtractCapturingGroupReferencesContext,
): Iterable<CapturingGroupReference> {
if (
replacementNode.params.length < 2 &&
!replacementNode.params.some((arg) => arg.type === "RestElement")
) {
yield {
type: "WithoutRef",
node: argument,
on,
}
return
}
for (let index = 0; index < replacementNode.params.length; index++) {
const arg = replacementNode.params[index]
if (arg.type === "RestElement") {
yield {
type: "UnknownRef",
kind: "replacerFunction",
arg,
}
return
}
if (index === 0) {
continue
} else if (index <= ctx.countOfCapturingGroup) {
yield {
type: "ReplacerFunctionRef",
kind: "index",
ref: index,
arg,
}
} else if (ctx.countOfCapturingGroup + 3 === index) {
if (arg.type === "Identifier" || arg.type === "ObjectPattern") {
for (const ref of extractPropertyReferencesForPattern(
arg,
ctx.context,
)) {
if (hasNameRef(ref)) {
yield {
type: "ReplacerFunctionRef",
kind: "name",
ref: ref.name,
prop: ref,
}
} else {
yield {
type: "ReplacerFunctionRef",
kind: "name",
ref: null,
prop: ref,
arg: null,
}
}
}
} else {
yield {
type: "ReplacerFunctionRef",
kind: "name",
ref: null,
arg,
prop: null,
}
}
}
}
}
/** Checks whether the given reference is a named reference. */
function hasNameRef(
ref: PropertyReference,
): ref is PropertyReference & { type: "member" | "destructuring" } {
return ref.type === "destructuring" || ref.type === "member"
}
/** Get the index array ref from PropertyReference */
function getIndexArrayRef(
ref: PropertyReference & { type: "member" | "destructuring" },
): CapturingGroupReference {
const numRef = Number(ref.name)
if (Number.isFinite(numRef)) {
return {
type: "ArrayRef",
kind: "index",
ref: numRef,
prop: ref,
}
}
return {
type: "ArrayRef",
kind: "index",
ref: null,
prop: ref,
}
}
/** Get the named array ref from PropertyReference */
function getNamedArrayRef(
namedRef: PropertyReference,
): CapturingGroupReference {
if (hasNameRef(namedRef)) {
return {
type: "ArrayRef",
kind: "name",
ref: namedRef.name,
prop: namedRef,
}
}
// unknown used as name
return {
type: "ArrayRef",
kind: "name",
ref: null,
prop: namedRef,
}
} | the_stack |
import * as crypto from 'crypto';
import * as os from 'os';
import * as path from 'path';
import * as cxapi from '@aws-cdk/cx-api';
import { Construct } from 'constructs';
import * as fs from 'fs-extra';
import * as minimatch from 'minimatch';
import { AssetHashType, AssetOptions, FileAssetPackaging } from './assets';
import { BundlingOptions, BundlingOutput } from './bundling';
import { FileSystem, FingerprintOptions } from './fs';
import { Names } from './names';
import { Cache } from './private/cache';
import { Stack } from './stack';
import { Stage } from './stage';
// v2 - keep this import as a separate section to reduce merge conflict when forward merging with the v2 branch.
// eslint-disable-next-line
import { Construct as CoreConstruct } from './construct-compat';
const ARCHIVE_EXTENSIONS = ['.zip', '.jar'];
/**
* A previously staged asset
*/
interface StagedAsset {
/**
* The path where we wrote this asset previously
*/
readonly stagedPath: string;
/**
* The hash we used previously
*/
readonly assetHash: string;
/**
* The packaging of the asset
*/
readonly packaging: FileAssetPackaging,
/**
* Whether this asset is an archive
*/
readonly isArchive: boolean;
}
/**
* Initialization properties for `AssetStaging`.
*/
export interface AssetStagingProps extends FingerprintOptions, AssetOptions {
/**
* The source file or directory to copy from.
*/
readonly sourcePath: string;
}
/**
* Stages a file or directory from a location on the file system into a staging
* directory.
*
* This is controlled by the context key 'aws:cdk:asset-staging' and enabled
* by the CLI by default in order to ensure that when the CDK app exists, all
* assets are available for deployment. Otherwise, if an app references assets
* in temporary locations, those will not be available when it exists (see
* https://github.com/aws/aws-cdk/issues/1716).
*
* The `stagedPath` property is a stringified token that represents the location
* of the file or directory after staging. It will be resolved only during the
* "prepare" stage and may be either the original path or the staged path
* depending on the context setting.
*
* The file/directory are staged based on their content hash (fingerprint). This
* means that only if content was changed, copy will happen.
*/
export class AssetStaging extends CoreConstruct {
/**
* The directory inside the bundling container into which the asset sources will be mounted.
*/
public static readonly BUNDLING_INPUT_DIR = '/asset-input';
/**
* The directory inside the bundling container into which the bundled output should be written.
*/
public static readonly BUNDLING_OUTPUT_DIR = '/asset-output';
/**
* Clears the asset hash cache
*/
public static clearAssetHashCache() {
this.assetCache.clear();
}
/**
* Cache of asset hashes based on asset configuration to avoid repeated file
* system and bundling operations.
*/
private static assetCache = new Cache<StagedAsset>();
/**
* Absolute path to the asset data.
*
* If asset staging is disabled, this will just be the source path or
* a temporary directory used for bundling.
*
* If asset staging is enabled it will be the staged path.
*
* IMPORTANT: If you are going to call `addFileAsset()`, use
* `relativeStagedPath()` instead.
*
* @deprecated - Use `absoluteStagedPath` instead.
*/
public readonly stagedPath: string;
/**
* Absolute path to the asset data.
*
* If asset staging is disabled, this will just be the source path or
* a temporary directory used for bundling.
*
* If asset staging is enabled it will be the staged path.
*
* IMPORTANT: If you are going to call `addFileAsset()`, use
* `relativeStagedPath()` instead.
*/
public readonly absoluteStagedPath: string;
/**
* The absolute path of the asset as it was referenced by the user.
*/
public readonly sourcePath: string;
/**
* A cryptographic hash of the asset.
*/
public readonly assetHash: string;
/**
* How this asset should be packaged.
*/
public readonly packaging: FileAssetPackaging;
/**
* Whether this asset is an archive (zip or jar).
*/
public readonly isArchive: boolean;
private readonly fingerprintOptions: FingerprintOptions;
private readonly hashType: AssetHashType;
private readonly assetOutdir: string;
/**
* A custom source fingerprint given by the user
*
* Will not be used literally, always hashed later on.
*/
private customSourceFingerprint?: string;
private readonly cacheKey: string;
private readonly sourceStats: fs.Stats;
constructor(scope: Construct, id: string, props: AssetStagingProps) {
super(scope, id);
this.sourcePath = path.resolve(props.sourcePath);
this.fingerprintOptions = props;
if (!fs.existsSync(this.sourcePath)) {
throw new Error(`Cannot find asset at ${this.sourcePath}`);
}
this.sourceStats = fs.statSync(this.sourcePath);
const outdir = Stage.of(this)?.assetOutdir;
if (!outdir) {
throw new Error('unable to determine cloud assembly asset output directory. Assets must be defined indirectly within a "Stage" or an "App" scope');
}
this.assetOutdir = outdir;
// Determine the hash type based on the props as props.assetHashType is
// optional from a caller perspective.
this.customSourceFingerprint = props.assetHash;
this.hashType = determineHashType(props.assetHashType, this.customSourceFingerprint);
// Decide what we're going to do, without actually doing it yet
let stageThisAsset: () => StagedAsset;
let skip = false;
if (props.bundling) {
// Check if we actually have to bundle for this stack
const bundlingStacks: string[] = this.node.tryGetContext(cxapi.BUNDLING_STACKS) ?? ['*'];
// bundlingStacks is of the form `Stage/Stack`, convert it to `Stage-Stack` before comparing to stack name
skip = !bundlingStacks.find(pattern => minimatch(Stack.of(this).stackName, pattern.replace('/', '-')));
const bundling = props.bundling;
stageThisAsset = () => this.stageByBundling(bundling, skip);
} else {
stageThisAsset = () => this.stageByCopying();
}
// Calculate a cache key from the props. This way we can check if we already
// staged this asset and reuse the result (e.g. the same asset with the same
// configuration is used in multiple stacks). In this case we can completely
// skip file system and bundling operations.
//
// The output directory and whether this asset is skipped or not should also be
// part of the cache key to make sure we don't accidentally return the wrong
// staged asset from the cache.
this.cacheKey = calculateCacheKey({
outdir: this.assetOutdir,
sourcePath: path.resolve(props.sourcePath),
bundling: props.bundling,
assetHashType: this.hashType,
customFingerprint: this.customSourceFingerprint,
extraHash: props.extraHash,
exclude: props.exclude,
ignoreMode: props.ignoreMode,
skip,
});
const staged = AssetStaging.assetCache.obtain(this.cacheKey, stageThisAsset);
this.stagedPath = staged.stagedPath;
this.absoluteStagedPath = staged.stagedPath;
this.assetHash = staged.assetHash;
this.packaging = staged.packaging;
this.isArchive = staged.isArchive;
}
/**
* A cryptographic hash of the asset.
*
* @deprecated see `assetHash`.
*/
public get sourceHash(): string {
return this.assetHash;
}
/**
* Return the path to the staged asset, relative to the Cloud Assembly (manifest) directory of the given stack
*
* Only returns a relative path if the asset was staged, returns an absolute path if
* it was not staged.
*
* A bundled asset might end up in the outDir and still not count as
* "staged"; if asset staging is disabled we're technically expected to
* reference source directories, but we don't have a source directory for the
* bundled outputs (as the bundle output is written to a temporary
* directory). Nevertheless, we will still return an absolute path.
*
* A non-obvious directory layout may look like this:
*
* ```
* CLOUD ASSEMBLY ROOT
* +-- asset.12345abcdef/
* +-- assembly-Stage
* +-- MyStack.template.json
* +-- MyStack.assets.json <- will contain { "path": "../asset.12345abcdef" }
* ```
*/
public relativeStagedPath(stack: Stack) {
const asmManifestDir = Stage.of(stack)?.outdir;
if (!asmManifestDir) { return this.stagedPath; }
const isOutsideAssetDir = path.relative(this.assetOutdir, this.stagedPath).startsWith('..');
if (isOutsideAssetDir || this.stagingDisabled) {
return this.stagedPath;
}
return path.relative(asmManifestDir, this.stagedPath);
}
/**
* Stage the source to the target by copying
*
* Optionally skip if staging is disabled, in which case we pretend we did something but we don't really.
*/
private stageByCopying(): StagedAsset {
const assetHash = this.calculateHash(this.hashType);
const stagedPath = this.stagingDisabled
? this.sourcePath
: path.resolve(this.assetOutdir, renderAssetFilename(assetHash, path.extname(this.sourcePath)));
if (!this.sourceStats.isDirectory() && !this.sourceStats.isFile()) {
throw new Error(`Asset ${this.sourcePath} is expected to be either a directory or a regular file`);
}
this.stageAsset(this.sourcePath, stagedPath, 'copy');
return {
assetHash,
stagedPath,
packaging: this.sourceStats.isDirectory() ? FileAssetPackaging.ZIP_DIRECTORY : FileAssetPackaging.FILE,
isArchive: this.sourceStats.isDirectory() || ARCHIVE_EXTENSIONS.includes(path.extname(this.sourcePath).toLowerCase()),
};
}
/**
* Stage the source to the target by bundling
*
* Optionally skip, in which case we pretend we did something but we don't really.
*/
private stageByBundling(bundling: BundlingOptions, skip: boolean): StagedAsset {
if (!this.sourceStats.isDirectory()) {
throw new Error(`Asset ${this.sourcePath} is expected to be a directory when bundling`);
}
if (skip) {
// We should have bundled, but didn't to save time. Still pretend to have a hash.
// If the asset uses OUTPUT or BUNDLE, we use a CUSTOM hash to avoid fingerprinting
// a potentially very large source directory. Other hash types are kept the same.
let hashType = this.hashType;
if (hashType === AssetHashType.OUTPUT || hashType === AssetHashType.BUNDLE) {
this.customSourceFingerprint = Names.uniqueId(this);
hashType = AssetHashType.CUSTOM;
}
return {
assetHash: this.calculateHash(hashType, bundling),
stagedPath: this.sourcePath,
packaging: FileAssetPackaging.ZIP_DIRECTORY,
isArchive: true,
};
}
// Try to calculate assetHash beforehand (if we can)
let assetHash = this.hashType === AssetHashType.SOURCE || this.hashType === AssetHashType.CUSTOM
? this.calculateHash(this.hashType, bundling)
: undefined;
const bundleDir = this.determineBundleDir(this.assetOutdir, assetHash);
this.bundle(bundling, bundleDir);
// Check bundling output content and determine if we will need to archive
const bundlingOutputType = bundling.outputType ?? BundlingOutput.AUTO_DISCOVER;
const bundledAsset = determineBundledAsset(bundleDir, bundlingOutputType);
// Calculate assetHash afterwards if we still must
assetHash = assetHash ?? this.calculateHash(this.hashType, bundling, bundledAsset.path);
const stagedPath = path.resolve(this.assetOutdir, renderAssetFilename(assetHash, bundledAsset.extension));
this.stageAsset(bundledAsset.path, stagedPath, 'move');
// If bundling produced a single archive file we "touch" this file in the bundling
// directory after it has been moved to the staging directory. This way if bundling
// is skipped because the bundling directory already exists we can still determine
// the correct packaging type.
if (bundledAsset.packaging === FileAssetPackaging.FILE) {
fs.closeSync(fs.openSync(bundledAsset.path, 'w'));
}
return {
assetHash,
stagedPath,
packaging: bundledAsset.packaging,
isArchive: true, // bundling always produces an archive
};
}
/**
* Whether staging has been disabled
*/
private get stagingDisabled() {
return !!this.node.tryGetContext(cxapi.DISABLE_ASSET_STAGING_CONTEXT);
}
/**
* Copies or moves the files from sourcePath to targetPath.
*
* Moving implies the source directory is temporary and can be trashed.
*
* Will not do anything if source and target are the same.
*/
private stageAsset(sourcePath: string, targetPath: string, style: 'move' | 'copy') {
// Is the work already done?
const isAlreadyStaged = fs.existsSync(targetPath);
if (isAlreadyStaged) {
if (style === 'move' && sourcePath !== targetPath) {
fs.removeSync(sourcePath);
}
return;
}
// Moving can be done quickly
if (style == 'move') {
fs.renameSync(sourcePath, targetPath);
return;
}
// Copy file/directory to staging directory
if (this.sourceStats.isFile()) {
fs.copyFileSync(sourcePath, targetPath);
} else if (this.sourceStats.isDirectory()) {
fs.mkdirSync(targetPath);
FileSystem.copyDirectory(sourcePath, targetPath, this.fingerprintOptions);
} else {
throw new Error(`Unknown file type: ${sourcePath}`);
}
}
/**
* Determine the directory where we're going to write the bundling output
*
* This is the target directory where we're going to write the staged output
* files if we can (if the hash is fully known), or a temporary directory
* otherwise.
*/
private determineBundleDir(outdir: string, sourceHash?: string) {
if (sourceHash) {
return path.resolve(outdir, renderAssetFilename(sourceHash));
}
// When the asset hash isn't known in advance, bundler outputs to an
// intermediate directory named after the asset's cache key
return path.resolve(outdir, `bundling-temp-${this.cacheKey}`);
}
/**
* Bundles an asset to the given directory
*
* If the given directory already exists, assume that everything's already
* in order and don't do anything.
*
* @param options Bundling options
* @param bundleDir Where to create the bundle directory
* @returns The fully resolved bundle output directory.
*/
private bundle(options: BundlingOptions, bundleDir: string) {
if (fs.existsSync(bundleDir)) { return; }
fs.ensureDirSync(bundleDir);
// Chmod the bundleDir to full access.
fs.chmodSync(bundleDir, 0o777);
// Always mount input and output dir
const volumes = [
{
hostPath: this.sourcePath,
containerPath: AssetStaging.BUNDLING_INPUT_DIR,
},
{
hostPath: bundleDir,
containerPath: AssetStaging.BUNDLING_OUTPUT_DIR,
},
...options.volumes ?? [],
];
let localBundling: boolean | undefined;
try {
process.stderr.write(`Bundling asset ${this.node.path}...\n`);
localBundling = options.local?.tryBundle(bundleDir, options);
if (!localBundling) {
let user: string;
if (options.user) {
user = options.user;
} else { // Default to current user
const userInfo = os.userInfo();
user = userInfo.uid !== -1 // uid is -1 on Windows
? `${userInfo.uid}:${userInfo.gid}`
: '1000:1000';
}
options.image.run({
command: options.command,
user,
volumes,
environment: options.environment,
workingDirectory: options.workingDirectory ?? AssetStaging.BUNDLING_INPUT_DIR,
securityOpt: options.securityOpt ?? '',
});
}
} catch (err) {
// When bundling fails, keep the bundle output for diagnosability, but
// rename it out of the way so that the next run doesn't assume it has a
// valid bundleDir.
const bundleErrorDir = bundleDir + '-error';
if (fs.existsSync(bundleErrorDir)) {
// Remove the last bundleErrorDir.
fs.removeSync(bundleErrorDir);
}
fs.renameSync(bundleDir, bundleErrorDir);
throw new Error(`Failed to bundle asset ${this.node.path}, bundle output is located at ${bundleErrorDir}: ${err}`);
}
if (FileSystem.isEmpty(bundleDir)) {
const outputDir = localBundling ? bundleDir : AssetStaging.BUNDLING_OUTPUT_DIR;
throw new Error(`Bundling did not produce any output. Check that content is written to ${outputDir}.`);
}
}
private calculateHash(hashType: AssetHashType, bundling?: BundlingOptions, outputDir?: string): string {
// When bundling a CUSTOM or SOURCE asset hash type, we want the hash to include
// the bundling configuration. We handle CUSTOM and bundled SOURCE hash types
// as a special case to preserve existing user asset hashes in all other cases.
if (hashType == AssetHashType.CUSTOM || (hashType == AssetHashType.SOURCE && bundling)) {
const hash = crypto.createHash('sha256');
// if asset hash is provided by user, use it, otherwise fingerprint the source.
hash.update(this.customSourceFingerprint ?? FileSystem.fingerprint(this.sourcePath, this.fingerprintOptions));
// If we're bundling an asset, include the bundling configuration in the hash
if (bundling) {
hash.update(JSON.stringify(bundling));
}
return hash.digest('hex');
}
switch (hashType) {
case AssetHashType.SOURCE:
return FileSystem.fingerprint(this.sourcePath, this.fingerprintOptions);
case AssetHashType.BUNDLE:
case AssetHashType.OUTPUT:
if (!outputDir) {
throw new Error(`Cannot use \`${hashType}\` hash type when \`bundling\` is not specified.`);
}
return FileSystem.fingerprint(outputDir, this.fingerprintOptions);
default:
throw new Error('Unknown asset hash type.');
}
}
}
function renderAssetFilename(assetHash: string, extension = '') {
return `asset.${assetHash}${extension}`;
}
/**
* Determines the hash type from user-given prop values.
*
* @param assetHashType Asset hash type construct prop
* @param customSourceFingerprint Asset hash seed given in the construct props
*/
function determineHashType(assetHashType?: AssetHashType, customSourceFingerprint?: string) {
const hashType = customSourceFingerprint
? (assetHashType ?? AssetHashType.CUSTOM)
: (assetHashType ?? AssetHashType.SOURCE);
if (customSourceFingerprint && hashType !== AssetHashType.CUSTOM) {
throw new Error(`Cannot specify \`${assetHashType}\` for \`assetHashType\` when \`assetHash\` is specified. Use \`CUSTOM\` or leave \`undefined\`.`);
}
if (hashType === AssetHashType.CUSTOM && !customSourceFingerprint) {
throw new Error('`assetHash` must be specified when `assetHashType` is set to `AssetHashType.CUSTOM`.');
}
return hashType;
}
/**
* Calculates a cache key from the props. Normalize by sorting keys.
*/
function calculateCacheKey<A extends object>(props: A): string {
return crypto.createHash('sha256')
.update(JSON.stringify(sortObject(props)))
.digest('hex');
}
/**
* Recursively sort object keys
*/
function sortObject(object: { [key: string]: any }): { [key: string]: any } {
if (typeof object !== 'object' || object instanceof Array) {
return object;
}
const ret: { [key: string]: any } = {};
for (const key of Object.keys(object).sort()) {
ret[key] = sortObject(object[key]);
}
return ret;
}
/**
* Returns the single archive file of a directory or undefined
*/
function singleArchiveFile(directory: string): string | undefined {
if (!fs.existsSync(directory)) {
throw new Error(`Directory ${directory} does not exist.`);
}
if (!fs.statSync(directory).isDirectory()) {
throw new Error(`${directory} is not a directory.`);
}
const content = fs.readdirSync(directory);
if (content.length === 1) {
const file = path.join(directory, content[0]);
const extension = path.extname(content[0]).toLowerCase();
if (fs.statSync(file).isFile() && ARCHIVE_EXTENSIONS.includes(extension)) {
return file;
}
}
return undefined;
}
interface BundledAsset {
path: string,
packaging: FileAssetPackaging,
extension?: string
}
/**
* Returns the bundled asset to use based on the content of the bundle directory
* and the type of output.
*/
function determineBundledAsset(bundleDir: string, outputType: BundlingOutput): BundledAsset {
const archiveFile = singleArchiveFile(bundleDir);
// auto-discover means that if there is an archive file, we take it as the
// bundle, otherwise, we will archive here.
if (outputType === BundlingOutput.AUTO_DISCOVER) {
outputType = archiveFile ? BundlingOutput.ARCHIVED : BundlingOutput.NOT_ARCHIVED;
}
switch (outputType) {
case BundlingOutput.NOT_ARCHIVED:
return { path: bundleDir, packaging: FileAssetPackaging.ZIP_DIRECTORY };
case BundlingOutput.ARCHIVED:
if (!archiveFile) {
throw new Error('Bundling output directory is expected to include only a single .zip or .jar file when `output` is set to `ARCHIVED`');
}
return { path: archiveFile, packaging: FileAssetPackaging.FILE, extension: path.extname(archiveFile) };
}
} | the_stack |
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types";
import {
CreateApplicationCommand,
CreateApplicationCommandInput,
CreateApplicationCommandOutput,
} from "./commands/CreateApplicationCommand";
import {
DeleteApplicationCommand,
DeleteApplicationCommandInput,
DeleteApplicationCommandOutput,
} from "./commands/DeleteApplicationCommand";
import {
DescribeApplicationCommand,
DescribeApplicationCommandInput,
DescribeApplicationCommandOutput,
} from "./commands/DescribeApplicationCommand";
import {
ListApplicationsCommand,
ListApplicationsCommandInput,
ListApplicationsCommandOutput,
} from "./commands/ListApplicationsCommand";
import {
ListTagsForResourceCommand,
ListTagsForResourceCommandInput,
ListTagsForResourceCommandOutput,
} from "./commands/ListTagsForResourceCommand";
import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand";
import {
UntagResourceCommand,
UntagResourceCommandInput,
UntagResourceCommandOutput,
} from "./commands/UntagResourceCommand";
import {
UpdateApplicationCommand,
UpdateApplicationCommandInput,
UpdateApplicationCommandOutput,
} from "./commands/UpdateApplicationCommand";
import { IoTFleetHubClient } from "./IoTFleetHubClient";
/**
* <p>With Fleet Hub for AWS IoT Device Management you can build stand-alone web applications for monitoring the health of your device fleets.</p>
* <note>
* <p>Fleet Hub for AWS IoT Device Management is in public preview and is subject to change.</p>
* </note>
*/
export class IoTFleetHub extends IoTFleetHubClient {
/**
* <p>Creates a Fleet Hub for AWS IoT Device Management web application.</p>
* <note>
* <p>Fleet Hub for AWS IoT Device Management is in public preview and is subject to change.</p>
* </note>
*/
public createApplication(
args: CreateApplicationCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateApplicationCommandOutput>;
public createApplication(
args: CreateApplicationCommandInput,
cb: (err: any, data?: CreateApplicationCommandOutput) => void
): void;
public createApplication(
args: CreateApplicationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateApplicationCommandOutput) => void
): void;
public createApplication(
args: CreateApplicationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateApplicationCommandOutput) => void),
cb?: (err: any, data?: CreateApplicationCommandOutput) => void
): Promise<CreateApplicationCommandOutput> | void {
const command = new CreateApplicationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes a Fleet Hub for AWS IoT Device Management web application.</p>
* <note>
* <p>Fleet Hub for AWS IoT Device Management is in public preview and is subject to change.</p>
* </note>
*/
public deleteApplication(
args: DeleteApplicationCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteApplicationCommandOutput>;
public deleteApplication(
args: DeleteApplicationCommandInput,
cb: (err: any, data?: DeleteApplicationCommandOutput) => void
): void;
public deleteApplication(
args: DeleteApplicationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteApplicationCommandOutput) => void
): void;
public deleteApplication(
args: DeleteApplicationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteApplicationCommandOutput) => void),
cb?: (err: any, data?: DeleteApplicationCommandOutput) => void
): Promise<DeleteApplicationCommandOutput> | void {
const command = new DeleteApplicationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Gets information about a Fleet Hub for AWS IoT Device Management web application.</p>
* <note>
* <p>Fleet Hub for AWS IoT Device Management is in public preview and is subject to change.</p>
* </note>
*/
public describeApplication(
args: DescribeApplicationCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeApplicationCommandOutput>;
public describeApplication(
args: DescribeApplicationCommandInput,
cb: (err: any, data?: DescribeApplicationCommandOutput) => void
): void;
public describeApplication(
args: DescribeApplicationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeApplicationCommandOutput) => void
): void;
public describeApplication(
args: DescribeApplicationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeApplicationCommandOutput) => void),
cb?: (err: any, data?: DescribeApplicationCommandOutput) => void
): Promise<DescribeApplicationCommandOutput> | void {
const command = new DescribeApplicationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Gets a list of Fleet Hub for AWS IoT Device Management web applications for the current account.</p>
* <note>
* <p>Fleet Hub for AWS IoT Device Management is in public preview and is subject to change.</p>
* </note>
*/
public listApplications(
args: ListApplicationsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListApplicationsCommandOutput>;
public listApplications(
args: ListApplicationsCommandInput,
cb: (err: any, data?: ListApplicationsCommandOutput) => void
): void;
public listApplications(
args: ListApplicationsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListApplicationsCommandOutput) => void
): void;
public listApplications(
args: ListApplicationsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListApplicationsCommandOutput) => void),
cb?: (err: any, data?: ListApplicationsCommandOutput) => void
): Promise<ListApplicationsCommandOutput> | void {
const command = new ListApplicationsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists the tags for the specified resource.</p>
* <note>
* <p>Fleet Hub for AWS IoT Device Management is in public preview and is subject to change.</p>
* </note>
*/
public listTagsForResource(
args: ListTagsForResourceCommandInput,
options?: __HttpHandlerOptions
): Promise<ListTagsForResourceCommandOutput>;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
cb: (err: any, data?: ListTagsForResourceCommandOutput) => void
): void;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListTagsForResourceCommandOutput) => void
): void;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void),
cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void
): Promise<ListTagsForResourceCommandOutput> | void {
const command = new ListTagsForResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Adds to or modifies the tags of the specified resource. Tags are metadata which can be used to manage a resource.</p>
* <note>
* <p>Fleet Hub for AWS IoT Device Management is in public preview and is subject to change.</p>
* </note>
*/
public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>;
public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void;
public tagResource(
args: TagResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: TagResourceCommandOutput) => void
): void;
public tagResource(
args: TagResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void),
cb?: (err: any, data?: TagResourceCommandOutput) => void
): Promise<TagResourceCommandOutput> | void {
const command = new TagResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Removes the specified tags (metadata) from the resource.</p>
* <note>
* <p>Fleet Hub for AWS IoT Device Management is in public preview and is subject to change.</p>
* </note>
*/
public untagResource(
args: UntagResourceCommandInput,
options?: __HttpHandlerOptions
): Promise<UntagResourceCommandOutput>;
public untagResource(
args: UntagResourceCommandInput,
cb: (err: any, data?: UntagResourceCommandOutput) => void
): void;
public untagResource(
args: UntagResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UntagResourceCommandOutput) => void
): void;
public untagResource(
args: UntagResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void),
cb?: (err: any, data?: UntagResourceCommandOutput) => void
): Promise<UntagResourceCommandOutput> | void {
const command = new UntagResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates information about a Fleet Hub for a AWS IoT Device Management web application.</p>
* <note>
* <p>Fleet Hub for AWS IoT Device Management is in public preview and is subject to change.</p>
* </note>
*/
public updateApplication(
args: UpdateApplicationCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateApplicationCommandOutput>;
public updateApplication(
args: UpdateApplicationCommandInput,
cb: (err: any, data?: UpdateApplicationCommandOutput) => void
): void;
public updateApplication(
args: UpdateApplicationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateApplicationCommandOutput) => void
): void;
public updateApplication(
args: UpdateApplicationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateApplicationCommandOutput) => void),
cb?: (err: any, data?: UpdateApplicationCommandOutput) => void
): Promise<UpdateApplicationCommandOutput> | void {
const command = new UpdateApplicationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
} | the_stack |
import React from 'react'
import debounce from 'lodash/debounce'
import api from 'utils/api'
import { Form, Row, Col, Input, InputNumber, Radio, Checkbox, Select, Upload, Icon, Popover, Tooltip } from 'antd'
const FormItem = Form.Item
const RadioGroup = Radio.Group
const CheckboxGroup = Checkbox.Group
const Option = Select.Option
import { FormComponentProps } from 'antd/lib/form/Form'
import { SketchPicker } from 'react-color'
const styles = require('../Display.less')
interface ISettingFormProps extends FormComponentProps {
id: number
settingInfo: any
settingParams: any
onDisplaySizeChange: (width: number, height: number) => void
onFormItemChange: (field: any, value: any) => any
onCollapseChange: () => void
}
interface ISettingFormStates {
loading: object
collapse: boolean
}
export class SettingForm extends React.Component<ISettingFormProps, ISettingFormStates> {
private debounceFormItemChange = null
constructor (props: ISettingFormProps) {
super(props)
this.state = {
loading: {},
collapse: false
}
this.debounceFormItemChange = debounce(this.props.onFormItemChange, 1000)
}
public shouldComponentUpdate (nextProps: ISettingFormProps, nextState: ISettingFormStates) {
const { settingInfo, settingParams } = nextProps
const { collapse } = nextState
const needUpdate = settingInfo !== this.props.settingInfo
|| !(this.compareSettingParams(this.props.settingParams, settingParams) && this.compareSettingParams(this.props.settingParams, this.props.form.getFieldsValue()))
|| collapse !== this.state.collapse
return needUpdate
}
public componentWillReceiveProps (nextProps: ISettingFormProps) {
const {
onFormItemChange,
settingParams
} = nextProps
if (onFormItemChange !== this.props.onFormItemChange) {
this.debounceFormItemChange = debounce(onFormItemChange, 1000)
}
if (!this.compareSettingParams(this.props.settingParams, settingParams)) {
this.props.form.setFieldsValue({...settingParams})
}
}
private compareSettingParams = (
params1: ISettingFormProps['settingParams'],
params2: ISettingFormProps['settingParams']
) => {
const isSame = Object.keys(params1)
.every((key) => JSON.stringify(params1[key]) === JSON.stringify(params2[key]))
return isSame
}
private getFormItemLayout = (item) => {
const { labelCol, wrapperCol } = item
return {
labelCol: {
xs: { span: labelCol || 12 }
},
wrapperCol: {
xs: { span: wrapperCol || 12 }
}
}
}
private toggleCollapse = () => {
const { onCollapseChange } = this.props
const { collapse } = this.state
this.setState({ collapse: !collapse }, () => {
onCollapseChange()
})
}
private renderSetting = (setting) => {
const title = (
<h2 className={styles.formTitle}>
<span>{setting.title}</span>
<Tooltip title="显示/隐藏设置">
<Icon onClick={this.toggleCollapse} type="right-square-o" />
</Tooltip>
</h2>
)
const formItems = setting.params.map((param) => this.renderItem(param))
return (
<div className={styles.right}>
{title}
<div className={styles.items}>
<Form>
{formItems}
{this.props.children}
</Form>
</div>
</div>
)
}
private formItemChange = (field) => (val) => {
this.props.onFormItemChange(field, val)
}
private formDebouncedItemChange = (field) => (val) => {
this.debounceFormItemChange(field, val)
}
private formInputItemChange = (field) => (e) => {
this.props.onFormItemChange(field, e.target.value)
}
private formRadioItemChange = (field) => (e) => {
this.props.onFormItemChange(field, e.target.value)
}
private formCheckboxItemChange = (field) => (e) => {
this.props.onFormItemChange(field, e.target.checked)
}
private renderItem = (param) => {
const { form, settingParams } = this.props
const { getFieldDecorator } = form
const title = <h3 className={styles.formBlockTitle}>{param.title}</h3>
const content = param.items.map((item) => {
let control
switch (item.component) {
case 'input':
control = this.renderInput(item, this.formInputItemChange)
break
case 'inputnumber':
control = this.renderInputNumber(item, this.formDebouncedItemChange)
break
case 'colorPicker':
control = this.renderColorPicker(item, this.formDebouncedItemChange, settingParams[item.name])
break
case 'select':
control = this.renderSelect(item, this.formItemChange)
break
case 'radio':
control = this.renderRadio(item, this.formRadioItemChange)
break
case 'checkbox':
control = this.renderCheckbox(item, this.formCheckboxItemChange)
break
case 'checkboxGroup':
control = this.renderCheckboxGroup(item, this.formItemChange)
break
case 'upload':
control = this.renderUpload(item, this.formItemChange, settingParams[item.name])
break
default:
control = ''
break
}
if (control) {
control = this.wrapFormItem(control, item, getFieldDecorator)
}
return control
})
return (
<Row className={styles.formBlock} key={param.name}>
{title}
{content}
</Row>
)
}
public render () {
const {
settingInfo
} = this.props
const { collapse } = this.state
if (collapse) {
return (
<div className={styles.collapse}>
<h2 className={styles.formTitle}>
<Tooltip title="显示/隐藏设置">
<Icon onClick={this.toggleCollapse} type="left-square-o" />
</Tooltip>
</h2>
<div className={styles.title}>
<label>{settingInfo.title}</label>
</div>
</div>
)
}
return this.renderSetting(settingInfo)
}
private wrapFormItem = (control, item, getFieldDecorator) => {
const { settingParams, id } = this.props
return (
<Col key={item.name} span={item.span || 24}>
<FormItem label={item.title} {...this.getFormItemLayout(item)}>
{getFieldDecorator(item.name, {
initialValue: settingParams[item.name] || item.default || ''
})(control)}
</FormItem>
</Col>
)
}
private renderSelect = (item, formItemChange) => {
return (
<Select
placeholder={item.tip || item.placeholder || item.name}
onChange={formItemChange(item.name)}
>
{
Array.isArray(item.values)
? item.values.map((val) => (
<Option key={val.value} value={val.value}>{val.name}</Option>
))
: ''
}
</Select>
)
}
private renderInput = (item, formItemChange) => {
return (
<Input
placeholder={item.tip || item.placeholder || item.name}
onPressEnter={formItemChange(item.name)}
/>
)
}
private renderInputNumber = (item, formItemChange) => {
return (
<InputNumber
placeholder={item.tip || item.placeholder || item.name}
min={item.min === undefined ? -Infinity : item.min}
max={item.max === undefined ? Infinity : item.max}
onChange={formItemChange(item.name)}
/>
)
}
private renderRadio = (item, formItemChange) => {
return (
<RadioGroup onChange={formItemChange(item.name)}>
{
item.values.map((val) => (
<Radio key={val.value} value={val.value}>{val.name}</Radio>
))
}
</RadioGroup>
)
}
private renderCheckbox = (item, formItemChange) => {
return (
<Checkbox checked={item.value} onChange={formItemChange(item.name)}>{item.title}</Checkbox>
)
}
private renderCheckboxGroup = (item, formItemChange) => {
return (
<CheckboxGroup onChange={formItemChange(item.name)} options={item.values} />
)
}
private renderColorPicker = (item, formItemChange, rgb) => {
const onChangeComplete = (e) => {
const { r, g, b, a } = e.rgb
formItemChange(item.name)([r, g, b, a])
}
const color = rgb ? `rgba(${rgb.join()})` : `rgba(0,0,0,1)`
const colorPicker = (
<SketchPicker
color={color}
onChangeComplete={onChangeComplete}
/>
)
return (
<Popover placement="bottom" trigger="click" content={colorPicker}>
<i className="iconfont icon-palette" style={{color}}/>
</Popover>
)
}
private renderUpload = (item, formItemChange, img) => {
const { id } = this.props
const action = `${api.display}/${item.action}`.replace(/({id})/, id.toString())
const headers = {
authorization: `Bearer ${localStorage.getItem('TOKEN')}`
}
const { loading } = this.state
const onChange = (info) => {
const { status, response } = info.file
if (status === 'uploading') {
this.setState({
loading: {
...loading,
[item.name]: true
}
})
return
}
if (status === 'done') {
this.setState({
loading: {
...loading,
[item.name]: false
}
}, () => {
formItemChange(item.name)(response.payload)
})
}
}
const deleteUpload = (e: React.MouseEvent) => {
formItemChange(item.name)(null)
e.stopPropagation()
}
return (
<Row>
<Col span={24}>
<Upload
className={styles.upload}
showUploadList={false}
name={item.name}
disabled={loading[item.name]}
action={action}
headers={headers}
onChange={onChange}
>
{img ? (
<div className={styles.img}>
<img src={img} alt={item.title}/>
<Icon type="delete" onClick={deleteUpload}/>
</div>
) : <Icon type="plus" />}
</Upload>
</Col>
</Row>
)
}
}
export default Form.create<ISettingFormProps>()(SettingForm) | the_stack |
import './polyfills'
import _Promise from 'promise-polyfill'
/**
* The NGL module. These members are available in the `NGL` namespace when using the {@link https://github.com/umdjs/umd|UMD} build in the `ngl.js` file.
* @module NGL
*/
export {
Debug, setDebug,
MeasurementDefaultParams, setMeasurementDefaultParams,
ScriptExtensions, ColormakerRegistry,
DatasourceRegistry, DecompressorRegistry,
ParserRegistry, RepresentationRegistry,
setListingDatasource, setTrajectoryDatasource,
ListingDatasource, TrajectoryDatasource
} from './globals'
export { autoLoad, getDataInfo, getFileInfo } from './loader/loader-utils'
import Selection from './selection/selection'
import PdbWriter from './writer/pdb-writer'
import SdfWriter from './writer/sdf-writer'
import StlWriter from './writer/stl-writer'
import Stage from './stage/stage'
import Viewer from './viewer/viewer'
import Collection from './component/collection'
import ComponentCollection from './component/component-collection'
import Component from './component/component'
import ShapeComponent from './component/shape-component'
import StructureComponent, {StructureRepresentationType} from './component/structure-component'
import SurfaceComponent from './component/surface-component'
import VolumeComponent, {VolumeRepresentationType} from './component/volume-component'
import RepresentationCollection from './component/representation-collection'
import RepresentationElement from './component/representation-element'
import Assembly from './symmetry/assembly'
import TrajectoryPlayer from './trajectory/trajectory-player'
import Superposition from './align/superposition'
export { superpose } from './align/align-utils'
export { guessElement, concatStructures } from './structure/structure-utils'
export { flatten, throttle, download, getQuery, uniqueArray } from './utils'
import Queue from './utils/queue'
import Counter from './utils/counter'
import Frames from './trajectory/frames'
//
import Colormaker from './color/colormaker'
import './color/atomindex-colormaker'
import './color/bfactor-colormaker'
import './color/chainid-colormaker'
import './color/chainindex-colormaker'
import './color/chainname-colormaker'
import './color/densityfit-colormaker'
import './color/electrostatic-colormaker'
import './color/element-colormaker'
import './color/entityindex-colormaker'
import './color/entitytype-colormaker'
import './color/geoquality-colormaker'
import './color/hydrophobicity-colormaker'
import './color/modelindex-colormaker'
import './color/moleculetype-colormaker'
import './color/occupancy-colormaker'
import './color/partialcharge-colormaker'
import './color/random-colormaker'
import './color/randomcoilindex-colormaker'
import './color/residueindex-colormaker'
import './color/resname-colormaker'
import './color/sstruc-colormaker'
import './color/structuredata-colormaker'
import './color/uniform-colormaker'
import './color/value-colormaker'
import './color/volume-colormaker'
//
import './component/shape-component'
import './component/structure-component'
import './component/surface-component'
import './component/volume-component'
//
import AngleRepresentation, {AngleRepresentationParameters} from './representation/angle-representation'
import AxesRepresentation, {AxesRepresentationParameters} from './representation/axes-representation'
import BackboneRepresentation from './representation/backbone-representation'
import BallAndStickRepresentation, {BallAndStickRepresentationParameters} from './representation/ballandstick-representation'
import BaseRepresentation from './representation/base-representation'
import CartoonRepresentation, {CartoonRepresentationParameters} from './representation/cartoon-representation'
import ContactRepresentation, {ContactRepresentationParameters} from './representation/contact-representation'
import DihedralRepresentation, {DihedralRepresentationParameters} from './representation/dihedral-representation'
import DihedralHistogramRepresentation, {DihedralHistogramRepresentationParameters} from './representation/dihedral-histogram-representation'
import DistanceRepresentation, {DistanceRepresentationParameters} from './representation/distance-representation'
import HelixorientRepresentation from './representation/helixorient-representation'
import HyperballRepresentation, {HyperballRepresentationParameters} from './representation/hyperball-representation'
import LabelRepresentation, {LabelRepresentationParameters} from './representation/label-representation'
import LicoriceRepresentation from './representation/licorice-representation'
import LineRepresentation, {LineRepresentationParameters} from './representation/line-representation'
import MolecularSurfaceRepresentation, {MolecularSurfaceRepresentationParameters} from './representation/molecularsurface-representation'
import PointRepresentation, {PointRepresentationParameters} from './representation/point-representation'
import RibbonRepresentation, {RibbonRepresentationParameters} from './representation/ribbon-representation'
import RocketRepresentation, {RocketRepresentationParameters} from './representation/rocket-representation'
import RopeRepresentation from './representation/rope-representation'
import SpacefillRepresentation from './representation/spacefill-representation'
import StructureRepresentation, {StructureRepresentationParameters} from './representation/structure-representation'
import TraceRepresentation, {TraceRepresentationParameters} from './representation/trace-representation'
import TubeRepresentation from './representation/tube-representation'
import UnitcellRepresentation, {UnitcellRepresentationParameters} from './representation/unitcell-representation'
import ValidationRepresentation from './representation/validation-representation'
import BufferRepresentation from './representation/buffer-representation'
import ArrowBuffer from './buffer/arrow-buffer'
import BoxBuffer from './buffer/box-buffer'
import ConeBuffer from './buffer/cone-buffer'
import CylinderBuffer from './buffer/cylinder-buffer'
import EllipsoidBuffer from './buffer/ellipsoid-buffer'
import MeshBuffer from './buffer/mesh-buffer'
import OctahedronBuffer from './buffer/octahedron-buffer'
import PointBuffer from './buffer/point-buffer'
import SphereBuffer from './buffer/sphere-buffer'
import TetrahedronBuffer from './buffer/tetrahedron-buffer'
import TextBuffer from './buffer/text-buffer'
import TorusBuffer from './buffer/torus-buffer'
import WidelineBuffer from './buffer/wideline-buffer'
//
import './parser/cif-parser'
import './parser/gro-parser'
import './parser/mmtf-parser'
import './parser/mol2-parser'
import './parser/pdb-parser'
import './parser/pdbqt-parser'
import './parser/pqr-parser'
import './parser/sdf-parser'
import './parser/prmtop-parser'
import './parser/psf-parser'
import './parser/top-parser'
import './parser/dcd-parser'
import './parser/nctraj-parser'
import './parser/trr-parser'
import './parser/xtc-parser'
import './parser/cube-parser'
import './parser/dsn6-parser'
import './parser/dx-parser'
import './parser/dxbin-parser'
import './parser/mrc-parser'
import './parser/xplor-parser'
import './parser/kin-parser'
import './parser/obj-parser'
import './parser/ply-parser'
import './parser/csv-parser'
import './parser/json-parser'
import './parser/msgpack-parser'
import './parser/netcdf-parser'
import './parser/text-parser'
import './parser/xml-parser'
import './parser/validation-parser'
//
import Shape from './geometry/shape'
import Kdtree from './geometry/kdtree'
import SpatialHash from './geometry/spatial-hash'
import Structure from './structure/structure'
import MolecularSurface from './surface/molecular-surface'
import Volume from './surface/volume'
//
import './utils/gzip-decompressor'
//
import './datasource/rcsb-datasource'
import './datasource/pubchem-datasource'
import './datasource/passthrough-datasource'
import './datasource/alphafold-datasource'
import StaticDatasource from './datasource/static-datasource'
import MdsrvDatasource from './datasource/mdsrv-datasource'
//
export {
LeftMouseButton, MiddleMouseButton, RightMouseButton
} from './constants'
export {MouseActionCallback} from './controls/mouse-actions'
import MouseActions from './controls/mouse-actions'
import KeyActions from './controls/key-actions'
import PickingProxy from './controls/picking-proxy'
//
export { Signal } from 'signals'
export {
Matrix3, Matrix4, Vector2, Vector3, Box3, Quaternion, Euler, Plane, Color
} from 'three'
//
export { UIStageParameters } from './ui/parameters'
export { StageParameters } from './stage/stage'
export { StructureComponentDefaultParameters } from './component/structure-component'
//
import Version from './version'
if (!(window as any).Promise) {
(window as any).Promise = _Promise
}
export {
Version,
StaticDatasource,
MdsrvDatasource,
Colormaker,
Selection,
PdbWriter,
SdfWriter,
StlWriter,
Stage,
Viewer,
Collection,
ComponentCollection,
RepresentationCollection,
RepresentationElement,
Component,
ShapeComponent,
StructureComponent,
SurfaceComponent,
VolumeComponent,
StructureRepresentationType,
VolumeRepresentationType,
Assembly,
TrajectoryPlayer,
Superposition,
Frames,
Queue,
Counter,
AngleRepresentation,
AngleRepresentationParameters,
AxesRepresentation,
AxesRepresentationParameters,
BackboneRepresentation,
BallAndStickRepresentation,
BallAndStickRepresentationParameters,
BaseRepresentation,
CartoonRepresentation,
CartoonRepresentationParameters,
ContactRepresentation,
ContactRepresentationParameters,
DihedralRepresentation,
DihedralRepresentationParameters,
DihedralHistogramRepresentation,
DihedralHistogramRepresentationParameters,
DistanceRepresentation,
DistanceRepresentationParameters,
HelixorientRepresentation,
HyperballRepresentation,
HyperballRepresentationParameters,
LabelRepresentation,
LabelRepresentationParameters,
LicoriceRepresentation,
LineRepresentation,
LineRepresentationParameters,
MolecularSurfaceRepresentation,
MolecularSurfaceRepresentationParameters,
PointRepresentation,
PointRepresentationParameters,
RibbonRepresentation,
RibbonRepresentationParameters,
RocketRepresentation,
RocketRepresentationParameters,
RopeRepresentation,
SpacefillRepresentation,
StructureRepresentation,
StructureRepresentationParameters,
TraceRepresentation,
TraceRepresentationParameters,
TubeRepresentation,
UnitcellRepresentation,
UnitcellRepresentationParameters,
ValidationRepresentation,
BufferRepresentation,
ArrowBuffer,
BoxBuffer,
ConeBuffer,
CylinderBuffer,
EllipsoidBuffer,
MeshBuffer,
OctahedronBuffer,
PointBuffer,
SphereBuffer,
TetrahedronBuffer,
TextBuffer,
TorusBuffer,
WidelineBuffer,
Shape,
Structure,
Kdtree,
SpatialHash,
MolecularSurface,
Volume,
MouseActions,
KeyActions,
PickingProxy
} | the_stack |
namespace com.keyman.dom {
// Utility object used to handle beep (keyboard error response) operations.
class BeepData {
e: HTMLElement;
c: string;
constructor(e: HTMLElement) {
this.e = e;
this.c = e.style.backgroundColor;
}
reset(): void {
this.e.style.backgroundColor = this.c;
}
}
/**
* This class serves as the intermediary between KeymanWeb and any given web page's elements.
*/
export class DOMManager {
private keyman: KeymanBase;
/**
* Implements the AliasElementHandlers interface for touch interaction.
*/
touchHandlers?: DOMTouchHandlers;
/**
* Implements stubs for the AliasElementHandlers interface for non-touch interaction.
*/
nonTouchHandlers: DOMEventHandlers;
/**
* Tracks the attachment MutationObserver.
*/
attachmentObserver: MutationObserver;
/**
* Tracks the enablement MutationObserver.
*/
enablementObserver: MutationObserver;
/**
* Tracks a list of event-listening elements.
*
* In touch mode, this should contain touch-aliasing DIVs, but will contain other elements in non-touch mode.
*/
inputList: HTMLElement[] = []; // List of simulated input divisions for touch-devices I3363 (Build 301)
/**
* Tracks a visually-sorted list of elements that are KMW-enabled.
*/
sortedInputs: HTMLElement[] = []; // List of all INPUT and TEXTAREA elements ordered top to bottom, left to right
_BeepObjects: BeepData[] = []; // BeepObjects - maintains a list of active 'beep' visual feedback elements
_BeepTimeout: number = 0; // BeepTimeout - a flag indicating if there is an active 'beep'.
// Set to 1 if there is an active 'beep', otherwise leave as '0'.
// Used for special touch-based page interactions re: element activation on touch devices.
deactivateOnScroll: boolean = false;
deactivateOnRelease: boolean = false;
touchY: number; // For scroll-related aspects on iOS.
touchStartActivationHandler: (e: TouchEvent) => boolean;
touchMoveActivationHandler: (e: TouchEvent) => boolean;
touchEndActivationHandler: (e: TouchEvent) => boolean;
constructor(keyman: KeymanBase) {
this.keyman = keyman;
if(keyman.util.device.touchable) {
this.touchHandlers = new DOMTouchHandlers(keyman);
}
this.nonTouchHandlers = new DOMEventHandlers(keyman);
}
shutdown() {
// Catch and notify of any shutdown errors, but don't let errors fail unit tests.
try {
if(this.enablementObserver) {
this.enablementObserver.disconnect();
}
if(this.attachmentObserver) {
this.attachmentObserver.disconnect();
}
for(let input of this.inputList) {
this.disableInputElement(input);
}
// On shutdown, we remove our general focus-suppression handlers as well.
this.keyman.util.detachDOMEvent(document.body, 'focus', DOMManager.suppressFocusCheck, true);
this.keyman.util.detachDOMEvent(document.body, 'blur', DOMManager.suppressFocusCheck, true);
// Also, the base-page touch handlers for activation management.
if(this.touchStartActivationHandler) {
this.keyman.util.detachDOMEvent(document.body, 'touchstart', this.touchStartActivationHandler, false);
this.keyman.util.detachDOMEvent(document.body, 'touchmove', this.touchMoveActivationHandler, false);
this.keyman.util.detachDOMEvent(document.body, 'touchend', this.touchEndActivationHandler, false);
}
} catch (e) {
console.error("Error occurred during shutdown");
console.error(e);
}
}
/**
* Function beep KB (DOM-side implementation)
* Scope Public
* @param {Object} Pelem element to flash
* Description Flash body as substitute for audible beep; notify embedded device to vibrate
*/
doBeep(outputTarget: targets.OutputTarget) {
// Handles embedded-mode beeps.
let keyman = com.keyman.singleton;
if ('beepKeyboard' in keyman) {
keyman['beepKeyboard']();
return;
}
if(!(outputTarget instanceof targets.OutputTarget)) {
return;
}
// All code after this point is DOM-based, triggered by the beep.
var Pelem: HTMLElement = outputTarget.getElement();
if(outputTarget instanceof dom.targets.DesignIFrame) {
Pelem = outputTarget.docRoot; // I1446 - beep sometimes fails to flash when using OSK and rich control
}
if(!Pelem) {
return; // There's no way to signal a 'beep' to null, so just cut everything short.
}
if(!Pelem.style || typeof(Pelem.style.backgroundColor)=='undefined') {
return;
}
for(var Lbo=0; Lbo<this._BeepObjects.length; Lbo++) { // I1446 - beep sometimes fails to return background color to normal
// I1511 - array prototype extended
if(this._BeepObjects[Lbo].e == Pelem) {
return;
}
}
this._BeepObjects = com.keyman.singleton._push(this._BeepObjects, new BeepData(Pelem));
// TODO: This is probably a bad color choice if "dark mode" is enabled. A proper implementation
// would probably require some 'fun' CSS work, though.
Pelem.style.backgroundColor = '#000000';
if(this._BeepTimeout == 0) {
this._BeepTimeout = 1;
window.setTimeout(this.beepReset.bind(this), 50);
}
}
/**
* Function beepReset
* Scope Public
* Description Reset/terminate beep or flash (not currently used: Aug 2011)
*/
beepReset(): void {
com.keyman.singleton.core.keyboardInterface.resetContextCache();
var Lbo;
this._BeepTimeout = 0;
for(Lbo=0;Lbo<this._BeepObjects.length;Lbo++) { // I1511 - array prototype extended
this._BeepObjects[Lbo].reset();
}
this._BeepObjects = [];
}
/**
* Function getHandlers
* Scope Private
* @param {Element} Pelem An input, textarea, or touch-alias element from the page.
* @returns {Object}
*/
getHandlers(Pelem: HTMLElement): DOMEventHandlers {
var _attachObj = Pelem.base ? Pelem.base._kmwAttachment : Pelem._kmwAttachment;
if(_attachObj) {
return _attachObj.touchEnabled ? this.touchHandlers : this.nonTouchHandlers;
} else {
// Best guess solution.
return this.keyman.touchAliasing;
}
}
/**
* Function enableTouchElement
* Scope Private
* @param {Element} Pelem An input or textarea element from the page.
* @return {boolean} Returns true if it creates a simulated input element for Pelem; false if not.
* Description Creates a simulated input element for the specified INPUT or TEXTAREA, comprising:
* an outer DIV, matching the position, size and style of the base element
* a scrollable DIV within that outer element
* two SPAN elements within the scrollable DIV, to hold the text before and after the caret
*
* The left border of the second SPAN is flashed on and off as a visible caret
*
* Also ensures the element is registered on keymanweb's internal input list.
*/
enableTouchElement(Pelem: HTMLElement) {
// Touch doesn't worry about iframes.
if(Pelem.tagName.toLowerCase() == 'iframe') {
return false;
}
if(this.isKMWDisabled(Pelem)) {
this.setupNonKMWTouchElement(Pelem);
return false;
} else {
// Initialize and protect input elements for touch-screen devices (but never for apps)
// NB: now set disabled=true rather than readonly, since readonly does not always
// prevent element from getting focus, e.g. within a LABEL element.
// c.f. http://kreotekdev.wordpress.com/2007/11/08/disabled-vs-readonly-form-fields/
Pelem.kmwInput = true;
}
// Remove any handlers for "NonKMWTouch" elements, since we're enabling it here.
Pelem.removeEventListener('touchstart', this.nonKMWTouchHandler);
/*
* Does this element already have a simulated touch element established? If so,
* just reuse it - if it isn't still in the input list!
*/
if(Pelem['kmw_ip']) {
if(this.inputList.indexOf(Pelem['kmw_ip']) != -1) {
return false;
}
this.inputList.push(Pelem['kmw_ip']);
console.log("Unexpected state - this element's simulated input DIV should have been removed from the page!");
return true; // May need setup elsewhere since it's just been re-added!
}
// The simulated touch element doesn't already exist? Time to initialize it.
let x=dom.constructTouchAlias(Pelem);
if(this.isAttached(x)) {
x._kmwAttachment.interface = dom.targets.wrapElement(x);
} else {
this.setupElementAttachment(x); // The touch-alias should have its own wrapper.
}
Pelem._kmwAttachment = x._kmwAttachment; // It's an object reference we need to alias.
// Set font for base element
this.enableInputElement(x, true);
// Superimpose custom input fields for each input or textarea, unless readonly or disabled
// On touch event, reposition the text caret and prepare for OSK input
// Removed 'onfocus=' as that resulted in handling the event twice (on iOS, anyway)
// We know this to be the correct set of handlers because we're setting up a touch element.
var touchHandlers = this.touchHandlers;
x.addEventListener('touchstart', touchHandlers.setFocus);
x.onmspointerdown=function(e: MSPointerEvent) {
e.preventDefault();
e.stopPropagation();
return touchHandlers.setFocus(e);
};
x.addEventListener('touchend', touchHandlers.dragEnd, false);
x.onmspointerup=function(e) {
e.stopPropagation();
};
// Disable internal scroll when input element in focus
x.addEventListener('touchmove', touchHandlers.dragInput, false);
x.onmspointermove=touchHandlers.dragInput;
// Hide keyboard and caret when losing focus from simulated input field
x.onblur=touchHandlers.setBlur;
// Note that touchend event propagates and is processed by body touchend handler
// re-setting the first touch point for a drag
return true;
}
/**
* Function disableTouchElement
* Scope Private
* @param {Element} Pelem An input or textarea element from the page.
* Description Destroys the simulated input element for the specified INPUT or TEXTAREA and reverts
* back to desktop-style 'enablement' for the base control.
*/
disableTouchElement(Pelem: HTMLElement) {
// Do not check for the element being officially disabled - it's also used for detachment.
// Touch doesn't worry about iframes.
if(Pelem.tagName.toLowerCase() == 'iframe') {
return; // If/when we do support this, we'll need an iframe-level manager for it.
}
if(Pelem['kmw_ip']) {
var index = this.inputList.indexOf(Pelem['kmw_ip']);
if(index != -1) {
this.inputList.splice(index, 1);
}
Pelem.style.visibility='visible'; // hide by default: KMW-3
Pelem.disabled = false;
Pelem.removeEventListener('resize', Pelem['kmw_ip']._kmwResizeHandler);
// Disable touch-related handling code.
this.disableInputElement(Pelem['kmw_ip']);
Pelem._kmwAttachment.interface = dom.targets.wrapElement(Pelem);
// We get weird repositioning errors if we don't remove our simulated input element - and permanently.
if(Pelem.parentNode) {
Pelem.parentNode.removeChild(Pelem['kmw_ip']);
}
delete Pelem['kmw_ip'];
}
this.setupNonKMWTouchElement(Pelem);
}
/**
* Function nonKMWTouchHandler
* Scope Private
* Description A handler for KMW-touch-disabled elements when operating on touch devices.
*/
nonKMWTouchHandler = function(x) {
DOMEventHandlers.states.focusing=false;
clearTimeout(DOMEventHandlers.states.focusTimer);
this.keyman.osk.hideNow();
}.bind(this);
/**
* Function setupNonKMWTouchElement
* Scope Private
* @param {Element} x A child element of document.
* Description Performs handling for the specified disabled input element on touch-based systems.
*/
setupNonKMWTouchElement(x: HTMLElement) {
this.keyman.util.attachDOMEvent(x, 'touchstart', this.nonKMWTouchHandler, false);
// Signify that touch isn't enabled on the control.
if(this.isAttached(x)) {
x._kmwAttachment.touchEnabled = false;
}
}
/**
* Function enableInputElement
* Scope Private
* @param {Element} Pelem An element from the document to be enabled with full KMW handling.
* @param {boolean=} isAlias A flag that indicates if the element is a simulated input element for touch.
* Description Performs the basic enabling setup for one element and adds it to the inputList if it is an input element.
* Note that this method is called for both desktop and touch control routes; the touch route calls it from within
* enableTouchElement as it must first establish the simulated touch element to serve as the alias "input element" here.
* Note that the 'kmw-disabled' property is managed by the MutationObserver and by the surface API calls.
*/
enableInputElement(Pelem: HTMLElement, isAlias?: boolean) {
var baseElement = isAlias ? Pelem['base'] : Pelem;
if(!this.isKMWDisabled(baseElement)) {
if(Pelem instanceof Pelem.ownerDocument.defaultView.HTMLIFrameElement) {
this._AttachToIframe(Pelem);
} else {
if(!isAlias) {
this.setupElementAttachment(Pelem);
}
baseElement.className = baseElement.className ? baseElement.className + ' keymanweb-font' : 'keymanweb-font';
this.inputList.push(Pelem);
this.keyman.util.attachDOMEvent(baseElement,'focus', this.getHandlers(Pelem)._ControlFocus);
this.keyman.util.attachDOMEvent(baseElement,'blur', this.getHandlers(Pelem)._ControlBlur);
// These need to be on the actual input element, as otherwise the keyboard will disappear on touch.
Pelem.onkeypress = this.getHandlers(Pelem)._KeyPress;
Pelem.onkeydown = this.getHandlers(Pelem)._KeyDown;
Pelem.onkeyup = this.getHandlers(Pelem)._KeyUp;
}
}
};
/**
* Function disableInputElement
* Scope Private
* @param {Element} Pelem An element from the document to be enabled with full KMW handling.
* @param {boolean=} isAlias A flag that indicates if the element is a simulated input element for touch.
* Description Inverts the process of enableInputElement, removing all event-handling from the element.
* Note that the 'kmw-disabled' property is managed by the MutationObserver and by the surface API calls.
*/
disableInputElement(Pelem: HTMLElement, isAlias?: boolean) {
if(!Pelem) {
return;
}
var baseElement = isAlias ? Pelem['base'] : Pelem;
// Do NOT test for pre-disabledness - we also use this to fully detach without officially 'disabling' via kmw-disabled.
if((Pelem.ownerDocument.defaultView && Pelem instanceof Pelem.ownerDocument.defaultView.HTMLIFrameElement) ||
Pelem instanceof HTMLIFrameElement) {
this._DetachFromIframe(Pelem);
} else {
var cnIndex = baseElement.className.indexOf('keymanweb-font');
if(cnIndex > 0 && !isAlias) { // See note about the alias below.
baseElement.className = baseElement.className.replace('keymanweb-font', '').trim();
}
// Remove the element from our internal input tracking.
var index = this.inputList.indexOf(Pelem);
if(index > -1) {
this.inputList.splice(index, 1);
}
if(!isAlias) { // See note about the alias below.
this.keyman.util.detachDOMEvent(baseElement,'focus', this.getHandlers(Pelem)._ControlFocus);
this.keyman.util.detachDOMEvent(baseElement,'blur', this.getHandlers(Pelem)._ControlBlur);
}
// These need to be on the actual input element, as otherwise the keyboard will disappear on touch.
Pelem.onkeypress = null;
Pelem.onkeydown = null;
Pelem.onkeyup = null;
}
// If we're disabling an alias, we should fully enable the base version. (Thinking ahead to toggleable-touch mode.)
if(isAlias) {
this.inputList.push(baseElement);
baseElement.onkeypress = this.getHandlers(Pelem)._KeyPress;
baseElement.onkeydown = this.getHandlers(Pelem)._KeyDown;
baseElement.onkeyup = this.getHandlers(Pelem)._KeyUp;
}
var lastElem = this.lastActiveElement;
if(lastElem == Pelem || lastElem == Pelem['kmw_ip']) {
if(this.activeElement == lastElem) {
this.activeElement = null;
}
this.lastActiveElement = null;
this.keyman.osk.startHide(false);
}
return;
};
/**
* Function isKMWDisabled
* Scope Private
* @param {Element} x An element from the page.
* @return {boolean} true if the element's properties indicate a 'disabled' state.
* Description Examines attachable elements to determine their default enablement state.
*/
isKMWDisabled(x: HTMLElement): boolean {
var c = x.className;
// Exists for some HTMLElements.
if(x['readOnly']) {
return true;
} else if(c && c.indexOf('kmw-disabled') >= 0) {
return true;
}
return false;
}
/**
* Function attachToControl
* Scope Public
* @param {Element} Pelem Element to which KMW will be attached
* Description Attaches KMW to control (or IFrame)
*/
attachToControl(Pelem: HTMLElement) {
var touchable = this.keyman.util.device.touchable;
// Exception for IFrame elements, in case of async loading issues. (Fixes fun iframe loading bug with Chrome.)
if(this.isAttached(Pelem) && !(Pelem instanceof Pelem.ownerDocument.defaultView.HTMLIFrameElement)) {
return; // We're already attached.
}
if(this.isKMWInput(Pelem)) {
if(!this.isKMWDisabled(Pelem)) {
if(touchable && !this.keyman.isEmbedded) {
this.enableTouchElement(Pelem);
} else {
this.enableInputElement(Pelem);
}
} else {
if(touchable) {
this.setupNonKMWTouchElement(Pelem);
}
}
} else if(touchable) {
this.setupNonKMWTouchElement(Pelem);
}
}
/**
* Function detachFromControl
* Scope Public
* @param {Element} Pelem Element from which KMW will detach
* Description Detaches KMW from a control (or IFrame)
*/
detachFromControl(Pelem: HTMLElement) {
if(!(this.isAttached(Pelem) || Pelem instanceof Pelem.ownerDocument.defaultView.HTMLIFrameElement)) {
return; // We never were attached.
}
// #1 - if element is enabled, disable it. But don't manipulate the 'kmw-disabled' tag.
if(this.isKMWInput(Pelem)) {
// Is it already disabled?
if(!this.isKMWDisabled(Pelem)) {
this._DisableControl(Pelem);
}
}
// #2 - clear attachment data.
this.clearElementAttachment(Pelem);
}
/**
* Function isAttached
* Scope Private
* @param {Element} x An element from the page.
* @return {boolean} true if KMW is attached to the element, otherwise false.
*/
isAttached(x: HTMLElement) {
return x._kmwAttachment ? true : false;
}
/**
* Function isKMWInput
* Scope Private
* @param {Element} x An element from the page.
* @return {boolean} true if the element is viable for KMW attachment.
* Description Examines potential input elements to determine whether or not they are viable for KMW attachment.
* Also filters elements not supported for touch devices when device.touchable == true.
*/
isKMWInput(x: HTMLElement): boolean {
var touchable = this.keyman.util.device.touchable;
if(x instanceof x.ownerDocument.defaultView.HTMLTextAreaElement) {
return true;
} else if(x instanceof x.ownerDocument.defaultView.HTMLInputElement) {
if (x.type == 'text' || x.type == 'search') {
return true;
}
} else if(x instanceof x.ownerDocument.defaultView.HTMLIFrameElement && !touchable) { // Do not allow iframe attachment if in 'touch' mode.
try {
if(x.contentWindow) {
if(x.contentWindow.document) { // Only allow attachment if the iframe's internal document is valid.
return true;
}
} // else nothing?
}
catch(err) {
/* Do not attempt to access iframes outside this site */
console.warn("Error during attachment to / detachment from iframe: ");
console.warn(err);
}
} else if(x.isContentEditable && !touchable) { // Only allow contentEditable attachment outside of 'touch' mode.
return true;
}
return false;
}
/**
* Function setupElementAttachment
* Scope Private
* @param {Element} x An element from the page valid for KMW attachment
* Description Establishes the base KeymanWeb data for newly-attached elements.
* Does not establish input hooks, which are instead handled during enablement.
*/
setupElementAttachment(x: HTMLElement) {
// The `_kmwAttachment` property tag maintains all relevant KMW-maintained data regarding the element.
// It is disgarded upon de-attachment.
if(x._kmwAttachment) {
return;
} else {
// Problem: tries to wrap IFrames that aren't design-mode.
// The elements in the contained document get separately wrapped, so this doesn't need a proper wrapper.
//
// Its attachment process might need some work.
let eleInterface = dom.targets.wrapElement(x);
// May should filter better for IFrames.
if(!(eleInterface || dom.Utils.instanceof(x, "HTMLIFrameElement"))) {
console.warn("Could not create processing interface for newly-attached element!");
}
x._kmwAttachment = new AttachmentInfo(eleInterface, null, this.keyman.util.device.touchable);
}
}
/**
* Function clearElementAttachment
* Scope Private
* @param {Element} x An element from the page valid for KMW attachment
* Description Establishes the base KeymanWeb data for newly-attached elements.
* Does not establish input hooks, which are instead handled during enablement.
*/
clearElementAttachment(x: HTMLElement) {
// We need to clear the object when de-attaching; helps prevent memory leaks.
x._kmwAttachment = null;
}
/**
* Function _AttachToIframe
* Scope Private
* @param {Element} Pelem IFrame to which KMW will be attached
* Description Attaches KeymanWeb to IFrame
*/
_AttachToIframe(Pelem: HTMLIFrameElement) {
var util = this.keyman.util;
try {
var Lelem=Pelem.contentWindow.document;
/* editable Iframe */
if(Lelem) {
if(Lelem.designMode.toLowerCase() == 'on') {
// I2404 - Attach to IFRAMEs child objects, only editable IFRAMEs here
if(util.device.browser == 'firefox') {
util.attachDOMEvent(Lelem,'focus', this.getHandlers(Pelem)._ControlFocus);
util.attachDOMEvent(Lelem,'blur', this.getHandlers(Pelem)._ControlBlur);
} else { // Chrome, Safari
util.attachDOMEvent(Lelem.body,'focus', this.getHandlers(Pelem)._ControlFocus);
util.attachDOMEvent(Lelem.body,'blur', this.getHandlers(Pelem)._ControlBlur);
}
util.attachDOMEvent(Lelem.body,'keydown', this.getHandlers(Pelem)._KeyDown);
util.attachDOMEvent(Lelem.body,'keypress', this.getHandlers(Pelem)._KeyPress);
util.attachDOMEvent(Lelem.body,'keyup', this.getHandlers(Pelem)._KeyUp);
// Set up a reference alias; the internal document will need the same attachment info!
this.setupElementAttachment(Pelem);
Lelem.body._kmwAttachment = Pelem._kmwAttachment;
} else {
// Lelem is the IFrame's internal document; set 'er up!
this._SetupDocument(Lelem.body); // I2404 - Manage IE events in IFRAMEs
}
}
}
catch(err)
{
// do not attempt to attach to the iframe as it is from another domain - XSS denied!
}
}
/**
* Function _DetachFromIframe
* Scope Private
* @param {Element} Pelem IFrame to which KMW will be attached
* Description Detaches KeymanWeb from an IFrame
*/
_DetachFromIframe(Pelem: HTMLIFrameElement) {
var util = this.keyman.util;
try {
var Lelem=Pelem.contentWindow.document;
/* editable Iframe */
if(Lelem) {
if(Lelem.designMode.toLowerCase() == 'on') {
// Mozilla // I2404 - Attach to IFRAMEs child objects, only editable IFRAMEs here
if(util.device.browser == 'firefox') {
// Firefox won't handle these events on Lelem.body - only directly on Lelem (the doc) instead.
util.detachDOMEvent(Lelem,'focus', this.getHandlers(Pelem)._ControlFocus);
util.detachDOMEvent(Lelem,'blur', this.getHandlers(Pelem)._ControlBlur);
} else { // Chrome, Safari
util.detachDOMEvent(Lelem.body,'focus', this.getHandlers(Pelem)._ControlFocus);
util.detachDOMEvent(Lelem.body,'blur', this.getHandlers(Pelem)._ControlBlur);
}
util.detachDOMEvent(Lelem.body,'keydown', this.getHandlers(Pelem)._KeyDown);
util.detachDOMEvent(Lelem.body,'keypress', this.getHandlers(Pelem)._KeyPress);
util.detachDOMEvent(Lelem.body,'keyup', this.getHandlers(Pelem)._KeyUp);
// Remove the reference to our prior attachment data!
Lelem.body._kmwAttachment = null;
} else {
// Lelem is the IFrame's internal document; set 'er up!
this._ClearDocument(Lelem.body); // I2404 - Manage IE events in IFRAMEs
}
}
}
catch(err)
{
// do not attempt to attach to the iframe as it is from another domain - XSS denied!
}
}
/**
* Function _GetDocumentEditables
* Scope Private
* @param {Element} Pelem HTML element
* @return {Array<Element>} A list of potentially-editable controls. Further filtering [as with isKMWInput() and
* isKMWDisabled()] is required.
*/
_GetDocumentEditables(Pelem: HTMLElement): (HTMLElement)[] {
var util = this.keyman.util;
var possibleInputs: (HTMLElement)[] = [];
// Document.ownerDocument === null, so we better check that it's not null before proceeding.
if(Pelem.ownerDocument && Pelem instanceof Pelem.ownerDocument.defaultView.HTMLElement) {
var dv = Pelem.ownerDocument.defaultView;
if(Pelem instanceof dv.HTMLInputElement || Pelem instanceof dv.HTMLTextAreaElement) {
possibleInputs.push(Pelem);
} else if(Pelem instanceof dv.HTMLIFrameElement) {
possibleInputs.push(Pelem);
}
}
// Constructing it like this also allows for individual element filtering for the auto-attach MutationObserver without errors.
if(Pelem.getElementsByTagName) {
/**
* Function LiTmp
* Scope Private
* @param {string} _colon type of element
* @return {Array<Element>} array of elements of specified type
* Description Local function to get list of editable controls
*/
var LiTmp = function(_colon: string): HTMLElement[] {
return util.arrayFromNodeList(Pelem.getElementsByTagName(_colon));
};
// Note that isKMWInput() will block IFRAME elements as necessary for touch-based devices.
possibleInputs = possibleInputs.concat(LiTmp('INPUT'), LiTmp('TEXTAREA'), LiTmp('IFRAME'));
}
// Not all active browsers may support the method, but only those that do would work with contenteditables anyway.
if(Pelem.querySelectorAll) {
possibleInputs = possibleInputs.concat(util.arrayFromNodeList(Pelem.querySelectorAll('[contenteditable]')));
}
if(Pelem.ownerDocument && Pelem instanceof Pelem.ownerDocument.defaultView.HTMLElement && Pelem.isContentEditable) {
possibleInputs.push(Pelem);
}
return possibleInputs;
}
/**
* Function _SetupDocument
* Scope Private
* @param {Element} Pelem - the root element of a document, including IFrame documents.
* Description Used to automatically attach KMW to editable controls, regardless of control path.
*/
_SetupDocument(Pelem: HTMLElement) { // I1961
var possibleInputs = this._GetDocumentEditables(Pelem);
for(var Li = 0; Li < possibleInputs.length; Li++) {
var input = possibleInputs[Li];
// It knows how to handle pre-loaded iframes appropriately.
this.attachToControl(possibleInputs[Li] as HTMLElement);
}
}
/**
* Function _ClearDocument
* Scope Private
* @param {Element} Pelem - the root element of a document, including IFrame documents.
* Description Used to automatically detach KMW from editable controls, regardless of control path.
* Mostly used to clear out all controls of a detached IFrame.
*/
_ClearDocument(Pelem: HTMLElement) { // I1961
var possibleInputs = this._GetDocumentEditables(Pelem);
for(var Li = 0; Li < possibleInputs.length; Li++) {
var input = possibleInputs[Li];
// It knows how to handle pre-loaded iframes appropriately.
this.detachFromControl(possibleInputs[Li] as HTMLElement);
}
}
/**
* Set target element text direction (LTR or RTL), but only if the element is empty
*
* If the element base directionality is changed after it contains content, unless all the text
* has the same directionality, text runs will be re-ordered which is confusing and causes
* incorrect caret positioning
*
* @param {Object} Ptarg Target element
*/
_SetTargDir(Ptarg: HTMLElement) {
let activeKeyboard = com.keyman.singleton.core.activeKeyboard;
var elDir=(activeKeyboard && activeKeyboard.isRTL) ? 'rtl' : 'ltr';
if(Ptarg) {
if(this.keyman.util.device.touchable) {
let alias = <dom.TouchAliasElement> Ptarg;
if(Ptarg.textContent.length == 0) {
alias.base.dir=alias.dir=elDir;
alias.setTextCaret(10000);
}
} else {
if(Ptarg instanceof Ptarg.ownerDocument.defaultView.HTMLInputElement
|| Ptarg instanceof Ptarg.ownerDocument.defaultView.HTMLTextAreaElement) {
if((Ptarg as HTMLInputElement|HTMLTextAreaElement).value.length == 0) {
Ptarg.dir=elDir;
}
} else if(typeof Ptarg.textContent == "string" && Ptarg.textContent.length == 0) { // As with contenteditable DIVs, for example.
Ptarg.dir=elDir;
}
}
}
}
/**
* Function _DisableControl
* Scope Private
* @param {Element} Pelem Element to be disabled
* Description Disable KMW control element
*/
_DisableControl(Pelem: HTMLElement) {
// Only operate on attached elements! Non-design-mode IFrames don't get attachment markers, so we check them specifically instead.
if(this.isAttached(Pelem) || Pelem instanceof Pelem.ownerDocument.defaultView.HTMLIFrameElement) {
if(this.keyman.util.device.touchable) {
this.disableTouchElement(Pelem);
this.setupNonKMWTouchElement(Pelem);
var keyman = this.keyman;
// If a touch alias was removed, chances are it's gonna mess up our touch-based layout scheme, so let's update the touch elements.
window.setTimeout(function() {
this.listInputs();
for(var k = 0; k < this.sortedInputs.length; k++) {
if(this.sortedInputs[k]['kmw_ip']) {
this.sortedInputs[k]['kmw_ip'].updateInput(this.sortedInputs[k]['kmw_ip']);
}
}
}.bind(this), 1);
} else {
this.listInputs(); // Fix up our internal input ordering scheme.
}
this.disableInputElement(Pelem);
}
}
/**
* Function _EnableControl
* Scope Private
* @param {Element} Pelem Element to be enabled
* Description Enable KMW control element
*/
_EnableControl(Pelem: HTMLElement) {
if(this.isAttached(Pelem)) { // Only operate on attached elements!
if(this.keyman.util.device.touchable) {
this.enableTouchElement(Pelem);
var keyman = this.keyman;
// If we just added a new input alias, some languages will mess up our touch-based layout scheme
// if we don't update the touch elements.
window.setTimeout(function() {
keyman.domManager.listInputs();
for(var k = 0; k < this.sortedInputs.length; k++) {
if(this.sortedInputs[k]['kmw_ip']) {
this.sortedInputs[k]['kmw_ip'].updateInput(this.sortedInputs[k]['kmw_ip']);
}
}
}.bind(this), 1);
} else {
this.enableInputElement(Pelem);
}
}
}
// Create an ordered list of all text and search input elements and textarea elements
// except any tagged with class 'kmw-disabled'
// TODO: email and url types should perhaps use default keyboard only
listInputs() {
var i,eList=[],
t1=document.getElementsByTagName<'input'>('input'),
t2=document.getElementsByTagName<'textarea'>('textarea');
var util = this.keyman.util;
for(i=0; i<t1.length; i++) {
switch(t1[i].type) {
case 'text':
case 'search':
case 'email':
case 'url':
if(t1[i].className.indexOf('kmw-disabled') < 0) {
eList.push({ip:t1[i], x: dom.Utils.getAbsoluteX(t1[i]), y: dom.Utils.getAbsoluteY(t1[i])});
}
break;
}
}
for(i=0; i<t2.length; i++) {
if(t2[i].className.indexOf('kmw-disabled') < 0)
eList.push({ip:t2[i], x: dom.Utils.getAbsoluteX(t2[i]), y: dom.Utils.getAbsoluteY(t2[i])});
}
/**
* Local function to sort by screen position
*
* @param {Object} e1 first object
* @param {Object} e2 second object
* @return {number} y-difference between object positions, or x-difference if y values the same
*/
var xySort=function(e1,e2)
{
if(e1.y != e2.y) return e1.y-e2.y;
return e1.x-e2.x;
}
// Sort elements by Y then X
eList.sort(xySort);
// Create a new list of sorted elements
var tList=[];
for(i=0;i<eList.length;i++)
tList.push(eList[i].ip);
// Return the sorted element list
this.sortedInputs=tList;
}
_EnablementMutationObserverCore = function(mutations: MutationRecord[]) {
for(var i=0; i < mutations.length; i++) {
var mutation = mutations[i];
// ( ? : ) needed as a null check.
var disabledBefore = mutation.oldValue ? mutation.oldValue.indexOf('kmw-disabled') >= 0 : false;
var disabledAfter = (mutation.target as HTMLElement).className.indexOf('kmw-disabled') >= 0;
if(disabledBefore && !disabledAfter) {
this._EnableControl(mutation.target);
} else if(!disabledBefore && disabledAfter) {
this._DisableControl(mutation.target);
}
// 'readonly' triggers on whether or not the attribute exists, not its value.
if(!disabledAfter && mutation.attributeName == "readonly") {
var readonlyBefore = mutation.oldValue ? mutation.oldValue != null : false;
var elem = mutation.target;
if(elem instanceof elem.ownerDocument.defaultView.HTMLInputElement
|| elem instanceof elem.ownerDocument.defaultView.HTMLTextAreaElement) {
var readonlyAfter = elem.readOnly;
if(readonlyBefore && !readonlyAfter) {
this._EnableControl(mutation.target);
} else if(!readonlyBefore && readonlyAfter) {
this._DisableControl(mutation.target);
}
}
}
}
}.bind(this);
_AutoAttachObserverCore = function(mutations: MutationRecord[]) {
var inputElementAdditions = [];
var inputElementRemovals = [];
for(var i=0; i < mutations.length; i++) {
var mutation = mutations[i];
for(var j=0; j < mutation.addedNodes.length; j++) {
inputElementAdditions = inputElementAdditions.concat(this._GetDocumentEditables(mutation.addedNodes[j]));
}
for(j = 0; j < mutation.removedNodes.length; j++) {
inputElementRemovals = inputElementRemovals.concat(this._GetDocumentEditables(mutation.removedNodes[j]));
}
}
for(var k = 0; k < inputElementAdditions.length; k++) {
if(this.isKMWInput(inputElementAdditions[k])) { // Apply standard element filtering!
this._MutationAdditionObserved(inputElementAdditions[k]);
}
}
for(k = 0; k < inputElementRemovals.length; k++) {
if(this.isKMWInput(inputElementRemovals[k])) { // Apply standard element filtering!
this._MutationRemovalObserved(inputElementRemovals[k]);
}
}
/* After all mutations have been handled, we need to recompile our .sortedInputs array, but only
* if any have actually occurred.
*/
if(inputElementAdditions.length || inputElementRemovals.length) {
if(!this.keyman.util.device.touchable) {
this.listInputs();
} else if(this.keyman.util.device.touchable) { // If something was added or removed, chances are it's gonna mess up our touch-based layout scheme, so let's update the touch elements.
var domManager = this;
window.setTimeout(function() {
domManager.listInputs();
for(var k = 0; k < this.sortedInputs.length; k++) {
if(this.sortedInputs[k]['kmw_ip']) {
this.sortedInputs[k]['kmw_ip'].updateInput();
}
}
}.bind(this), 1);
}
}
}.bind(this);
/**
* Function _MutationAdditionObserved
* Scope Private
* @param {Element} Pelem A page input, textarea, or iframe element.
* Description Used by the MutationObserver event handler to properly setup any elements dynamically added to the document post-initialization.
*
*/
_MutationAdditionObserved = function(Pelem: HTMLElement) {
if(Pelem instanceof Pelem.ownerDocument.defaultView.HTMLIFrameElement && !this.keyman.util.device.touchable) {
//Problem: the iframe is loaded asynchronously, and we must wait for it to load fully before hooking in.
var domManager = this;
var attachFunctor = function() { // Triggers at the same time as iframe's onload property, after its internal document loads.
// Provide a minor delay to allow 'load' event handlers to set the design-mode property.
window.setTimeout(function() {
domManager.attachToControl(Pelem);
}, 1);
};
Pelem.addEventListener('load', attachFunctor);
// The following block breaks for design-mode iframes, at least in Chrome; a blank document may exist
// before the load of the desired actual document.
//
// /* If the iframe has somehow already loaded, we can't expect the onload event to be raised. We ought just
// * go ahead and perform our callback's contents.
// *
// * keymanweb.domManager.attachToControl() is now idempotent, so even if our call 'whiffs', it won't cause long-lasting
// * problems.
// */
// if(Pelem.contentDocument.readyState == 'complete') {
// window.setTimeout(attachFunctor, 1);
// }
} else {
this.attachToControl(Pelem);
}
}
// Used by the mutation event handler to properly decouple any elements dynamically removed from the document.
_MutationRemovalObserved = function(Pelem: HTMLElement) {
var element = Pelem;
if(this.keyman.util.device.touchable) {
this.disableTouchElement(Pelem);
}
this.disableInputElement(Pelem); // Remove all KMW event hooks, styling.
this.clearElementAttachment(element); // Memory management & auto de-attachment upon removal.
}
/**
* Function disableControl
* Scope Public
* @param {Element} Pelem Element to be disabled
* Description Disables a KMW control element
*/
disableControl(Pelem: HTMLElement) {
if(!this.isAttached(Pelem)) {
console.warn("KeymanWeb is not attached to element " + Pelem);
}
var cn = Pelem.className;
if(cn.indexOf('kmw-disabled') < 0) { // if not already explicitly disabled...
Pelem.className = cn ? cn + ' kmw-disabled' : 'kmw-disabled';
}
// The rest is triggered within MutationObserver code.
// See _EnablementMutationObserverCore.
}
/**
* Function enableControl
* Scope Public
* @param {Element} Pelem Element to be disabled
* Description Disables a KMW control element
*/
enableControl = function(Pelem: HTMLElement) {
if(!this.isAttached(Pelem)) {
console.warn("KeymanWeb is not attached to element " + Pelem);
}
var cn = Pelem.className;
var tagIndex = cn.indexOf('kmw-disabled');
if(tagIndex >= 0) { // if already explicitly disabled...
Pelem.className = cn.replace('kmw-disabled', '').trim();
}
// The rest is triggered within MutationObserver code.
// See _EnablementMutationObserverCore.
}
/* ------------- Page and document-level management events ------------------ */
_WindowLoad: (e: Event) => void = function(e: Event) {
//keymanweb.completeInitialization();
// Always return to top of page after a page reload
document.body.scrollTop=0;
if(typeof document.documentElement != 'undefined') {
document.documentElement.scrollTop=0;
}
}.bind(this);
/**
* Function _WindowUnload
* Scope Private
* Description Remove handlers before detaching KMW window
*/
_WindowUnload: () => void = function(this: DOMManager) {
// Allow the UI to release its own resources
this.keyman.uiManager.doUnload();
// Allow the OSK to release its own resources
if(this.keyman.osk) {
this.keyman.osk.shutdown();
if(this.keyman.osk['_Unload']) {
this.keyman.osk['_Unload'](); // I3363 (Build 301)
}
}
this.lastActiveElement = null;
}.bind(this);
/* ------ Defines independent, per-control keyboard setting behavior for the API. ------ */
/**
* Function setKeyboardForControl
* Scope Public
* @param {Element} Pelem Control element
* @param {string|null=} Pkbd Keyboard (Clears the set keyboard if set to null.)
* @param {string|null=} Plc Language Code
* Description Set default keyboard for the control
*/
setKeyboardForControl(Pelem: HTMLElement, Pkbd?: string, Plc?: string) {
/* pass null for kbd to specify no default, or '' to specify the default system keyboard. */
if(Pkbd !== null && Pkbd !== undefined) {
var index = Pkbd.indexOf("Keyboard_");
if(index < 0 && Pkbd != '') {
Pkbd = "Keyboard_" + Pkbd;
}
} else {
Plc = null;
}
if(Pelem instanceof Pelem.ownerDocument.defaultView.HTMLIFrameElement) {
console.warn("'keymanweb.setKeyboardForControl' cannot set keyboard on iframes.");
return;
}
if(!this.isAttached(Pelem)) {
console.error("KeymanWeb is not attached to element " + Pelem);
return;
} else {
Pelem._kmwAttachment.keyboard = Pkbd;
Pelem._kmwAttachment.languageCode = Plc;
// If Pelem is the focused element/active control, we should set the keyboard in place now.
// 'kmw_ip' is the touch-alias for the original page's control.
var lastElem = this.lastActiveElement;
if(lastElem && (lastElem == Pelem || lastElem == Pelem['kmw_ip'])) {
if(Pkbd != null && Plc != null) { // Second part necessary for Closure.
this.keyman.keyboardManager.setActiveKeyboard(Pkbd, Plc);
} else {
this.keyman.keyboardManager.setActiveKeyboard(this.keyman.globalKeyboard, this.keyman.globalLanguageCode);
}
}
}
}
/**
* Function getKeyboardForControl
* Scope Public
* @param {Element} Pelem Control element
* @return {string|null} The independently-managed keyboard for the control.
* Description Returns the keyboard ID of the current independently-managed keyboard for this control.
* If it is currently following the global keyboard setting, returns null instead.
*/
getKeyboardForControl(Pelem: HTMLElement): string {
if(!this.isAttached(Pelem)) {
console.error("KeymanWeb is not attached to element " + Pelem);
return null;
} else {
return Pelem._kmwAttachment.keyboard;
}
}
/**
* Function getLanguageForControl
* Scope Public
* @param {Element} Pelem Control element
* @return {string|null} The independently-managed keyboard for the control.
* Description Returns the language code used with the current independently-managed keyboard for this control.
* If it is currently following the global keyboard setting, returns null instead.
*/
getLanguageForControl(Pelem: HTMLElement): string {
if(!this.isAttached(Pelem)) {
console.error("KeymanWeb is not attached to element " + Pelem);
return null;
} else {
return Pelem._kmwAttachment.languageCode; // Should we have a version for the language code, too?
}
}
/* ------ End independent, per-control keyboard setting behavior definitions. ------ */
/**
* Set focus to last active target element (browser-dependent)
*/
focusLastActiveElement() {
var lastElem = this.lastActiveElement;
if(!lastElem) {
return;
}
this.keyman.uiManager.justActivated = true;
const target = Utils.getOutputTarget(lastElem);
target.focus();
}
/**
* Get the last active target element *before* KMW activated (I1297)
*
* @return {Element}
*/
get lastActiveElement(): HTMLElement {
return DOMEventHandlers.states._lastActiveElement;
}
set lastActiveElement(Pelem: HTMLElement) {
DOMEventHandlers.states._lastActiveElement = Pelem;
const osk = this.keyman.osk;
if(osk) {
if(this.lastActiveElement == null && this.activeElement == null) {
// Assigning to the property does have side-effects.
// If the property is already unset, it's best to not unset it again.
osk.activeTarget = null;
this.keyman.osk.hideNow(); // originally from a different one, seemed to serve the same role?
}
}
}
get activeElement(): HTMLElement {
return DOMEventHandlers.states._activeElement;
}
set activeElement(Pelem: HTMLElement) {
// Ensure that a TouchAliasElement is hidden whenever it is deactivated for input.
if(this.activeElement) {
if(Utils.instanceof(this.keyman.domManager.activeElement, "TouchAliasElement")) {
(this.keyman.domManager.activeElement as TouchAliasElement).hideCaret();
}
}
DOMEventHandlers.states._activeElement = Pelem;
var isActivating = this.keyman.uiManager.isActivating;
// Hide the OSK when the control is blurred, unless the UI is being temporarily selected
const osk = this.keyman.osk;
// const device = this.keyman.util.device;
if(osk) {
const target = Pelem?._kmwAttachment?.interface || null;
if(osk && (target || !isActivating)) {
// Do not unset the field if the UI is activated.
osk.activeTarget = target;
}
}
}
/**
* Set the active input element directly optionally setting focus
*
* @param {Object|string} e element id or element
* @param {boolean=} setFocus optionally set focus (KMEW-123)
*/
setActiveElement(e: string|HTMLElement, setFocus?: boolean) {
if(typeof e == "string") { // Can't instanceof string, and String is a different type.
e = document.getElementById(e);
}
if(this.keyman.isEmbedded) {
// If we're in embedded mode, auto-attach to the element specified by the page.
if(!this.isAttached(e)) {
this.attachToControl(e);
}
// Non-attached elements cannot be set as active.
} else if(!this.isAttached(e)) {
console.warn("Cannot set an element KMW is not attached to as the active element.");
return;
}
// As this is an API function, someone may pass in the base of a touch element.
// We need to respond appropriately.
e = (e['kmw_ip'] ? e['kmw_ip'] : e) as HTMLElement;
// If we're changing controls, don't forget to properly manage the keyboard settings!
// It's only an issue on 'native' (non-embedded) code paths.
if(!this.keyman.isEmbedded) {
this.keyman.touchAliasing._BlurKeyboardSettings(this.keyman.domManager.lastActiveElement);
}
// No need to reset context if we stay within the same element.
if(this.activeElement != e) {
this.keyman['resetContext'](e as HTMLElement);
}
this.activeElement = this.lastActiveElement = e;
if(!this.keyman.isEmbedded) {
this.keyman.touchAliasing._FocusKeyboardSettings(e, false);
}
// Allow external focusing KMEW-123
if(arguments.length > 1 && setFocus) {
if(this.keyman.util.device.touchable) {
var tEvent = {
clientX: 0,
clientY: 0,
target: e as HTMLElement
};
// Kinda hacky, but gets the job done.
(this.keyman.touchAliasing as DOMTouchHandlers).setFocusWithTouch(tEvent);
} else {
this.focusLastActiveElement();
}
}
}
/** Sets the active input element only if it is presently null.
*
* @param {Element}
*/
initActiveElement(Lelem: HTMLElement) {
if(this.activeElement == null) {
this.activeElement = Lelem;
}
}
/**
* Move focus to next (or previous) input or text area element on TAB
* Uses list of actual input elements
*
* Note that activeElement() on touch devices returns the DIV that overlays
* the input element, not the element itself.
*
* @param {number|boolean} bBack Direction to move (0 or 1)
*/
moveToNext(bBack: number|boolean) {
var i,t=this.sortedInputs, activeBase = this.activeElement;
var touchable = this.keyman.util.device.touchable;
if(t.length == 0) {
return;
}
// For touchable devices, get the base element of the DIV
if(touchable) {
activeBase=activeBase.base;
}
// Identify the active element in the list of inputs ordered by position
for(i=0; i<t.length; i++) {
if(t[i] == activeBase) break;
}
// Find the next (or previous) element in the list
i = bBack ? i-1 : i+1;
// Treat the list as circular, wrapping the index if necessary.
i = i >= t.length ? i-t.length : i;
i = i < 0 ? i+t.length : i;
// Move to the selected element
if(touchable) {
// Set focusing flag to prevent OSK disappearing
DOMEventHandlers.states.focusing=true;
var target=t[i]['kmw_ip'];
// Focus if next element is non-mapped
if(typeof(target) == 'undefined') {
t[i].focus();
} else { // Or reposition the caret on the input DIV if mapped
let alias = <dom.TouchAliasElement> target;
this.keyman.domManager.setActiveElement(target); // Handles both `lastActive` + `active`.
alias.setTextCaret(10000); // Safe b/c touchable == true.
alias.scrollInput(); // mousedown check
target.focus();
}
} else { // Behaviour for desktop browsers
t[i].focus();
}
}
/**
* Move focus to user-specified element
*
* @param {string|Object} e element or element id
*
*/
moveToElement(e:string|HTMLElement) {
var i;
if(typeof(e) == "string") { // Can't instanceof string, and String is a different type.
e=document.getElementById(e);
}
if(this.keyman.util.device.touchable && e['kmw_ip']) {
e['kmw_ip'].focus();
} else {
e.focus();
}
}
/* ----------------------- Editable IFrame methods ------------------- */
/**
* Function _IsIEEditableIframe
* Scope Private
* @param {Object} Pelem Iframe element
* {boolean|number} PtestOn 1 to test if frame content is editable (TODO: unclear exactly what this is doing!)
* @return {boolean}
* Description Test if element is an IE editable IFrame
*/
_IsIEEditableIframe(Pelem: HTMLIFrameElement, PtestOn?: number) {
var Ldv, Lvalid = Pelem && (Ldv=Pelem.tagName) && Ldv.toLowerCase() == 'body' && (Ldv=Pelem.ownerDocument) && Ldv.parentWindow;
return (!PtestOn && Lvalid) || (PtestOn && (!Lvalid || Pelem.isContentEditable));
}
/**
* Function _IsMozillaEditableIframe
* Scope Private
* @param {Object} Pelem Iframe element
* @param {boolean|number} PtestOn 1 to test if 'designMode' is 'ON'
* @return {boolean}
* Description Test if element is a Mozilla editable IFrame
*/
_IsMozillaEditableIframe(Pelem: HTMLIFrameElement, PtestOn?: number) {
var Ldv, Lvalid = Pelem && (Ldv=(<any>Pelem).defaultView) && Ldv.frameElement; // Probable bug!
return (!PtestOn && Lvalid) || (PtestOn && (!Lvalid || Ldv.document.designMode.toLowerCase()=='on'));
}
/* ----------------------- Initialization methods ------------------ */
/**
* Get the user-specified (or default) font for the first mapped input or textarea element
* before applying any keymanweb styles or classes
*
* @return {string}
*/
getBaseFont() {
var util = this.keyman.util;
var ipInput = document.getElementsByTagName<'input'>('input'),
ipTextArea=document.getElementsByTagName<'textarea'>('textarea'),
n=0,fs,fsDefault='Arial,sans-serif';
// Find the first input element (if it exists)
if(ipInput.length == 0 && ipTextArea.length == 0) {
n=0;
} else if(ipInput.length > 0 && ipTextArea.length == 0) {
n=1;
} else if(ipInput.length == 0 && ipTextArea.length > 0) {
n=2;
} else {
var firstInput = ipInput[0];
var firstTextArea = ipTextArea[0];
if(firstInput.offsetTop < firstTextArea.offsetTop) {
n=1;
} else if(firstInput.offsetTop > firstTextArea.offsetTop) {
n=2;
} else if(firstInput.offsetLeft < firstTextArea.offsetLeft) {
n=1;
} else if(firstInput.offsetLeft > firstTextArea.offsetLeft) {
n=2;
}
}
// Grab that font!
switch(n) {
case 0:
fs=fsDefault;
case 1:
fs=util.getStyleValue(ipInput[0],'font-family');
case 2:
fs=util.getStyleValue(ipTextArea[0],'font-family');
}
if(typeof(fs) == 'undefined' || fs == 'monospace') {
fs=fsDefault;
}
return fs;
}
/**
* Function Initialization
* Scope Public
* @param {com.keyman.OptionType} arg object of user-defined properties
* Description KMW window initialization
*/
init: (arg: com.keyman.OptionType) => Promise<any> = function(this: DOMManager, arg): Promise<any> {
var p,opt,dTrailer,ds;
var util = this.keyman.util;
var device = util.device;
// Set callbacks for proper feedback from web-core.
this.keyman.core.keyboardProcessor.beepHandler = this.doBeep.bind(this);
this.keyman.core.keyboardProcessor.warningLogger = console.warn.bind(console);
this.keyman.core.keyboardProcessor.errorLogger = console.error.bind(console);
// Local function to convert relative to absolute URLs
// with respect to the source path, server root and protocol
var fixPath = function(p) {
if(p.length == 0) return p;
// Add delimiter if missing
if(p.substr(p.length-1,1) != '/') p = p+'/';
// Absolute
if((p.replace(/^(http)s?:.*/,'$1') == 'http')
|| (p.replace(/^(file):.*/,'$1') == 'file'))
return p;
// Absolute (except for protocol)
if(p.substr(0,2) == '//')
return this.keyman.protocol+p;
// Relative to server root
if(p.substr(0,1) == '/')
return this.keyman.rootPath+p.substr(1);
// Otherwise, assume relative to source path
return this.keyman.srcPath+p;
}.bind(this);
// Explicit (user-defined) parameter initialization
opt=this.keyman.options;
if(typeof(arg) == 'object' && arg !== null)
{
for(p in opt)
{
if(arg.hasOwnProperty(p)) opt[p] = arg[p];
}
}
// Get default paths and device options
if(opt['root'] != '') {
this.keyman.rootPath = fixPath(opt['root']);
}
// Keyboards and fonts are located with respect to the server root by default
//if(opt['keyboards'] == '') opt['keyboards'] = keymanweb.rootPath+'keyboard/';
//if(opt['fonts'] == '') opt['fonts'] = keymanweb.rootPath+'font/';
// Resources are located with respect to the engine by default
if(opt['resources'] == '') {
opt['resources'] = this.keyman.srcPath;
}
// Convert resource, keyboard and font paths to absolute URLs
opt['resources'] = fixPath(opt['resources']);
opt['keyboards'] = fixPath(opt['keyboards']);
opt['fonts'] = fixPath(opt['fonts']);
// Set default device options
this.keyman.setDefaultDeviceOptions(opt);
// Only do remainder of initialization once!
if(this.keyman.initialized) {
return Promise.resolve();
}
var keyman: KeymanBase = this.keyman;
var domManager = this;
// Do not initialize until the document has been fully loaded
if(document.readyState !== 'complete')
{
return new Promise<void>(function(resolve) {
window.setTimeout(function(){
domManager.init(arg).then(function() {
resolve();
});
}, 50);
});
}
keyman.modelManager.init();
this.keyman._MasterDocument = window.document;
/*
* Initialization of touch devices and browser interfaces must be done
* after all resources are loaded, during final stage of initialization
*/
// Set exposed initialization flag member for UI (and other) code to use
this.keyman.setInitialized(1);
// Finish keymanweb and initialize the OSK once all necessary resources are available
if(device.touchable) {
this.keyman.osk = new com.keyman.osk.AnchoredOSKView(device.coreSpec);
} else {
this.keyman.osk = new com.keyman.osk.FloatingOSKView(device.coreSpec);
}
const osk = this.keyman.osk;
// Create and save the remote keyboard loading delay indicator
util.prepareWait();
// Trigger registration of deferred keyboard stubs and keyboards
this.keyman.keyboardManager.endDeferment();
// Initialize the desktop UI
this.initializeUI();
// Exit initialization here if we're using an embedded code path.
if(this.keyman.isEmbedded) {
if(!this.keyman.keyboardManager.setDefaultKeyboard()) {
console.error("No keyboard stubs exist - cannot initialize keyboard!");
}
return Promise.resolve();
}
// Determine the default font for mapped elements
this.keyman.appliedFont=this.keyman.baseFont=this.getBaseFont();
// Add orientationchange event handler to manage orientation changes on mobile devices
// Initialize touch-screen device interface I3363 (Build 301)
if(device.touchable) {
this.keyman.handleRotationEvents();
}
// Initialize browser interface
if(this.keyman.options['attachType'] != 'manual') {
this._SetupDocument(document.documentElement);
}
// Create an ordered list of all input and textarea fields
this.listInputs();
// Initialize the OSK and set default OSK styles
// Note that this should *never* be called before the OSK has been initialized.
// However, it possibly may be called before the OSK has been fully defined with the current keyboard, need to check.
//osk._Load();
//document.body.appendChild(osk._Box);
//osk._Load(false);
// I3363 (Build 301)
if(device.touchable) {
const osk = keyman.osk as osk.AnchoredOSKView;
// Handle OSK touchend events (prevent propagation)
osk._Box.addEventListener('touchend',function(e){
e.stopPropagation();
}, false);
// Add a blank DIV to the bottom of the page to allow the bottom of the page to be shown
dTrailer=document.createElement('DIV');
ds=dTrailer.style;
ds.width='100%';
ds.height=(screen.width/2)+'px';
document.body.appendChild(dTrailer);
// Sets up page-default touch-based handling for activation-state management.
// These always trigger for the page, wherever a touch may occur. Does not
// prevent element-specific or OSK-key-specific handling from triggering.
const _this = this;
this.touchStartActivationHandler=function(e) {
_this.deactivateOnRelease=true;
_this.touchY=e.touches[0].screenY;
// On Chrome, scrolling up or down causes the URL bar to be shown or hidden
// according to whether or not the document is at the top of the screen.
// But when doing that, each OSK row top and height gets modified by Chrome
// looking very ugly. It would be best to hide the OSK then show it again
// when the user scroll finishes, but Chrome has no way to reliably report
// the touch end event after a move. c.f. http://code.google.com/p/chromium/issues/detail?id=152913
// The best compromise behaviour is simply to hide the OSK whenever any
// non-input and non-OSK element is touched.
_this.deactivateOnScroll=false;
if(device.OS == 'Android' && navigator.userAgent.indexOf('Chrome') > 0) {
// _this.deactivateOnScroll has the inverse of the 'true' default,
// but that fact actually facilitates the following conditional logic.
if(typeof(osk._Box) == 'undefined') return false;
if(typeof(osk._Box.style) == 'undefined') return false;
// The following tests are needed to prevent the OSK from being hidden during normal input!
let p=(e.target as HTMLElement).parentElement;
if(typeof(p) != 'undefined' && p != null) {
if(p.className.indexOf('keymanweb-input') >= 0) return false;
if(p.className.indexOf('kmw-key-') >= 0) return false;
if(typeof(p.parentElement) != 'undefined' && p.parentElement != null) {
p=p.parentElement;
if(p.className.indexOf('keymanweb-input') >= 0) return false;
if(p.className.indexOf('kmw-key-') >= 0) return false;
}
}
_this.deactivateOnScroll = true;
}
return false;
};
this.touchMoveActivationHandler = function(e) {
if(_this.deactivateOnScroll) { // Android / Chrone case.
DOMEventHandlers.states.focusing = false;
_this.activeElement = null;
}
const y = e.touches[0].screenY;
const y0 = _this.touchY;
if(y-y0 > 5 || y0-y < 5) {
_this.deactivateOnRelease = false;
}
return false;
};
this.touchEndActivationHandler = function() {
// Should not hide OSK if simply closing the language menu (30/4/15)
// or if the focusing timer (setFocusTimer) is still active.
if(_this.deactivateOnRelease && !osk['lgList'] && !DOMEventHandlers.states.focusing) {
_this.activeElement = null;
}
_this.deactivateOnRelease=false;
return false;
};
this.keyman.util.attachDOMEvent(document.body, 'touchstart', this.touchStartActivationHandler,false);
this.keyman.util.attachDOMEvent(document.body, 'touchmove', this.touchMoveActivationHandler, false);
this.keyman.util.attachDOMEvent(document.body, 'touchend', this.touchEndActivationHandler, false);
}
//document.body.appendChild(keymanweb._StyleBlock);
// Restore and reload the currently selected keyboard, selecting a default keyboard if necessary.
this.keyman.keyboardManager.restoreCurrentKeyboard();
/* Setup of handlers for dynamically-added and (eventually) dynamically-removed elements.
* Reference: https://developer.mozilla.org/en/docs/Web/API/MutationObserver
*
* We place it here so that it loads after most of the other UI loads, reducing the MutationObserver's overhead.
* Of course, we only want to dynamically add elements if the user hasn't enabled the manual attachment option.
*/
if(typeof MutationObserver == 'function') {
var observationTarget = document.querySelector('body'), observationConfig: MutationObserverInit;
if(this.keyman.options['attachType'] != 'manual') { //I1961
observationConfig = { childList: true, subtree: true};
this.attachmentObserver = new MutationObserver(this._AutoAttachObserverCore);
this.attachmentObserver.observe(observationTarget, observationConfig);
}
/*
* Setup of handlers for dynamic detection of the kmw-disabled class tag that controls enablement.
*/
observationConfig = { subtree: true, attributes: true, attributeOldValue: true, attributeFilter: ['class', 'readonly']};
this.enablementObserver = new MutationObserver(this._EnablementMutationObserverCore);
this.enablementObserver.observe(observationTarget, observationConfig);
} else {
console.warn("Your browser is outdated and does not support MutationObservers, a web feature " +
"needed by KeymanWeb to support dynamically-added elements.");
}
// Set exposed initialization flag to 2 to indicate deferred initialization also complete
/* To prevent propagation of focus & blur events from the input-scroll workaround,
* we attach top-level capturing listeners to the focus & blur events. They prevent propagation
* but NOT default behavior, allowing the scroll to complete while preventing nearly all
* possible event 'noise' that could result from the workaround.
*/
this.keyman.util.attachDOMEvent(document.body, 'focus', DOMManager.suppressFocusCheck, true);
this.keyman.util.attachDOMEvent(document.body, 'blur', DOMManager.suppressFocusCheck, true);
this.keyman.setInitialized(2);
return Promise.resolve();
}.bind(this);
/**
* Initialize the desktop user interface as soon as it is ready
*/
initializeUI() {
if(this.keyman.ui && this.keyman.ui['initialize'] instanceof Function) {
this.keyman.ui['initialize']();
// Display the OSK (again) if enabled, in order to set its position correctly after
// adding the UI to the page
this.keyman.osk.present();
} else if(this.keyman.isEmbedded) {
// UI modules aren't utilized in embedded mode. There's nothing to init, so we simply
// return instead of waiting for a UI module that will never come.
return;
} else {
window.setTimeout(this.initializeUI.bind(this),1000);
}
}
static suppressFocusCheck(e: Event) {
if(DOMEventHandlers.states._IgnoreBlurFocus) {
// Prevent triggering other blur-handling events (as possible)
e.stopPropagation();
e.cancelBubble = true;
}
// But DO perform default event behavior (actually blurring & focusing the affected element)
return true;
}
}
} | the_stack |
import { EMPTY, Observable } from 'rxjs';
import { EntityKey, ODataResource } from '../resource';
import { Expand, Filter, OrderBy, Select, Transform } from '../builder';
import { ODataCollection, ODataModel } from '../../models';
import {
ODataEntities,
ODataEntitiesAnnotations,
ODataEntity,
ODataEntityAnnotations,
} from '../responses';
import {
ODataEntitiesOptions,
ODataEntityOptions,
ODataOptions,
} from './options';
import { PathSegmentNames, QueryOptionNames } from '../../types';
import { concatMap, expand, map, toArray } from 'rxjs/operators';
import { ODataApi } from '../../api';
import { ODataCountResource } from './count';
import { ODataMediaResource } from './media';
import { ODataPathSegments } from '../path-segments';
import { ODataPropertyResource } from './property';
import { ODataQueryOptions } from '../query-options';
import { ODataReferenceResource } from './reference';
import { ODataStructuredTypeParser } from '../../parsers/structured-type';
/**
* OData Navigation Property Resource
* https://www.odata.org/getting-started/advanced-tutorial/#containment
* https://www.odata.org/getting-started/advanced-tutorial/#derived
*/
export class ODataNavigationPropertyResource<T> extends ODataResource<T> {
//#region Factory
static factory<E>(
api: ODataApi,
path: string,
type: string | undefined,
segments: ODataPathSegments,
options: ODataQueryOptions
) {
const segment = segments.add(PathSegmentNames.navigationProperty, path);
if (type) segment.type(type);
options.keep(QueryOptionNames.format);
return new ODataNavigationPropertyResource<E>(api, segments, options);
}
//#endregion
clone() {
return new ODataNavigationPropertyResource<T>(
this.api,
this.cloneSegments(),
this.cloneQuery()
);
}
schema() {
let type = this.type();
return type !== undefined
? this.api.findStructuredTypeForType<T>(type)
: undefined;
}
asModel<M extends ODataModel<T>>(
entity: Partial<T> | { [name: string]: any },
{ annots, reset }: { annots?: ODataEntityAnnotations; reset?: boolean } = {}
): M {
const type = annots?.type || this.type();
const Model = this.api.modelForType(type);
return new Model(entity, { resource: this, annots, reset }) as M;
}
asCollection<M extends ODataModel<T>, C extends ODataCollection<T, M>>(
entities: Partial<T>[] | { [name: string]: any }[],
{
annots,
reset,
}: { annots?: ODataEntitiesAnnotations; reset?: boolean } = {}
): C {
const type = annots?.type || this.type();
const Collection = this.api.collectionForType(type);
return new Collection(entities, { resource: this, annots, reset }) as C;
}
//#region Inmutable Resource
key(value: any) {
const navigation = this.clone();
var key = this.resolveKey(value);
if (key !== undefined) navigation.segment.navigationProperty().key(key);
return navigation;
}
keys(values: any[]) {
const navigation = this.clone();
const types = this.pathSegments.types({ key: true });
const keys = values.map((value, index) =>
ODataResource.resolveKey(
value,
this.api.findStructuredTypeForType<T>(types[index])
)
);
navigation.segment.keys(keys);
return navigation;
}
media() {
return ODataMediaResource.factory<T>(
this.api,
this.cloneSegments(),
this.cloneQuery()
);
}
reference() {
return ODataReferenceResource.factory(
this.api,
this.cloneSegments(),
this.cloneQuery()
);
}
navigationProperty<N>(path: string) {
let type = this.type();
if (type !== undefined) {
let parser = this.api.parserForType<N>(type);
type =
parser instanceof ODataStructuredTypeParser
? parser.typeFor(path)
: undefined;
}
return ODataNavigationPropertyResource.factory<N>(
this.api,
path,
type,
this.cloneSegments(),
this.cloneQuery()
);
}
property<P>(path: string) {
let type = this.type();
if (type !== undefined) {
let parser = this.api.parserForType<P>(type);
type =
parser instanceof ODataStructuredTypeParser
? parser.typeFor(path)
: undefined;
}
return ODataPropertyResource.factory<P>(
this.api,
path,
type,
this.cloneSegments(),
this.cloneQuery()
);
}
count() {
return ODataCountResource.factory(
this.api,
this.cloneSegments(),
this.cloneQuery()
);
}
cast<C>(type: string) {
let segments = this.cloneSegments();
segments.add(PathSegmentNames.type, type).type(type);
return new ODataNavigationPropertyResource<C>(
this.api,
segments,
this.cloneQuery()
);
}
select(opts: Select<T>) {
const clone = this.clone();
clone.query.select(opts);
return clone;
}
expand(opts: Expand<T>) {
const clone = this.clone();
clone.query.expand(opts);
return clone;
}
transform(opts: Transform<T>) {
const clone = this.clone();
clone.query.transform(opts);
return clone;
}
search(opts: string) {
const clone = this.clone();
clone.query.search(opts);
return clone;
}
filter(opts: Filter) {
const clone = this.clone();
clone.query.filter(opts);
return clone;
}
orderBy(opts: OrderBy<T>) {
const clone = this.clone();
clone.query.orderBy(opts);
return clone;
}
format(opts: string) {
const clone = this.clone();
clone.query.format(opts);
return clone;
}
top(opts: number) {
const clone = this.clone();
clone.query.top(opts);
return clone;
}
skip(opts: number) {
const clone = this.clone();
clone.query.skip(opts);
return clone;
}
skiptoken(opts: string) {
const clone = this.clone();
clone.query.skiptoken(opts);
return clone;
}
//#endregion
//#region Mutable Resource
get segment() {
const segments = this.pathSegments;
return {
entitySet() {
return segments.get(PathSegmentNames.entitySet);
},
singleton() {
return segments.get(PathSegmentNames.singleton);
},
navigationProperty() {
return segments.get(PathSegmentNames.navigationProperty);
},
keys(values?: (EntityKey<T> | undefined)[]) {
return segments.keys(values);
},
};
}
/**
* Handle query options of the navigation property
* @returns Handler for mutate the query of the navigation property
*/
get query() {
return this.entitiesQueryHandler();
}
//#endregion
//#region Requests
protected post(
attrs: Partial<T>,
options: ODataOptions = {}
): Observable<ODataEntity<T>> {
return super.post(attrs, { responseType: 'entity', ...options });
}
protected put(
attrs: Partial<T>,
options: ODataOptions & { etag?: string } = {}
): Observable<ODataEntity<T>> {
return super.put(attrs, { responseType: 'entity', ...options });
}
protected patch(
attrs: Partial<T>,
options: ODataOptions & { etag?: string } = {}
): Observable<ODataEntity<T>> {
return super.patch(attrs, { responseType: 'entity', ...options });
}
protected delete(
options: ODataOptions & { etag?: string } = {}
): Observable<any> {
return super.delete({ responseType: 'entity', ...options });
}
protected get(
options: ODataEntityOptions &
ODataEntitiesOptions & {
etag?: string;
bodyQueryOptions?: QueryOptionNames[];
} = {}
): Observable<any> {
return super.get(options);
}
//#endregion
//#region Shortcuts
/**
* Create a new entity
* @param attrs The entity attributes
* @param options Options for the request
* @returns The created entity with the annotations
*/
create(
attrs: Partial<T>,
options?: ODataOptions
): Observable<ODataEntity<T>> {
return this.post(attrs, options);
}
/**
* Update an existing entity
* @param attrs The entity attributes
* @param options Options for the request
* @param etag The etag of the entity
* @returns The updated entity with the annotations
*/
update(
attrs: Partial<T>,
options?: ODataOptions & { etag?: string }
): Observable<ODataEntity<T>> {
return this.put(attrs, options);
}
/**
* Modify an existing entity
* @param attrs The entity attributes
* @param options Options for the request
* @param etag The etag of the entity
* @returns The modified entity with the annotations
*/
modify(
attrs: Partial<T>,
options?: ODataOptions & { etag?: string }
): Observable<ODataEntity<T>> {
return this.patch(attrs, options);
}
/**
* Delete an existing entity
* @param options Options for the request
* @param etag The etag of the entity
* @returns An observable of the destroy
*/
destroy(options?: ODataOptions & { etag?: string }): Observable<any> {
return this.delete(options);
}
/**
* Fetch entity / entities
* @param options Options for the request
* @return An observable of the entity or entities with annotations
*/
fetch(
options?: ODataEntityOptions & {
etag?: string;
bodyQueryOptions?: QueryOptionNames[];
}
): Observable<ODataEntity<T>>;
fetch(
options?: ODataEntitiesOptions & {
etag?: string;
bodyQueryOptions?: QueryOptionNames[];
}
): Observable<ODataEntities<T>>;
fetch(
options: ODataEntityOptions &
ODataEntitiesOptions & {
etag?: string;
bodyQueryOptions?: QueryOptionNames[];
} = {}
): Observable<any> {
return this.get(options);
}
/**
* Fetch the entity
* @param options Options for the request
* @returns The entity
*/
fetchEntity(
options: ODataOptions & {
etag?: string;
bodyQueryOptions?: QueryOptionNames[];
} = {}
): Observable<T | null> {
return this.fetch({ responseType: 'entity', ...options }).pipe(
map(({ entity }) => entity)
);
}
/**
* Fetch the entity and return as model
* @param options Options for the request
* @returns The model
*/
fetchModel<M extends ODataModel<T>>(
options: ODataOptions & {
etag?: string;
bodyQueryOptions?: QueryOptionNames[];
} = {}
): Observable<M | null> {
return this.fetch({ responseType: 'entity', ...options }).pipe(
map(({ entity, annots }) =>
entity ? this.asModel<M>(entity, { annots, reset: true }) : null
)
);
}
/**
* Fetch entities
* @param options Options for the request
* @returns The entities
*/
fetchEntities(
options: ODataOptions & {
bodyQueryOptions?: QueryOptionNames[];
} = {}
): Observable<T[] | null> {
return this.fetch({ responseType: 'entities', ...options }).pipe(
map(({ entities }) => entities)
);
}
/**
* Fetch entities and return as collection
* @param options Options for the request
* @returns The collection
*/
fetchCollection<M extends ODataModel<T>, C extends ODataCollection<T, M>>(
options: ODataOptions & {
withCount?: boolean;
bodyQueryOptions?: QueryOptionNames[];
} = {}
): Observable<C | null> {
return this.fetch({ responseType: 'entities', ...options }).pipe(
map(({ entities, annots }) =>
entities
? this.asCollection<M, C>(entities, { annots, reset: true })
: null
)
);
}
/**
* Fetch all entities
* @param options Options for the request
* @returns All entities
*/
fetchAll(
options: ODataOptions & {
bodyQueryOptions?: QueryOptionNames[];
} = {}
): Observable<T[]> {
let res = this.clone();
// Clean Paging
res.query.clearPaging();
let fetch = (opts?: {
skip?: number;
skiptoken?: string;
top?: number;
}): Observable<ODataEntities<T>> => {
if (opts) {
res.query.paging(opts);
}
return res.fetch({ responseType: 'entities', ...options });
};
return fetch().pipe(
expand(({ annots: meta }) =>
meta.skip || meta.skiptoken ? fetch(meta) : EMPTY
),
concatMap(({ entities }) => entities || []),
toArray()
);
}
//#endregion
} | the_stack |
import { BehaviorSubject, Subject, Observable } from 'rxjs';
import { ValidatorFn, ValidationErrors, ValidationError } from './validators.class';
import { IsNullOrEmpty } from './helpers.class';
import { IFileUploadControlConfiguration } from './control.interface';
export enum STATUS {
INVALID,
VALID,
DISABLED
}
export enum FileEvent {
click = 'click',
focus = 'focus',
blur = 'blur'
}
export class FileUploadControl {
private readonly files: Map<string, File> = new Map();
private listVisible = true;
private status: STATUS = STATUS.VALID;
private errors: Array<{ [key: string]: any }> = [];
private validators: Array<ValidatorFn> = [];
private multipleEnabled: boolean = true;
private nativeBehavior: boolean = false;
private readonly multipleChanged: BehaviorSubject<boolean> = new BehaviorSubject(this.multipleEnabled);
private readonly statusChanged: Subject<STATUS> = new Subject();
private readonly eventsChanged: Subject<FileEvent> = new Subject();
private readonly discardedValue: Subject<Array<ValidationError>> = new Subject();
private accept: string | null = null;
private discard: boolean = false;
private readonly acceptChanged: BehaviorSubject<string> = new BehaviorSubject(this.accept);
/**
* track status `VALID`, `INVALID` or `DISABLED`
*/
public readonly statusChanges: Observable<STATUS> = this.statusChanged.asObservable();
/**
* emit an event every time the value of the control
* changes.
* Initially returns last value
*/
public readonly valueChanges: BehaviorSubject<Array<File>> = new BehaviorSubject([]);
/**
* @internal
* used to trigger layout change for list visibility
*/
public readonly listVisibilityChanges: BehaviorSubject<boolean> = new BehaviorSubject(this.listVisible);
/**
* track changed on accept attribute
*/
public readonly acceptChanges: Observable<string> = this.acceptChanged.asObservable();
/**
* emit an event every time user programmatically ask for certain event
*/
public readonly eventsChanges: Observable<FileEvent> = this.eventsChanged.asObservable();
/**
* track changed on multiple attribute
*/
public readonly multipleChanges: Observable<boolean> = this.multipleChanged.asObservable();
/**
* track which files were discarded
*/
public readonly discardedValueChanges: Observable<Array<ValidationError>> = this.discardedValue.asObservable();
constructor(configuration?: IFileUploadControlConfiguration, validators?: ValidatorFn | Array<ValidatorFn>) {
this.initialState(configuration);
this.defineValidators(validators);
}
/**
* set functions that determines the synchronous validity of this control.
*/
public setValidators(newValidators: ValidatorFn | Array<ValidatorFn>): this {
this.defineValidators(newValidators);
this.validate();
return this;
}
public addFile(file: File): this {
return this.addMultipleFiles([file]);
}
public removeFile(file: File): this {
if (!this.disabled) {
this.files.delete(file.name);
this.validate();
this.valueChanges.next(Array.from(this.files.values()));
}
return this;
}
public addFiles(files: FileList): this {
return this.addMultipleFiles(Array.from(files));
}
public get valid(): boolean {
return this.errors.length === 0 && this.status !== STATUS.DISABLED;
}
public get invalid(): boolean {
return this.errors.length > 0;
}
public getError(): Array<ValidationErrors> {
return this.errors;
}
/**
* number of uploaded files
*/
public get size(): number {
return this.files.size;
}
/**
* return list of Files
*/
public get value(): Array<File> {
return Array.from(this.files.values());
}
public setValue(files: Array<File>): this {
this.files.clear();
if (files instanceof Array) {
this.addMultipleFiles(files);
} else {
throw Error(`FormControl.setValue was provided with wrong argument type, ${files} was provided instead Array<File>`);
}
return this;
}
/**
* reset the control
*/
public clear(): this {
this.files.clear();
this.validate();
this.valueChanges.next(Array.from(this.files.values()));
return this;
}
public get isListVisible(): boolean {
return this.listVisible;
}
public setListVisibility(isVisible: boolean = true): this {
this.listVisible = isVisible;
this.listVisibilityChanges.next(this.listVisible);
return this;
}
public get disabled() {
return this.status === STATUS.DISABLED;
}
public enable(isEnabled: boolean = true): this {
this.status = isEnabled ? STATUS.VALID : STATUS.DISABLED;
this.validate();
this.statusChanged.next(this.status);
return this;
}
public disable(isDisabled: boolean = true): this {
this.status = isDisabled ? STATUS.DISABLED : STATUS.VALID;
this.validate();
this.statusChanged.next(this.status);
return this;
}
public click(): this {
this.eventsChanged.next(FileEvent.click);
return this;
}
public focus(): this {
this.eventsChanged.next(FileEvent.focus);
return this;
}
public blur(): this {
this.eventsChanged.next(FileEvent.blur);
return this;
}
/**
* specifies the types of files that the server accepts
*
* ### Example
*
* ```
* acceptFiles("file_extension|audio/*|video/*|image/*|media_type")
* ```
*
* To specify more than one value, separate the values with a comma (e.g. acceptFiles("audio/*,video/*,image/*").
*
*/
public acceptFiles(accept: string): this {
this.accept = accept;
this.acceptChanged.next(this.accept);
return this;
}
public acceptAll(): this {
this.accept = null;
this.acceptChanged.next(this.accept);
return this;
}
public get isMultiple(): boolean {
return this.multipleEnabled;
}
public multiple(isEnabled: boolean = true): this {
this.multipleEnabled = isEnabled;
this.multipleChanged.next(this.multipleEnabled);
return this;
}
public native(isNativeBehaviorEnabled: boolean = true): this {
this.nativeBehavior = isNativeBehaviorEnabled;
return this;
}
public discardInvalid(discard: boolean = true): this {
this.discard = discard;
return this;
}
private initialState(configuration: IFileUploadControlConfiguration = {}): void {
if (IsNullOrEmpty(configuration)) {
return;
}
/**
* Toggles discard of all invalid files
* it depends to accept, limit, size once a file
* dropped or selected it will be discarded if does not satisfy the constraint
*/
this.discard = configuration.discardInvalid || this.discard;
this.status = !!configuration.disabled ? STATUS.DISABLED : this.status;
this.multipleEnabled = configuration.multiple || this.multipleEnabled;
this.nativeBehavior = configuration.native != null ? configuration.native : this.nativeBehavior;
if (!IsNullOrEmpty(configuration.listVisible)) {
this.setListVisibility(configuration.listVisible);
}
if (!IsNullOrEmpty(configuration.accept)) {
this.acceptFiles(configuration.accept.join(','));
}
}
private defineValidators(validators: ValidatorFn | Array<ValidatorFn>): void {
if (!IsNullOrEmpty(validators)) {
this.validators = Array.isArray(validators) ? [...validators] : [validators];
}
}
/**
* @internal
* used to prevent valueChanges emit more times
* when multiple files are uploaded
*/
private addMultipleFiles(files: Array<File>): this {
if (IsNullOrEmpty(files)) {
this.validate();
this.valueChanges.next(Array.from(this.files.values()));
return this;
}
/**
* native component deletes the list of files before adding new ones
*/
if (this.nativeBehavior !== false) {
this.files.clear();
}
if (!this.multipleEnabled) {
/**
* if multiple is disabled and one file exists
* clear it and reupload a new one
*/
if (this.files.size === 1) {
this.files.clear();
}
// add only one file
this.files.set(files[0].name, files[0]);
} else {
// replace files with same name
files.forEach(file => this.files.set(file.name, file));
}
if (this.discard) {
this.analyzeToDiscard();
} else {
this.validate();
}
this.valueChanges.next(Array.from(this.files.values()));
return this;
}
/**
* method used to discard invalid files
*/
private analyzeToDiscard(): void {
const deletedFiles: Array<ValidationError> = [];
const validators = [...this.validators];
while (validators.length) {
const validator = validators.shift();
const error = validator(this);
if (error) {
this.discardFile(error, deletedFiles);
}
}
if (deletedFiles.length) {
this.discardedValue.next(deletedFiles);
}
}
private discardFile(error: ValidationErrors, deletedFiles: Array<ValidationError>) {
const errorsKey = Object.keys(error)[0];
const errors = error[errorsKey];
(Array.isArray(errors) ? errors : [errors]).forEach(fileError => {
if (fileError.file && this.files.has(fileError.file.name)) {
deletedFiles.push(fileError);
this.files.delete(fileError.file.name);
} else {
this.errors.push(error);
}
});
}
private validate(): void {
if (this.status !== STATUS.DISABLED) {
const currentState = this.valid;
this.errors = this.validators.map((validator) => validator(this)).filter((isInvalid) => isInvalid);
if (currentState !== this.valid) {
this.statusChanged.next(this.valid ? STATUS.VALID : STATUS.INVALID);
}
} else {
this.errors.length = 0;
}
}
} | the_stack |
import EventEmitter from "eventemitter3";
import * as React from "react";
import { useState, useEffect, useRef } from "react";
import {
Stack,
Spinner,
SpinnerSize,
DetailsList,
Selection,
SelectionMode,
IColumn,
Dropdown,
PrimaryButton,
DefaultButton,
Toggle,
Dialog,
DialogType,
DialogFooter,
TextField,
Checkbox,
IconButton,
ActionButton
} from "@fluentui/react";
import { UIState } from "../index";
import { ConfigTuners, ChannelType } from "../../../api";
const configAPI = "/api/config/tuners";
interface Item {
key: string;
enable: JSX.Element;
name: JSX.Element;
types: JSX.Element;
options: JSX.Element;
controls: JSX.Element;
}
const columns: IColumn[] = [
{
key: "col-enable",
name: "Enable",
fieldName: "enable",
minWidth: 44,
maxWidth: 44
},
{
key: "col-name",
name: "Name",
fieldName: "name",
minWidth: 0,
maxWidth: 70
},
{
key: "col-types",
name: "Types",
fieldName: "types",
minWidth: 60,
maxWidth: 105
},
{
key: "col-options",
name: "Options",
fieldName: "options",
minWidth: 340,
// maxWidth: 400
},
{
key: "col-controls",
name: "",
fieldName: "controls",
minWidth: 120,
maxWidth: 120
}
];
const dummySelection = new Selection(); // dummy
const typesIndex = ["GR", "BS", "CS", "SKY"];
function sortTypes(types: ChannelType[]): ChannelType[] {
return types.sort((a, b) => typesIndex.indexOf(a) - typesIndex.indexOf(b));
}
const Configurator: React.FC<{ uiState: UIState, uiStateEvents: EventEmitter }> = ({ uiState, uiStateEvents }) => {
const [current, setCurrent] = useState<ConfigTuners>(null);
const [editing, setEditing] = useState<ConfigTuners>(null);
const [showSaveDialog, setShowSaveDialog] = useState<boolean>(false);
const [saved, setSaved] = useState<boolean>(false);
const listContainerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (saved === true) {
setTimeout(() => {
uiStateEvents.emit("notify:restart-required");
}, 500);
setSaved(false);
return;
}
(async () => {
try {
const res = await (await fetch(configAPI)).json();
console.log("TunersConfigurator", "GET", configAPI, "->", res);
setEditing(JSON.parse(JSON.stringify(res)));
setCurrent(JSON.parse(JSON.stringify(res)));
} catch (e) {
console.error(e);
}
})();
}, [saved]);
const items = [];
editing?.forEach((tuner, i) => {
const item: Item = {
key: `item${i}`,
enable: (
<Toggle
checked={!tuner.isDisabled}
onChange={(ev, checked) => {
tuner.isDisabled = !checked;
setEditing([...editing]);
}}
style={{ marginTop: 6 }}
/>
),
name: (
<TextField
value={tuner.name}
onChange={(ev, newValue) => {
tuner.name = newValue;
setEditing([...editing]);
}}
/>
),
types: (
<Dropdown
styles={{ root: { display: "inline-block", minWidth: 70 } }}
multiSelect
options={[
{ key: "GR", text: "GR" },
{ key: "BS", text: "BS" },
{ key: "CS", text: "CS" },
{ key: "SKY", text: "SKY" }
]}
selectedKeys={tuner.types}
onChange={(ev, option) => {
if (option.selected === true) {
tuner.types.push(option.key as any);
tuner.types = sortTypes(tuner.types);
} else {
tuner.types = tuner.types.filter(type => type !== option.key);
}
setEditing([...editing]);
}}
/>
),
options: (
<Stack tokens={{ childrenGap: "8 0" }}>
{!tuner.remoteMirakurunHost && (
<>
<TextField
label="Command:"
value={tuner.command || ""}
onChange={(ev, newValue) => {
if (newValue === "") {
delete tuner.command;
} else {
tuner.command = newValue;
}
setEditing([...editing]);
}}
/>
<TextField
label="DVB Device Path:"
value={tuner.dvbDevicePath || ""}
onChange={(ev, newValue) => {
if (newValue === "") {
delete tuner.dvbDevicePath;
} else {
tuner.dvbDevicePath = newValue;
}
setEditing([...editing]);
}}
/>
</>
)}
{!tuner.command && (
<Stack horizontal tokens={{ childrenGap: "0 8" }}>
<TextField
label="Remote Mirakurun Host:"
value={tuner.remoteMirakurunHost || ""}
onChange={(ev, newValue) => {
if (newValue === "") {
delete tuner.remoteMirakurunHost;
} else if (/^[0-9a-z\.]+$/.test(newValue)) {
tuner.remoteMirakurunHost = newValue;
}
setEditing([...editing]);
}}
/>
<TextField
style={{ width: 55 }}
label="Port:"
placeholder="40772"
value={`${tuner.remoteMirakurunPort || ""}`}
onChange={(ev, newValue) => {
if (newValue === "") {
delete tuner.remoteMirakurunPort;
} else if (/^[0-9]+$/.test(newValue)) {
const port = parseInt(newValue, 10);
if (port <= 65535 && port > 0) {
tuner.remoteMirakurunPort = port;
}
}
setEditing([...editing]);
}}
/>
<Checkbox
styles={{ root: { marginTop: 34 } }}
label="Decode"
checked={tuner.remoteMirakurunDecoder || false}
onChange={(ev, checked) => {
if (checked) {
tuner.remoteMirakurunDecoder = true;
} else {
delete tuner.remoteMirakurunDecoder;
}
setEditing([...editing]);
}}
/>
</Stack>
)}
{(!tuner.remoteMirakurunHost || !tuner.remoteMirakurunDecoder) && (
<TextField
label="Decoder:"
value={tuner.decoder || ""}
onChange={(ev, newValue) => {
if (newValue === "") {
delete tuner.decoder;
} else {
tuner.decoder = newValue;
}
setEditing([...editing]);
}}
/>
)}
</Stack>
),
controls: (
<Stack horizontal horizontalAlign="end">
<IconButton
disabled={i === 0}
style={{ opacity: i === 0 ? 0 : 1 }}
title="Up"
iconProps={{ iconName: "Up" }}
onClick={() => {
editing.splice(i, 1);
editing.splice(i - 1, 0, tuner);
setEditing([...editing]);
}}
/>
<IconButton
disabled={i === editing.length - 1}
style={{ opacity: i === editing.length - 1 ? 0 : 1 }}
title="Down"
iconProps={{ iconName: "Down" }}
onClick={() => {
editing.splice(i, 1);
editing.splice(i + 1, 0, tuner);
setEditing([...editing]);
}}
/>
<IconButton
title="Controls"
iconProps={{ iconName: "More" }}
menuProps={{ items: [{
key: "remove",
text: "Remove Tuner",
iconProps: { iconName: "Delete" },
onClick: () => {
editing.splice(i, 1);
setEditing([...editing]);
}
}] }}
/>
</Stack>
)
};
//
items.push(item);
});
const changed = JSON.stringify(current) !== JSON.stringify(editing);
if (listContainerRef.current) {
listContainerRef.current.style.maxHeight = "calc(100vh - 410px)";
}
return (
<>
{!current && <Spinner size={SpinnerSize.large} />}
{editing &&
<Stack tokens={{ childrenGap: "8 0" }}>
<Stack.Item>
<ActionButton
text="Add Tuner"
iconProps={{ iconName: "Add" }}
onClick={() => {
const i = editing.length;
editing.push({
name: `adapter${i}`,
types: [],
command: `dvbv5-zap -a ${i} -c ./config/dvbconf-for-isdb/conf/dvbv5_channels_isdbs.conf -r -P <channel>`,
dvbDevicePath: `/dev/dvb/adapter${i}/dvr0`,
decoder: "arib-b25-stream-test",
isDisabled: true
});
setEditing([...editing]);
setTimeout(() => {
listContainerRef.current.scrollTop = listContainerRef.current.scrollHeight;
}, 0);
}}
/>
</Stack.Item>
<div ref={listContainerRef} style={{ overflowY: "scroll" }}>
<DetailsList
setKey="items"
items={items}
columns={columns}
selection={dummySelection}
selectionMode={SelectionMode.none}
/>
</div>
<Stack horizontal tokens={{ childrenGap: "0 8" }} style={{ marginTop: 16 }}>
<PrimaryButton text="Save" disabled={!changed} onClick={() => setShowSaveDialog(true)} />
<DefaultButton text="Cancel" disabled={!changed} onClick={() => setEditing(JSON.parse(JSON.stringify(current)))} />
</Stack>
</Stack>
}
<Dialog
hidden={!showSaveDialog}
onDismiss={() => setShowSaveDialog(false)}
dialogContentProps={{
type: DialogType.largeHeader,
title: "Save",
subText: "Restart is required to apply configuration."
}}
>
<DialogFooter>
<PrimaryButton
text="Save"
onClick={() => {
setShowSaveDialog(false);
(async () => {
console.log("TunersConfigurator", "PUT", configAPI, "<-", editing);
await fetch(configAPI, {
method: "PUT",
headers: { "Content-Type": "application/json; charset=utf-8" },
body: JSON.stringify(editing)
});
setSaved(true);
})();
}}
/>
<DefaultButton
text="Cancel"
onClick={() => setShowSaveDialog(false)}
/>
</DialogFooter>
</Dialog>
</>
);
};
export default Configurator; | the_stack |
import {
JSONValue
} from '@lumino/coreutils';
import {
IApplication, IStatefulService
} from './app';
import {
AsyncRemote, asyncRemoteMain
} from '../asyncremote';
import {
ISettingRegistry
} from '@jupyterlab/settingregistry';
import {
IDataConnector
} from '@jupyterlab/statedb';
import {
IService
} from './main';
import * as path from 'path';
import * as fs from 'fs';
import log from 'electron-log';
export
interface ISaveOptions {
id: string;
raw: string;
}
export
interface IElectronDataConnector extends IDataConnector<ISettingRegistry.IPlugin, string> { }
export
namespace IElectronDataConnector {
export
let fetch: AsyncRemote.IMethod<string, ISettingRegistry.IPlugin> = {
id: 'JupyterLabDataConnector-fetch'
};
export
let save: AsyncRemote.IMethod<ISaveOptions, void> = {
id: 'JupyterLabDataConnector-save'
};
}
/**
* Create a data connector to be used by the render
* processes. Stores JupyterLab plugin settings that
* need to be persistent.
*
* If settings are not found in the apllication data
* directory, default settings are read in from the
* application bundle.
*/
export
class JupyterLabDataConnector implements IStatefulService, IElectronDataConnector {
SCHEMAS_PATH: string = path.join(__dirname, '../../schemas/');
id: string = 'JupyterLabSettings';
constructor(app: IApplication) {
this._availableSchemas = this._getAllDefaultSchemas();
this._settings = app.registerStatefulService(this)
.then((settings: Private.IPluginData) => {
if (!settings) {
return this._availableSchemas.then(schemas => this._getDefaultSettings(schemas));
}
return settings;
})
.catch(() => {
return this._availableSchemas.then(schemas => this._getDefaultSettings(schemas));
});
// Create 'fetch' remote method
asyncRemoteMain.registerRemoteMethod(IElectronDataConnector.fetch, this.fetch.bind(this));
// Create 'save' remote method
asyncRemoteMain.registerRemoteMethod(IElectronDataConnector.save,
(opts: ISaveOptions) => {
return this.save(opts.id, opts.raw);
});
}
/**
* Fetch settings for a plugin.
*
* @param id The plugin id.
*/
fetch(id: string): Promise<ISettingRegistry.IPlugin> {
return this._settings
.then(data => {
if (!data[id]) {
return this._availableSchemas.then(schemas => {
if (id in schemas) {
return this._loadSingleDefault(schemas[id], id).then(pluginDefault => {
data[id] = pluginDefault;
return pluginDefault;
});
} else {
return Promise.reject(new Error('Setting ' + id + ' not available'));
}
});
} else {
return Promise.resolve({
id: id,
...data[id]
});
}
}).catch((reason) => {
return Promise.reject(new Error(`Private data store failed to load.`));
});
}
list(query?: string): Promise<{
ids: string[];
values: ISettingRegistry.IPlugin[];
}> {
return Promise.resolve({
ids: [],
values: []
});
}
/**
* Remove a setting. Not needed in this implementation.
*
* @param id The plugin id.
*/
remove(id: string): Promise<void> {
return Promise.reject(new Error('Removing setting resources is note supported.'));
}
/**
* Save user settings for a plugin.
*
* @param id
* @param user
*/
save(id: string, raw: string): Promise<void> {
const user = JSON.parse(raw);
let saving = this._settings
.then(data => {
if (!user[id]) {
return this._availableSchemas.then(schemas => {
if (id in schemas) {
return this._loadSingleDefault(schemas[id], id).then(pluginDefault => {
pluginDefault.data = user as ISettingRegistry.ISettingBundle;
pluginDefault.raw = raw;
data[id] = pluginDefault;
return data;
});
} else {
return Promise.reject(new Error('Setting ' + id + ' not available'));
}
});
} else {
data[id].data = user as ISettingRegistry.ISettingBundle;
data[id].raw = raw;
return Promise.resolve(data);
}
});
this._settings = saving;
return saving.then(() => { return; });
}
getStateBeforeQuit(): Promise<JSONValue> {
return this._settings;
}
verifyState(state: Private.IPluginData): boolean {
for (let key in state) {
if (state[key].schema === undefined || state[key].data === undefined) {
return false;
}
}
return true;
}
/**
* Get default JupyterLab settings from application
* bundle.
*/
private _getDefaultSettings(schemaPaths: Private.ISchemaPathContainer): Promise<Private.IPluginData> {
let buildRegistryPlugins: Promise<ISettingRegistry.IPlugin[]> = Promise.all(Object.keys(schemaPaths).map(schemaID => {
let schemaPath = schemaPaths[schemaID];
return this._loadSingleDefault(schemaPath, schemaID);
}));
return buildRegistryPlugins.then((settings: ISettingRegistry.IPlugin[]) => {
let iSettings: Private.IPluginData = {};
settings.forEach(setting => {
if (!setting) {
return;
}
iSettings[setting.id] = setting;
});
return iSettings;
}).catch((e) => {
log.error(e);
return Promise.resolve({});
});
}
private _loadSingleDefault(schemaPath: string, schemaID: string): Promise<ISettingRegistry.IPlugin> {
return new Promise<ISettingRegistry.IPlugin>((resolve, reject) => {
fs.readFile(schemaPath, (err, data: Buffer) => {
if (err) {
reject(err);
} else {
let rawSchema = data.toString();
resolve({
id: schemaID,
schema: JSON.parse(rawSchema),
data: {} as ISettingRegistry.ISettingBundle,
raw: '{}',
version: ''
});
}
});
});
}
private _getAllDefaultSchemas(): Promise<Private.ISchemaPathContainer> {
let getSettingProviders = this._readDirectoryFilenames(this.SCHEMAS_PATH);
let buildPluginProvider: Promise<{ provider: string, name: string }[]> = getSettingProviders.then(providers => {
return Promise.all(providers.map(provider => {
return this._readDirectoryFilenames(path.join(this.SCHEMAS_PATH, provider)).then(plugins => {
return plugins.map(plugin => {
return {
provider: provider,
name: plugin
};
});
});
})).then(nestedPlugins => {
return Array.prototype.concat.apply([], nestedPlugins);
});
});
return buildPluginProvider.then(plugins => {
return Promise.all(plugins.map(plugin => {
return this._readDirectoryFilenames(path.join(this.SCHEMAS_PATH, plugin.provider, plugin.name)).then(settingFiles => {
let allPlugins = settingFiles.map(settingFile => {
let schemaPath = path.join(this.SCHEMAS_PATH, plugin.provider, plugin.name, settingFile);
let id = plugin.provider + '/' + plugin.name + ':' + path.basename(settingFile, '.json');
return {
path: schemaPath, id
};
});
return allPlugins;
});
})).then(nestPlugins => {
let flattenedPlugins: { path: string, id: string }[] = Array.prototype.concat.apply([], nestPlugins);
let schemaContainer = {} as Private.ISchemaPathContainer;
flattenedPlugins.forEach(plugin => {
schemaContainer[plugin.id] = plugin.path;
});
return schemaContainer;
});
});
}
private _readDirectoryFilenames(directoryPath: string): Promise<string[]> {
return new Promise((resolve, reject) => {
fs.readdir(directoryPath, (err, filenames) => {
if (err) {
reject(err);
} else {
resolve(filenames);
}
});
});
}
private _availableSchemas: Promise<Private.ISchemaPathContainer>;
private _settings: Promise<Private.IPluginData>;
}
namespace Private {
export
interface IPluginData {
[id: string]: ISettingRegistry.IPlugin;
}
export
interface ISchemaPathContainer {
[id: string]: string;
}
}
let service: IService = {
requirements: ['IApplication'],
provides: 'IElectronDataConnector',
activate: (app: IApplication): IDataConnector<ISettingRegistry.IPlugin, string> => {
return new JupyterLabDataConnector(app);
},
autostart: true
};
export default service; | the_stack |
import { isQuotedString, rmEscapes, parseArgs, getAt } from '@formkit/utils'
import { warn, error } from './errors'
/**
* Tokens are strings that map to functions.
* @internal
*/
interface FormKitTokens {
[index: string]: (...args: any[]) => any
}
/**
* The compiler output, a function that adds the required tokens.
* @public
*/
export interface FormKitCompilerOutput {
(tokens?: Record<string, any>): boolean | number | string
provide: FormKitCompilerProvider
}
/**
* A function that accepts a callback with a token as the only argument, and
* must return a function that provides the true value of the token.
* @public
*/
export type FormKitCompilerProvider = (
callback: (requirements: string[]) => Record<string, () => any>
) => FormKitCompilerOutput
/**
* Logical operations are always a left/right fn
* @internal
*/
type LogicOperator = (
l: any,
r: any,
t?: Record<string, any>,
tt?: any
) => boolean | number | string
/**
* A set of logical operators used for parsing string logic.
* @internal
*/
interface LogicOperators {
[index: string]: LogicOperator
}
/**
* Describes a registry of operators that occur at different periods during
* the order of operations. Typically this is:
* 0: Boolean
* 1: Comparison
* 2: Arithmetic
*/
type OperatorRegistry = LogicOperators[]
/**
* Compiles a logical string like "a != z || b == c" into a single function.
* The return value is an object with a "provide" method that iterates over all
* requirement tokens to use as replacements.
* ```typescript
* let name = {
* value: 'jon'
* }
* const condition = compile("$name == 'bob'").provide((token) => {
* return () => name.value // must return a function!
* })
*
* condition() // false
* ```
* @param expr - A string to compile
* @returns
* @public
*/
export function compile(expr: string): FormKitCompilerOutput {
/**
* These tokens are replacements used in evaluating a given condition.
*/
// const tokens: FormKitTokens = {}
/**
* The value of the provide() callback. Used for late binding.
*/
let provideTokens: (requirements: string[]) => Record<string, () => any>
/**
* These are token requirements like "$name.value" that are need to fulfill
* a given condition call.
*/
const requirements = new Set<string>()
/**
* Expands the current value if it is a function.
* @param operand - A left or right hand operand
* @returns
*/
const x = function expand(operand: any, tokens?: Record<string, any>): any {
return typeof operand === 'function' ? operand(tokens) : operand
}
/**
* Comprehensive list of operators. This list MUST be
* ordered by the length of the operator characters in descending order.
*/
const operatorRegistry: OperatorRegistry = [
{
'&&': (l, r, t) => x(l, t) && x(r, t),
'||': (l, r, t) => x(l, t) || x(r, t),
},
{
'===': (l, r, t) => !!(x(l, t) === x(r, t)),
'!==': (l, r, t) => !!(x(l, t) !== x(r, t)),
'==': (l, r, t) => !!(x(l, t) == x(r, t)),
'!=': (l, r, t) => !!(x(l, t) != x(r, t)),
'>=': (l, r, t) => !!(x(l, t) >= x(r, t)),
'<=': (l, r, t) => !!(x(l, t) <= x(r, t)),
'>': (l, r, t) => !!(x(l, t) > x(r, t)),
'<': (l, r, t) => !!(x(l, t) < x(r, t)),
},
{
'+': (l, r, t) => x(l, t) + x(r, t),
'-': (l, r, t) => x(l, t) - x(r, t),
},
{
'*': (l, r, t) => x(l, t) * x(r, t),
'/': (l, r, t) => x(l, t) / x(r, t),
'%': (l, r, t) => x(l, t) % x(r, t),
},
]
/**
* A full list of all operator symbols.
*/
const operatorSymbols = operatorRegistry.reduce((s, g) => {
return s.concat(Object.keys(g))
}, [] as string[])
/**
* An array of the first character of each operator.
*/
const operatorChars = new Set(operatorSymbols.map((key) => key.charAt(0)))
/**
* Determines if the current character is the start of an operator symbol, if it
* is, it returns that symbol.
* @param symbols - An array of symbols that are considered operators
* @param char - The current character being operated on
* @param p - The position of the pointer
* @param expression - The full string expression
* @returns
*/
function getOp(
symbols: string[],
char: string,
p: number,
expression: string
): false | undefined | string {
const candidates = symbols.filter((s) => s.startsWith(char))
if (!candidates.length) return false
return candidates.find((symbol) => {
if (expression.length >= p + symbol.length) {
const nextChars = expression.substring(p, p + symbol.length)
if (nextChars === symbol) return symbol
}
return false
})
}
/**
* Determines the step number of the right or left hand operator.
* @param p - The position of the pointer
* @param expression - The full string expression
* @param direction - 1 = right, 0 = left
*/
function getStep(p: number, expression: string, direction = 1): number {
let next = direction
? expression.substring(p + 1).trim()
: expression.substring(0, p).trim()
if (!next.length) return -1
if (!direction) {
// left hand direction could include a function name we need to remove
const reversed = next.split('').reverse()
const start = reversed.findIndex((char) => operatorChars.has(char))
next = reversed.slice(start).join('')
}
const char = next[0]
return operatorRegistry.findIndex((operators) => {
const symbols = Object.keys(operators)
return !!getOp(symbols, char, 0, next)
})
}
/**
* Extracts a tail call. For example:
* ```
* $foo().bar(baz) + 7
* ```
* Would extract "bar(baz)" and return p of 15 (after the (baz)).
*
* @param p - The position of a closing parenthetical.
* @param expression - The full expression being parsed.
*/
function getTail(pos: number, expression: string): [tail: string, p: number] {
let tail = ''
const length = expression.length
let depth = 0
for (let p = pos; p < length; p++) {
const char = expression.charAt(p)
if (char === '(') {
depth++
} else if (char === ')') {
depth--
} else if (depth === 0 && char === ' ') {
continue
}
if (depth === 0 && getOp(operatorSymbols, char, p, expression)) {
return [tail, p - 1]
} else {
tail += char
}
}
return [tail, expression.length - 1]
}
/**
* Parse a string expression into a function that returns a boolean. This is
* the magic behind schema logic like $if.
* @param expression - A string expression to parse
* @returns
*/
function parseLogicals(
expression: string,
step = 0
): () => boolean | number | string {
const operators = operatorRegistry[step]
const length = expression.length
const symbols = Object.keys(operators)
let depth = 0
let quote: false | string = false
let op: null | ((l: any, r: any) => boolean | number | string) = null
let operand: string | number | boolean | (() => boolean | number | string) =
''
let left: null | ((r?: any) => boolean | number | string) = null
let operation: false | undefined | string
let lastChar = ''
let char = ''
let parenthetical = ''
let parenQuote: false | string = ''
let startP = 0
const addTo = (depth: number, char: string) => {
depth ? (parenthetical += char) : (operand += char)
}
for (let p = 0; p < length; p++) {
lastChar = char
char = expression.charAt(p)
if (
(char === "'" || char === '"') &&
lastChar !== '\\' &&
((depth === 0 && !quote) || (depth && !parenQuote))
) {
if (depth) {
parenQuote = char
} else {
quote = char
}
addTo(depth, char)
continue
} else if (
(quote && (char !== quote || lastChar === '\\')) ||
(parenQuote && (char !== parenQuote || lastChar === '\\'))
) {
addTo(depth, char)
continue
} else if (quote === char) {
quote = false
addTo(depth, char)
continue
} else if (parenQuote === char) {
parenQuote = false
addTo(depth, char)
continue
} else if (char === ' ') {
continue
} else if (char === '(') {
if (depth === 0) {
startP = p
} else {
parenthetical += char
}
depth++
} else if (char === ')') {
depth--
if (depth === 0) {
// Parenthetical statements cannot be grouped up in the implicit order
// of left/right statements based on which step they are on because
// they are parsed on every step and then must be applied to the
// operator. Example:
//
// 5 + (3) * 2
//
// This should yield 11 not 16. This order is normally implicit in the
// sequence of operators being parsed, but with parenthesis the parse
// happens each time. Instead we need to know if the resulting value
// should be applied to the left or the right hand operator. The
// general algorithm is:
//
// 1. Does this paren have an operator on the left or right side
// 2. If not, it's unnecessarily wrapped (3 + 2)
// 3. If it does, then which order of operation is highest?
// 4. Wait for the highest order of operation to bind to an operator.
// If the parenthetical has a preceding token like $fn(1 + 2) then we
// need to subtract the existing operand length from the start
// to determine if this is a left or right operation
const fn =
typeof operand === 'string' && operand.startsWith('$')
? operand
: undefined
const hasTail = fn && expression.charAt(p + 1) === '.'
// It's possible the function has a chained tail call:
let tail = ''
if (hasTail) {
;[tail, p] = getTail(p + 2, expression)
}
const lStep = op ? step : getStep(startP, expression, 0)
const rStep = getStep(p, expression)
if (lStep === -1 && rStep === -1) {
// This parenthetical was unnecessarily wrapped at the root, or
// these are args of a function call.
operand = evaluate(parenthetical, -1, fn, tail) as string
} else if (op && (lStep >= rStep || rStep === -1) && step === lStep) {
// has a left hand operator with a higher order of operation
left = op.bind(null, evaluate(parenthetical, -1, fn, tail))
op = null
operand = ''
} else if (rStep > lStep && step === rStep) {
// should be applied to the right hand operator when it gets one
operand = evaluate(parenthetical, -1, fn, tail) as string
} else {
operand += `(${parenthetical})${hasTail ? `.${tail}` : ''}`
}
parenthetical = ''
} else {
parenthetical += char
}
} else if (
depth === 0 &&
(operation = getOp(symbols, char, p, expression))
) {
if (p === 0) {
error(103, [operation, expression])
}
// We identified the operator by looking ahead in the string, so we need
// our position to move past the operator
p += operation.length - 1
if (p === expression.length - 1) {
error(104, [operation, expression])
}
if (!op) {
// Bind the left hand operand
if (left) {
// In this case we've already parsed the left hand operator
op = operators[operation].bind(null, evaluate(left, step))
left = null
} else {
op = operators[operation].bind(null, evaluate(operand, step))
operand = ''
}
} else if (operand) {
// Bind the right hand operand, and return the resulting expression as a new left hand operator
left = op.bind(null, evaluate(operand, step)) as () =>
| boolean
| number
| string
op = operators[operation].bind(null, left)
operand = ''
}
continue
} else {
addTo(depth, char)
}
}
if (operand && op) {
// If we were left with an operand after the loop, and an op, it should
// be the right hand assignment.
op = op.bind(null, evaluate(operand, step))
}
// If we don't have an op, but we do have a left hand assignment, then that
// is actually our operator, so just re-assign it to op
op = !op && left ? left : op
if (!op && operand) {
// If we don't have any op but we do have an operand so there is no boolean
// logic to perform, but that operand still means something so we need to
// evaluate it and return it as a function
op = (v: any, t: Record<string, any>): boolean => {
return typeof v === 'function' ? v(t) : v
}
op = op.bind(null, evaluate(operand, step))
}
if (!op && !operand) {
error(105, expression)
}
return op as () => boolean | number | string
}
/**
* Given a string like '$name==bobby' evaluate it to true or false
* @param operand - A left or right boolean operand — usually conditions
* @param step - The current order of operation
* @param fnToken - The token (string) representation of a function being called
* @returns
*/
function evaluate(
operand:
| string
| number
| boolean
| ((...args: any[]) => boolean | number | string),
step: number,
fnToken?: string,
tail?: string //eslint-disable-line
):
| boolean
| undefined
| string
| number
| ((...args: any[]) => boolean | number | string | CallableFunction) {
if (fnToken) {
const fn = evaluate(fnToken, operatorRegistry.length)
let userFuncReturn: unknown
// "Tail calls" are dot accessors after a function $foo().value. We need
// to compile tail calls, and then provide the function result to the
// exposed tokens.
let tailCall: false | FormKitCompilerOutput = tail
? compile(`$${tail}`)
: false
if (typeof fn === 'function') {
const args = parseArgs(String(operand)).map((arg: string) =>
evaluate(arg, -1)
)
return (tokens: Record<string, any>) => {
const userFunc = fn(tokens)
if (typeof userFunc !== 'function') {
warn(150, fnToken)
return userFunc
}
userFuncReturn = userFunc(
...args.map((arg) =>
typeof arg === 'function' ? arg(tokens) : arg
)
)
if (tailCall) {
tailCall = tailCall.provide((subTokens) => {
const rootTokens = provideTokens(subTokens)
const t = subTokens.reduce(
(tokenSet: Record<string, any>, token: string) => {
const isTail = token === tail || tail?.startsWith(`${token}(`)
if (isTail) {
const value = getAt(userFuncReturn, token)
tokenSet[token] = () => value
} else {
tokenSet[token] = rootTokens[token]
}
return tokenSet
},
{} as Record<string, any>
)
return t
})
}
return tailCall ? tailCall() : (userFuncReturn as string)
}
}
} else if (typeof operand === 'string') {
// the word true or false will never contain further operations
if (operand === 'true') return true
if (operand === 'false') return false
if (operand === 'undefined') return undefined
// Truly quotes strings cannot contain an operation, return the string
if (isQuotedString(operand))
return rmEscapes(operand.substring(1, operand.length - 1))
// Actual numbers cannot be contain an operation
if (!isNaN(+operand)) return Number(operand)
if (step < operatorRegistry.length - 1) {
return parseLogicals(operand, step + 1)
} else {
if (operand.startsWith('$')) {
const cleaned = operand.substring(1)
requirements.add(cleaned)
return function getToken(tokens: FormKitTokens) {
return cleaned in tokens ? tokens[cleaned]() : undefined
}
}
// In this case we are dealing with an unquoted string, just treat it
// as a plain string.
return operand
}
}
return operand
}
/**
* Compile the string.
*/
const compiled = parseLogicals(
expr.startsWith('$:') ? expr.substring(2) : expr
)
/**
* Convert compiled requirements to an array.
*/
const reqs = Array.from(requirements)
/**
* Provides token values via callback to compiled output.
* @param callback - A callback that needs to provide all token requirements
* @returns
*/
function provide(
callback: (requirements: string[]) => Record<string, () => any>
): FormKitCompilerOutput {
provideTokens = callback
return Object.assign(compiled.bind(null, callback(reqs)), {
provide,
})
}
return Object.assign(compiled, {
provide,
})
} | the_stack |
import Conditions from '../../../../../resources/conditions';
import NetRegexes from '../../../../../resources/netregexes';
import { Responses } from '../../../../../resources/responses';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { TriggerSet } from '../../../../../types/trigger';
export interface Data extends RaidbossData {
limitCutMap?: { [limitCutNumber: number]: string };
limitCutNumber?: number;
limitCutDelay?: number;
}
const triggerSet: TriggerSet<Data> = {
zoneId: ZoneId.AlexanderTheHeartOfTheCreatorSavage,
timelineFile: 'a11s.txt',
timelineTriggers: [
{
id: 'A11S Blastoff',
regex: /Blastoff/,
beforeSeconds: 5,
response: Responses.knockback(),
},
],
triggers: [
{
id: 'A11S Left Laser Sword',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Cruise Chaser', id: '1A7A', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Chaser-Mecha', id: '1A7A', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Croiseur-Chasseur', id: '1A7A', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'クルーズチェイサー', id: '1A7A', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '巡航驱逐者', id: '1A7A', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '순항추격기', id: '1A7A', capture: false }),
// Sorry tanks.
// We could figure out who is tanking and then do the opposite,
// but probably that could get confusing too?
// It seems better to just be consistent here and have tanks be smarter.
response: Responses.goRight(),
},
{
id: 'A11S Right Laser Sword',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Cruise Chaser', id: '1A79', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Chaser-Mecha', id: '1A79', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Croiseur-Chasseur', id: '1A79', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'クルーズチェイサー', id: '1A79', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '巡航驱逐者', id: '1A79', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '순항추격기', id: '1A79', capture: false }),
response: Responses.goLeft(),
},
{
id: 'A11S Optical Sight Clock',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Cruise Chaser', id: '1A6C', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Chaser-Mecha', id: '1A6C', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Croiseur-Chasseur', id: '1A6C', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'クルーズチェイサー', id: '1A6C', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '巡航驱逐者', id: '1A6C', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '순항추격기', id: '1A6C', capture: false }),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Clock',
de: 'Uhr',
fr: 'Sens horaire',
ja: '照準 (時針回り)',
cn: '九连环',
ko: '시계방향',
},
},
},
{
id: 'A11S Optical Sight Out',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Cruise Chaser', id: '1A6D', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Chaser-Mecha', id: '1A6D', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Croiseur-Chasseur', id: '1A6D', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'クルーズチェイサー', id: '1A6D', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '巡航驱逐者', id: '1A6D', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '순항추격기', id: '1A6D', capture: false }),
response: Responses.getOut('info'),
},
{
id: 'A11S Optical Sight Bait',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Cruise Chaser', id: '1A6E', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Chaser-Mecha', id: '1A6E', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Croiseur-Chasseur', id: '1A6E', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'クルーズチェイサー', id: '1A6E', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '巡航驱逐者', id: '1A6E', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '순항추격기', id: '1A6E', capture: false }),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Bait Optical Sight',
de: 'Köder Visier',
fr: 'Attirez la Visée optique',
ja: '照準AoEを誘導',
cn: '诱导AOE',
ko: '유도 장판',
},
},
},
{
id: 'A11S Super Hawk Blaster',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '005A' }),
condition: Conditions.targetIsYou(),
response: Responses.spread(),
},
{
id: 'A11S Whirlwind',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Cruise Chaser', id: '1A84', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Chaser-Mecha', id: '1A84', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Croiseur-Chasseur', id: '1A84', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'クルーズチェイサー', id: '1A84', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '巡航驱逐者', id: '1A84', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '순항추격기', id: '1A84', capture: false }),
response: Responses.aoe(),
},
{
id: 'A11S Spin Crusher',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Cruise Chaser', id: '1A85', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Chaser-Mecha', id: '1A85', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Croiseur-Chasseur', id: '1A85', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'クルーズチェイサー', id: '1A85', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '巡航驱逐者', id: '1A85', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '순항추격기', id: '1A85', capture: false }),
response: Responses.awayFromFront('info'),
},
{
id: 'A11S EDD Add',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatant({ name: 'E\\.D\\.D\\.', capture: false }),
netRegexDe: NetRegexes.addedCombatant({ name: 'E\\.D\\.D\\.-Mecha', capture: false }),
netRegexFr: NetRegexes.addedCombatant({ name: 'E\\.D\\.D\\.', capture: false }),
netRegexJa: NetRegexes.addedCombatant({ name: 'イーディーディー', capture: false }),
netRegexCn: NetRegexes.addedCombatant({ name: '护航机甲', capture: false }),
netRegexKo: NetRegexes.addedCombatant({ name: 'E\\.D\\.D\\.', capture: false }),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Kill Add',
de: 'Add besiegen',
fr: 'Tuez l\'Add',
ja: 'イーディーディーを倒す',
cn: '击杀小怪',
ko: '쫄 없애기',
},
},
},
{
id: 'A11S Armored Pauldron Add',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatant({ name: 'Armored Pauldron', capture: false }),
netRegexDe: NetRegexes.addedCombatant({ name: 'Schulterplatte', capture: false }),
netRegexFr: NetRegexes.addedCombatant({ name: 'Protection D\'Épaule', capture: false }),
netRegexJa: NetRegexes.addedCombatant({ name: 'ショルダーアーマー', capture: false }),
netRegexCn: NetRegexes.addedCombatant({ name: '肩部装甲', capture: false }),
netRegexKo: NetRegexes.addedCombatant({ name: '견갑부', capture: false }),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Break Pauldron',
de: 'Schulterplatte zerstören',
fr: 'Brisez la Protection',
ja: 'アーマーを破壊する',
cn: '击破护盾',
ko: '견갑부 부수기',
},
},
},
{
id: 'A11S GA-100',
type: 'StartsUsing',
// Note: 0057 headmarker, but starts using occurs 3 seconds earlier.
netRegex: NetRegexes.startsUsing({ source: 'Cruise Chaser', id: '1A77' }),
netRegexDe: NetRegexes.startsUsing({ source: 'Chaser-Mecha', id: '1A77' }),
netRegexFr: NetRegexes.startsUsing({ source: 'Croiseur-Chasseur', id: '1A77' }),
netRegexJa: NetRegexes.startsUsing({ source: 'クルーズチェイサー', id: '1A77' }),
netRegexCn: NetRegexes.startsUsing({ source: '巡航驱逐者', id: '1A77' }),
netRegexKo: NetRegexes.startsUsing({ source: '순항추격기', id: '1A77' }),
// TODO: maybe we need a Responses.abilityOn()
alarmText: (data, matches, output) => {
if (data.me !== matches.target)
return;
return output.gaOnYou!();
},
infoText: (data, matches, output) => {
if (data.me === matches.target)
return;
return output.gaOn!({ player: data.ShortName(matches.target) });
},
outputStrings: {
gaOn: {
en: 'GA-100 on ${player}',
de: 'GA-100 on ${player}',
fr: 'GA-100 sur ${player}',
ja: '${player}にGA-100',
cn: 'GA-100点${player}',
ko: '"${player}" GA-100',
},
gaOnYou: {
en: 'GA-100 on YOU',
de: 'GA-100 auf DIR',
fr: 'GA-100 sur VOUS',
ja: '自分にGA-100',
cn: 'GA-100点名',
ko: 'GA-100 대상자',
},
},
},
{
id: 'A11S Limit Cut Collect',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '00(?:4F|5[0-6])' }),
run: (data, matches) => {
const limitCutNumberMap: { [id: string]: number } = {
'004F': 1,
'0050': 2,
'0051': 3,
'0052': 4,
'0053': 5,
'0054': 6,
'0055': 7,
'0056': 8,
};
const limitCutNumber = limitCutNumberMap[matches.id];
if (!limitCutNumber)
return;
data.limitCutMap ??= {};
data.limitCutMap[limitCutNumber] = matches.target;
if (matches.target === data.me) {
data.limitCutNumber = limitCutNumber;
// Time between headmarker and mechanic.
const limitCutDelayMap: { [id: string]: number } = {
'004F': 8.8,
'0050': 9.3,
'0051': 11.0,
'0052': 11.5,
'0053': 13.2,
'0054': 13.7,
'0055': 15.5,
'0056': 16.0,
};
data.limitCutDelay = limitCutDelayMap[matches.id];
}
},
},
{
id: 'A11S Limit Cut Number',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '00(?:4F|5[0-6])' }),
condition: Conditions.targetIsYou(),
durationSeconds: (data) => data.limitCutDelay ?? 0,
infoText: (data, _matches, output) => output.text!({ num: data.limitCutNumber }),
outputStrings: {
text: {
en: '${num}',
de: '${num}',
fr: '${num}',
ja: '${num}',
cn: '${num}',
ko: '${num}',
},
},
},
{
id: 'A11S Limit Cut Mechanic',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '00(?:4F|5[0-6])' }),
condition: Conditions.targetIsYou(),
delaySeconds: (data) => (data.limitCutDelay ?? 0) - 5,
alertText: (data, _matches, output) => {
if (!data.limitCutNumber || !data.limitCutMap)
return;
if (data.limitCutNumber % 2 === 1) {
// Odds
return output.knockbackCleave!();
}
// Evens
const partner = data.limitCutMap[data.limitCutNumber - 1];
if (!partner) {
// In case something goes awry?
return output.knockbackCharge!();
}
return output.facePlayer!({ player: data.ShortName(partner) });
},
outputStrings: {
knockbackCleave: {
en: 'Knockback Cleave; Face Outside',
de: 'Rückstoß Cleave; nach Außen schauen',
fr: 'Poussée Cleave; Regardez vers l\'extérieur',
ja: 'ノックバック ソード; 外を向く',
cn: '击退顺劈; 面向外侧',
ko: '넉백 소드; 바깥쪽 바라보기',
},
knockbackCharge: {
en: 'Knockback Charge',
de: 'Rückstoß Charge',
fr: 'Poussée Charge',
ja: 'ノックバック チャージ',
cn: '击退冲锋',
ko: '넉백 차지',
},
facePlayer: {
en: 'Face ${player}',
de: 'Schaue zu ${player}',
fr: 'Regardez ${player}',
ja: '${player} に向かう',
cn: '面向${player}',
ko: '"${player}" 바라보기',
},
},
},
{
id: 'A11S Limit Cut Cleanup',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Cruise Chaser', id: '1A80', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Chaser-Mecha', id: '1A80', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Croiseur-Chasseur', id: '1A80', capture: false }),
netRegexJa: NetRegexes.ability({ source: 'クルーズチェイサー', id: '1A80', capture: false }),
netRegexCn: NetRegexes.ability({ source: '巡航驱逐者', id: '1A80', capture: false }),
netRegexKo: NetRegexes.ability({ source: '순항추격기', id: '1A80', capture: false }),
delaySeconds: 30,
run: (data) => {
delete data.limitCutDelay;
delete data.limitCutNumber;
delete data.limitCutMap;
},
},
{
id: 'A11S Laser X Sword',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Cruise Chaser', id: '1A7F' }),
netRegexDe: NetRegexes.startsUsing({ source: 'Chaser-Mecha', id: '1A7F' }),
netRegexFr: NetRegexes.startsUsing({ source: 'Croiseur-Chasseur', id: '1A7F' }),
netRegexJa: NetRegexes.startsUsing({ source: 'クルーズチェイサー', id: '1A7F' }),
netRegexCn: NetRegexes.startsUsing({ source: '巡航驱逐者', id: '1A7F' }),
netRegexKo: NetRegexes.startsUsing({ source: '순항추격기', id: '1A7F' }),
alertText: (data, matches, output) => {
if (data.me === matches.target)
return output.sharedTankbusterOnYou!();
if (data.role === 'tank' || data.role === 'healer' || data.job === 'BLU')
return output.sharedTankbusterOn!({ player: data.ShortName(matches.target) });
},
outputStrings: {
sharedTankbusterOnYou: {
en: 'Shared Tankbuster on YOU',
de: 'Geteilter Tankbuster auf DIR',
fr: 'Tank buster à partager sur VOUS',
ja: '自分に頭割りタンクバスター',
cn: '分摊死刑点名',
ko: '쉐어 탱버 대상자',
},
sharedTankbusterOn: {
en: 'Shared Tankbuster on ${player}',
de: 'Geteilter Tankbuster auf ${player}',
fr: 'Tank buster à partager sur ${player}',
ja: '${player}に頭割りタンクバスター',
cn: '分摊死刑点${player}',
ko: '"${player}" 쉐어 탱버',
},
},
},
{
id: 'A11S Propeller Wind',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Cruise Chaser', id: '1A7F', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Chaser-Mecha', id: '1A7F', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Croiseur-Chasseur', id: '1A7F', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'クルーズチェイサー', id: '1A7F', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '巡航驱逐者', id: '1A7F', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '순항추격기', id: '1A7F', capture: false }),
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Hide Behind Tower',
de: 'Hinter dem Tower verstecken',
fr: 'Cachez-vous derrière la tour',
ja: '塔の後ろに',
cn: '躲在塔后',
ko: '기둥 뒤에 숨기',
},
},
},
{
id: 'A11S Plasma Shield',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatant({ name: 'Plasma Shield', capture: false }),
netRegexDe: NetRegexes.addedCombatant({ name: 'Plasmaschild', capture: false }),
netRegexFr: NetRegexes.addedCombatant({ name: 'Bouclier Plasma', capture: false }),
netRegexJa: NetRegexes.addedCombatant({ name: 'プラズマシールド', capture: false }),
netRegexCn: NetRegexes.addedCombatant({ name: '等离子护盾', capture: false }),
netRegexKo: NetRegexes.addedCombatant({ name: '플라스마 방어막', capture: false }),
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Break Shield From Front',
de: 'Schild von vorne zerstören',
fr: 'Brisez le Bouclier par l\'avant',
ja: 'シールドを正面から破壊する',
cn: '正面击破护盾',
ko: '정면에서 방어막 부수기',
},
},
},
{
id: 'A11S Plasma Shield Shattered',
type: 'GameLog',
netRegex: NetRegexes.gameLog({ line: 'The plasma shield is shattered.*?', capture: false }),
response: Responses.spread(),
},
{
id: 'A11S Blassty Charge',
type: 'StartsUsing',
// The single post-shield charge. Not "super" blassty charge during limit cut.
netRegex: NetRegexes.startsUsing({ source: 'Cruise Chaser', id: '1A83' }),
netRegexDe: NetRegexes.startsUsing({ source: 'Chaser-Mecha', id: '1A83' }),
netRegexFr: NetRegexes.startsUsing({ source: 'Croiseur-Chasseur', id: '1A83' }),
netRegexJa: NetRegexes.startsUsing({ source: 'クルーズチェイサー', id: '1A83' }),
netRegexCn: NetRegexes.startsUsing({ source: '巡航驱逐者', id: '1A83' }),
netRegexKo: NetRegexes.startsUsing({ source: '순항추격기', id: '1A83' }),
alarmText: (data, matches, output) => {
if (data.me !== matches.target)
return;
return output.chargeOnYou!();
},
alertText: (data, matches, output) => {
if (data.me === matches.target)
return;
return output.chargeOn!({ player: data.ShortName(matches.target) });
},
outputStrings: {
chargeOn: {
en: 'Charge on ${player}',
de: 'Ansturm auf ${player}',
fr: 'Charge sur ${player}',
ja: '${player}にチャージ',
cn: '冲锋点${player}',
ko: '"${player}" 돌진',
},
chargeOnYou: {
en: 'Charge on YOU',
de: 'Ansturm auf DIR',
fr: 'Charge sur VOUS',
ja: '自分にチャージ',
cn: '冲锋点名',
ko: '돌진 대상자',
},
},
},
],
timelineReplace: [
{
'locale': 'de',
'replaceSync': {
'Armored Pauldron': 'Schulterplatte',
'Claster': 'Claster-Mecha',
'Cruise Chaser': 'Chaser-Mecha',
'E\\\\.D\\\\.D\\\\.': 'E\\.D\\.D\\.-Mecha',
'Multifield': 'Schichtfeld',
'Plasma Shield': 'Plasmaschild',
'The Main Generators': 'Hauptantriebsraum',
'The plasma shield is shattered': 'Die Schulterplatte ist zerstört',
},
'replaceText': {
'(?<! )Sword': 'Schwert',
'(?<!Super )Hawk Blaster': 'Jagdfalke',
'--invincible--': '--unverwundbar--',
'\\(bait\\)': '(ködern)',
'\\(clock/out\\)': '(im Uhrzeigersinn/Raus)',
'\\(everyone\\)': '(jeder)',
'\\(numbers\\)': '(Nummern)',
'\\(orbs\\)': '(Orbs)',
'\\(out/clock\\)': '(Raus/im Uhrzeigersinn)',
'\\(shield\\)': '(Schild)',
'\\?': ' ?',
'Assault Cannon': 'Sturmkanone',
'Blassty Blaster': 'Blassty-Blaster',
'Blassty Charge': 'Blassty-Ladung',
'Blastoff': 'Absprengen',
'(?<!Blassty )Charge': 'Sturm',
'E\\.D\\.D\\. Add': 'E.D.D.-Mecha Add',
'E\\.D\\.D\\. Armored Pauldron': 'E.D.D.-Mecha Schulterplatte',
'Eternal Darkness': 'Ewiges Dunkel',
'GA-100': 'GA-100',
'Lapis Lazuli': 'Lapislazuli',
'Laser X Sword': 'Laserschwert X',
'Left/Right Laser Sword': 'Linkes/Rechtes Laserschwert',
'Limit Cut': 'Grenzwertüberschreitung',
'Markers': 'Markierungen',
'Multifield': 'Schichtfeld',
'Optical Sight': 'Visier',
'Perfect Landing': 'Perfekte Landung',
'Photon': 'Photon',
'Plasma Shield': 'Plasmaschild',
'Plasmasphere': 'Plasmasphäre',
'Propeller Wind': 'Luftschraube',
'Spin Crusher': 'Rotorbrecher',
'Super Hawk Blaster': 'Super-Jagdfalke',
'Transform': 'Diamorphose',
'Whirlwind': 'Wirbelwind',
},
},
{
'locale': 'fr',
'replaceSync': {
'Armored Pauldron': 'Protection d\'épaule',
'Claster': 'Éclateur',
'Cruise Chaser': 'Croiseur-chasseur',
'E\\\\.D\\\\.D\\\\.': 'E\\.D\\.D\\.',
'Multifield': 'Champ multistrate',
'Plasma Shield': 'Bouclier plasma',
'The Main Generators': 'la chambre du générateur principal',
'The plasma shield is shattered.*?': 'Le bouclier plasma se brise.*?',
},
'replaceText': {
'(?<! )Sword': 'Épée',
'(?<!Super )Hawk Blaster': 'Canon faucon',
'--invincible--': '--invulnérable--',
'\\(bait\\)': '(attirez)',
'\\(clock/out\\)': '(sens horaire/extérieur)',
'\\(everyone\\)': '(tout les joueurs)',
'\\(numbers\\)': '(nombres)',
'\\(orbs\\)': '(orbes)',
'\\(out/clock\\)': '(extérieur/sens horaire)',
'\\(shield\\)': '(bouclier)',
'\\?': ' ?',
'Assault Cannon': 'Canon d\'assaut',
'Blassty Blaster': 'Canon Blassty',
'Blassty Charge': 'Charge Blassty',
'Blastoff': 'Lancement',
'(?<!Blassty )Charge': 'Charge',
'E\\.D\\.D\\. Add': 'Add E.D.D.',
'E\\.D\\.D\\. Armored Pauldron': 'E.D.D. Protection d\'épaule',
'Eternal Darkness': 'Ténèbres éternelles',
'GA-100': 'GA-100',
'Lapis Lazuli': 'Lapis-lazuli',
'Laser X Sword': 'Épée laser X',
'Left/Right Laser Sword': 'Épée laser gauche/droite',
'Limit Cut': 'Dépassement de limites',
'Markers': 'Marqueurs',
'Multifield': 'Champ multistrate',
'Optical Sight': 'Visée optique',
'Perfect Landing': 'Atterissage parfait',
'Photon': 'Photon',
'Plasma Shield': 'Bouclier plasma',
'Plasmasphere': 'Sphère de plasma',
'Propeller Wind': 'Vent turbine',
'Spin Crusher': 'Écrasement tournoyant',
'Super Hawk Blaster': 'Super canon faucon',
'Transform': 'Transformation',
'Whirlwind': 'Tornade',
},
},
{
'locale': 'ja',
'replaceSync': {
'Armored Pauldron': 'ショルダーアーマー',
'Claster': 'クラスター',
'Cruise Chaser': 'クルーズチェイサー',
'E\\\\.D\\\\.D\\\\.': 'イーディーディー',
'Multifield': '積層科学フィールド',
'Plasma Shield': 'プラズマシールド',
'The Main Generators': '中枢大動力室',
'The plasma shield is shattered': 'プラズマシールドが壊れた!',
},
'replaceText': {
'(?<! )Sword': 'ソード',
'(?<!Super )Hawk Blaster': 'ホークブラスター',
'--invincible--': '--インビンシブル--',
'\\(bait\\)': '(誘導)',
'\\(clock/out\\)': '(時針回り/外へ)',
'\\(everyone\\)': '(全員)',
'\\(numbers\\)': '(数字)',
'\\(offtank\\)': '(ST)',
'\\(orbs\\)': '(玉)',
'\\(out/clock\\)': '(外へ/時針回り)',
'\\(shield\\)': '(シールド)',
'\\?': ' ?',
'Assault Cannon': 'アサルトカノン',
'Blassty Blaster': 'ブラスティ・ブラスター',
'Blassty Charge': 'ブラスティ・チャージ',
'Blastoff': 'ブラストオフ',
'(?<!Blassty )Charge': 'チャージ',
'E\\.D\\.D\\. Add': '雑魚: イーディーディー',
'E\\.D\\.D\\. Armored Pauldron': 'イーディーディー ショルダーアーマー',
'Eternal Darkness': '暗黒の運命',
'GA-100': 'GA-100',
'Lapis Lazuli': 'ラピスラズリ',
'Laser X Sword': 'レーザーエックススウォード',
'Left/Right Laser Sword': '左/右 ソード',
'Limit Cut': 'リミッターカット',
'Markers': 'マーク',
'Multifield': '積層科学フィールド',
'Optical Sight': '照準',
'Perfect Landing': '着陸',
'Photon': 'フォトン',
'Plasma Shield': 'プラズマシールド',
'Plasmasphere': 'プラズマスフィア',
'Propeller Wind': 'プロペラウィンド',
'Spin Crusher': 'スピンクラッシャー',
'Super Hawk Blaster': 'スーパーホークブラスター',
'Transform': 'トランスフォーム・シューター',
'Whirlwind': '竜巻',
},
},
{
'locale': 'cn',
'replaceSync': {
'Armored Pauldron': '肩部装甲',
'Claster': '舰载浮游炮',
'Cruise Chaser': '巡航驱逐者',
'E\\\\.D\\\\.D\\\\.': '护航机甲',
'Multifield': '层积科学结界',
'Plasma Shield': '等离子护盾',
'The Main Generators': '中枢大动力室',
},
'replaceText': {
'(?<! )Sword': '剑 ',
'(?<!Super )Hawk Blaster': '鹰式破坏炮',
'--invincible--': '--无敌--',
'\\(bait\\)': '(诱导)',
'\\(clock/out\\)': '(顺时针/外)',
'\\(everyone\\)': '(全员)',
'\\(numbers\\)': '(麻将)',
'\\(orbs\\)': '(球)',
'\\(out/clock\\)': '(外/顺时针)',
'\\(shield\\)': '(护盾)',
'\\?': ' ?',
'Assault Cannon': '突击加农炮',
'Blassty Blaster': '摧毁者破坏炮',
'Blassty Charge': '摧毁者冲击',
'Blastoff': '准备升空',
'(?<!Blassty )Charge': '刺冲',
'E\\.D\\.D\\. Add': '护航机甲出现',
'E\\.D\\.D\\. Armored Pauldron': '护航机甲肩部装甲',
'Eternal Darkness': '黑暗命运',
'GA-100': '百式聚能炮',
'Lapis Lazuli': '天青石',
'Laser X Sword': '交叉光剑',
'Left/Right Laser Sword': '左/右光剑',
'Limit Cut': '限制器减档',
'Markers': '标记',
'Multifield': '层积科学结界',
'Optical Sight': '制导',
'Perfect Landing': '着陆',
'Photon': '光子炮',
'Plasma Shield': '等离子护盾',
'Plasmasphere': '等离子球',
'Propeller Wind': '螺旋桨强风',
'Spin Crusher': '回旋碎踢',
'Super Hawk Blaster': '超级鹰式破坏炮',
'Transform': '变形',
'Whirlwind': '龙卷风',
},
},
{
'locale': 'ko',
'replaceSync': {
'Armored Pauldron': '견갑부',
'Claster': '클래스터',
'Cruise Chaser': '순항추격기',
'E\\\\.D\\\\.D\\\\.': 'E\\.D\\.D\\.',
'Multifield': '적층과학 필드',
'Plasma Shield': '플라스마 방어막',
'The Main Generators': '중추 대동력실',
},
'replaceText': {
'(?<! )Sword': '알파검',
'(?<!Super )Hawk Blaster': '호크 블래스터',
'--invincible--': '--무적--',
'\\(bait\\)': '(유도)',
'\\(clock/out\\)': '(시계방향/밖)',
'\\(everyone\\)': '(모두)',
'\\(numbers\\)': '(주사위)',
'\\(orbs\\)': '(구슬)',
'\\(out/clock\\)': '(밖/시계방향)',
'\\(shield\\)': '(방어막)',
'Assault Cannon': '맹공포',
'Blassty Blaster': '블래스티 블래스터',
'Blassty Charge': '블래스티 돌진',
'Blastoff': '발진',
'(?<!Blassty )Charge': '돌격',
'E\\.D\\.D\\. Add': 'E.D.D. 등장',
'E\\.D\\.D\\. Armored Pauldron': 'E.D.D. 견갑부',
'Eternal Darkness': '암흑의 운명',
'GA-100': 'GA-100',
'Lapis Lazuli': '청금석',
'Laser X Sword': '레이저 교차베기',
'Left/Right Laser Sword': '왼쪽/오른쪽 레이저 베기',
'Limit Cut': '리미터 해제',
'Markers': '징',
'Multifield': '적층과학 필드',
'Optical Sight': '조준',
'Perfect Landing': '착륙',
'Photon': '광자',
'Plasma Shield': '플라스마 방어막',
'Plasmasphere': '플라스마 구체',
'Propeller Wind': '추진 돌풍',
'Spin Crusher': '회전 분쇄',
'Super Hawk Blaster': '슈퍼 호크 블래스터',
'Transform': '비행형 변신',
'Whirlwind': '회오리바람',
},
},
],
};
export default triggerSet; | the_stack |
import {loadChannelsForTeam, setChannelRetryFailed} from '@actions/views/channel';
import {getPostsSince} from '@actions/views/post';
import {loadMe} from '@actions/views/user';
import {Client4} from '@client/rest';
import {WebsocketEvents} from '@constants';
import {ChannelTypes, GeneralTypes, PreferenceTypes, TeamTypes, UserTypes, RoleTypes} from '@mm-redux/action_types';
import {getThreads} from '@mm-redux/actions/threads';
import {getProfilesByIds, getStatusesByIds} from '@mm-redux/actions/users';
import {General} from '@mm-redux/constants';
import {getCurrentChannelId, getCurrentChannelStats} from '@mm-redux/selectors/entities/channels';
import {getConfig} from '@mm-redux/selectors/entities/general';
import {getPostIdsInChannel} from '@mm-redux/selectors/entities/posts';
import {isCollapsedThreadsEnabled} from '@mm-redux/selectors/entities/preferences';
import {getCurrentTeamId} from '@mm-redux/selectors/entities/teams';
import {getCurrentUserId, getUsers, getUserStatuses} from '@mm-redux/selectors/entities/users';
import {ActionResult, DispatchFunc, GenericAction, GetStateFunc, batchActions} from '@mm-redux/types/actions';
import {Channel, ChannelMembership} from '@mm-redux/types/channels';
import {GlobalState} from '@mm-redux/types/store';
import {TeamMembership} from '@mm-redux/types/teams';
import {WebSocketMessage} from '@mm-redux/types/websocket';
import EventEmitter from '@mm-redux/utils/event_emitter';
import {removeUserFromList} from '@mm-redux/utils/user_utils';
import {getChannelSinceValue} from '@utils/channels';
import websocketClient from '@websocket';
import {handleRefreshAppsBindings} from './apps';
import {handleSidebarCategoryCreated, handleSidebarCategoryDeleted, handleSidebarCategoryOrderUpdated, handleSidebarCategoryUpdated} from './categories';
import {
handleChannelConvertedEvent,
handleChannelCreatedEvent,
handleChannelDeletedEvent,
handleChannelMemberUpdatedEvent,
handleChannelSchemeUpdatedEvent,
handleChannelUnarchiveEvent,
handleChannelUpdatedEvent,
handleChannelViewedEvent,
handleDirectAddedEvent,
handleUpdateMemberRoleEvent,
} from './channels';
import {handleConfigChangedEvent, handleLicenseChangedEvent} from './general';
import {handleGroupUpdatedEvent} from './groups';
import {handleOpenDialogEvent} from './integrations';
import {handleNewPostEvent, handlePostDeleted, handlePostEdited, handlePostUnread} from './posts';
import {handlePreferenceChangedEvent, handlePreferencesChangedEvent, handlePreferencesDeletedEvent} from './preferences';
import {handleAddEmoji, handleReactionAddedEvent, handleReactionRemovedEvent} from './reactions';
import {handleRoleAddedEvent, handleRoleRemovedEvent, handleRoleUpdatedEvent} from './roles';
import {handleLeaveTeamEvent, handleUpdateTeamEvent, handleTeamAddedEvent} from './teams';
import {handleThreadUpdated, handleThreadReadChanged, handleThreadFollowChanged} from './threads';
import {handleStatusChangedEvent, handleUserAddedEvent, handleUserRemovedEvent, handleUserRoleUpdated, handleUserUpdatedEvent} from './users';
export function init(additionalOptions: any = {}) {
return async (dispatch: DispatchFunc, getState: GetStateFunc) => {
const config = getConfig(getState());
let connUrl = additionalOptions.websocketUrl || config.WebsocketURL || Client4.getUrl();
const authToken = Client4.getToken();
connUrl += `${Client4.getUrlVersion()}/websocket`;
websocketClient.setFirstConnectCallback(() => dispatch(handleFirstConnect()));
websocketClient.setEventCallback((evt: WebSocketMessage) => dispatch(handleEvent(evt)));
websocketClient.setMissedEventsCallback(() => dispatch(doMissedEvents()));
websocketClient.setReconnectCallback(() => dispatch(handleReconnect()));
websocketClient.setCloseCallback((connectFailCount: number) => dispatch(handleClose(connectFailCount)));
const websocketOpts = {
connectionUrl: connUrl,
...additionalOptions,
};
return websocketClient.initialize(authToken, websocketOpts);
};
}
let reconnect = false;
export function close(shouldReconnect = false): GenericAction {
reconnect = shouldReconnect;
websocketClient.close(true);
return {
type: GeneralTypes.WEBSOCKET_CLOSED,
timestamp: Date.now(),
data: null,
};
}
function wsConnected(timestamp = Date.now()) {
return {
type: GeneralTypes.WEBSOCKET_SUCCESS,
timestamp,
data: null,
};
}
export function doFirstConnect(now: number) {
return async (dispatch: DispatchFunc, getState: GetStateFunc): Promise<ActionResult> => {
const state = getState();
const {lastDisconnectAt} = state.websocket;
const actions: Array<GenericAction> = [wsConnected(now)];
if (lastDisconnectAt) {
const currentUserId = getCurrentUserId(state);
const users = getUsers(state);
const userIds = Object.keys(users);
const userUpdates = await Client4.getProfilesByIds(userIds, {since: lastDisconnectAt});
if (userUpdates.length) {
removeUserFromList(currentUserId, userUpdates);
actions.push({
type: UserTypes.RECEIVED_PROFILES_LIST,
data: userUpdates,
});
}
}
dispatch(batchActions(actions, 'BATCH_WS_CONNCET'));
return {data: true};
};
}
export function doMissedEvents() {
return async (dispatch: DispatchFunc): Promise<ActionResult> => {
dispatch(wsConnected());
return {data: true};
};
}
export function doReconnect(now: number) {
return async (dispatch: DispatchFunc, getState: GetStateFunc): Promise<ActionResult> => {
const state = getState();
const currentTeamId = getCurrentTeamId(state);
const currentChannelId = getCurrentChannelId(state);
const currentUserId = getCurrentUserId(state);
const users = getUsers(state);
const {lastDisconnectAt} = state.websocket;
const actions: Array<GenericAction> = [];
dispatch(batchActions([
wsConnected(now),
setChannelRetryFailed(false),
], 'BATCH_WS_SUCCESS'));
try {
const {data: me}: any = await dispatch(loadMe(null, null, true));
if (!me.error) {
const roles = [];
if (me.roles?.length) {
roles.push(...me.roles);
}
actions.push({
type: UserTypes.RECEIVED_ME,
data: me.user,
}, {
type: PreferenceTypes.RECEIVED_ALL_PREFERENCES,
data: me.preferences,
}, {
type: TeamTypes.RECEIVED_MY_TEAM_UNREADS,
data: me.teamUnreads,
}, {
type: TeamTypes.RECEIVED_TEAMS_LIST,
data: me.teams,
}, {
type: TeamTypes.RECEIVED_MY_TEAM_MEMBERS,
data: me.teamMembers,
});
const currentTeamMembership = me.teamMembers.find((tm: TeamMembership) => tm.team_id === currentTeamId && tm.delete_at === 0);
if (currentTeamMembership) {
const {data: myData}: any = await dispatch(loadChannelsForTeam(currentTeamId, true, true));
if (myData?.channels && myData?.channelMembers) {
actions.push({
type: ChannelTypes.RECEIVED_MY_CHANNELS_WITH_MEMBERS,
data: myData,
});
if (isCollapsedThreadsEnabled(state)) {
dispatch(getThreads(currentUserId, currentTeamId, '', '', undefined, false, false, (state.websocket?.lastDisconnectAt || Date.now())));
}
const stillMemberOfCurrentChannel = myData.channelMembers.find((cm: ChannelMembership) => cm.channel_id === currentChannelId);
const channelStillExists = myData.channels.find((c: Channel) => c.id === currentChannelId);
const config = me.config || getConfig(getState());
const viewArchivedChannels = config.ExperimentalViewArchivedChannels === 'true';
if (!stillMemberOfCurrentChannel || !channelStillExists || (!viewArchivedChannels && channelStillExists.delete_at !== 0)) {
EventEmitter.emit(General.SWITCH_TO_DEFAULT_CHANNEL, currentTeamId);
} else {
const postIds = getPostIdsInChannel(state, currentChannelId);
const since = getChannelSinceValue(state, currentChannelId, postIds);
dispatch(getPostsSince(currentChannelId, since));
}
}
if (myData.roles?.length) {
roles.push(...myData.roles);
}
} else {
// If the user is no longer a member of this team when reconnecting
const newMsg = {
data: {
user_id: currentUserId,
team_id: currentTeamId,
},
};
dispatch(handleLeaveTeamEvent(newMsg));
}
if (roles.length) {
actions.push({
type: RoleTypes.RECEIVED_ROLES,
data: roles,
});
}
if (lastDisconnectAt) {
const userIds = Object.keys(users);
const userUpdates = await Client4.getProfilesByIds(userIds, {since: lastDisconnectAt});
if (userUpdates.length) {
removeUserFromList(currentUserId, userUpdates);
actions.push({
type: UserTypes.RECEIVED_PROFILES_LIST,
data: userUpdates,
});
}
}
if (actions.length) {
dispatch(batchActions(actions, 'BATCH_WS_RECONNECT'));
}
}
} catch (e) {
// do nothing
}
return {data: true};
};
}
export function handleUserTypingEvent(msg: WebSocketMessage) {
return (dispatch: DispatchFunc, getState: GetStateFunc): ActionResult => {
const state = getState();
const currentChannelId = getCurrentChannelId(state);
if (currentChannelId === msg.broadcast.channel_id) {
const profiles = getUsers(state);
const statuses = getUserStatuses(state);
const currentUserId = getCurrentUserId(state);
const config = getConfig(state);
const userId = msg.data.user_id;
const data = {
id: msg.broadcast.channel_id + msg.data.parent_id,
userId,
now: Date.now(),
};
dispatch({
type: WebsocketEvents.TYPING,
data,
});
setTimeout(() => {
const newState = getState();
const {typing} = newState.entities;
if (typing && typing[data.id]) {
dispatch({
type: WebsocketEvents.STOP_TYPING,
data,
});
}
}, parseInt(config.TimeBetweenUserTypingUpdatesMilliseconds!, 10));
if (!profiles[userId] && userId !== currentUserId) {
dispatch(getProfilesByIds([userId]));
}
const status = statuses[userId];
if (status !== General.ONLINE) {
dispatch(getStatusesByIds([userId]));
}
}
return {data: true};
};
}
function handleFirstConnect() {
return (dispatch: DispatchFunc, getState: GetStateFunc) => {
const state = getState();
const config = getConfig(state);
const now = Date.now();
if (reconnect && config?.EnableReliableWebSockets !== 'true') {
reconnect = false;
return dispatch(doReconnect(now));
}
return dispatch(doFirstConnect(now));
};
}
function handleReconnect() {
return (dispatch: DispatchFunc) => {
return dispatch(doReconnect(Date.now()));
};
}
function handleClose(connectFailCount: number) {
return {
type: GeneralTypes.WEBSOCKET_FAILURE,
error: connectFailCount,
data: null,
timestamp: Date.now(),
};
}
function handleEvent(msg: WebSocketMessage) {
return (dispatch: DispatchFunc) => {
switch (msg.event) {
case WebsocketEvents.POSTED:
case WebsocketEvents.EPHEMERAL_MESSAGE:
return dispatch(handleNewPostEvent(msg));
case WebsocketEvents.POST_EDITED:
return dispatch(handlePostEdited(msg));
case WebsocketEvents.POST_DELETED:
return dispatch(handlePostDeleted(msg));
case WebsocketEvents.POST_UNREAD:
return dispatch(handlePostUnread(msg));
case WebsocketEvents.LEAVE_TEAM:
return dispatch(handleLeaveTeamEvent(msg));
case WebsocketEvents.UPDATE_TEAM:
return dispatch(handleUpdateTeamEvent(msg));
case WebsocketEvents.ADDED_TO_TEAM:
return dispatch(handleTeamAddedEvent(msg));
case WebsocketEvents.USER_ADDED:
return dispatch(handleUserAddedEvent(msg));
case WebsocketEvents.USER_REMOVED:
return dispatch(handleUserRemovedEvent(msg));
case WebsocketEvents.USER_UPDATED:
return dispatch(handleUserUpdatedEvent(msg));
case WebsocketEvents.ROLE_ADDED:
return dispatch(handleRoleAddedEvent(msg));
case WebsocketEvents.ROLE_REMOVED:
return dispatch(handleRoleRemovedEvent(msg));
case WebsocketEvents.ROLE_UPDATED:
return dispatch(handleRoleUpdatedEvent(msg));
case WebsocketEvents.USER_ROLE_UPDATED:
return dispatch(handleUserRoleUpdated(msg));
case WebsocketEvents.MEMBERROLE_UPDATED:
return dispatch(handleUpdateMemberRoleEvent(msg));
case WebsocketEvents.CHANNEL_CREATED:
return dispatch(handleChannelCreatedEvent(msg));
case WebsocketEvents.CHANNEL_DELETED:
return dispatch(handleChannelDeletedEvent(msg));
case WebsocketEvents.CHANNEL_UNARCHIVED:
return dispatch(handleChannelUnarchiveEvent(msg));
case WebsocketEvents.CHANNEL_UPDATED:
return dispatch(handleChannelUpdatedEvent(msg));
case WebsocketEvents.CHANNEL_CONVERTED:
return dispatch(handleChannelConvertedEvent(msg));
case WebsocketEvents.CHANNEL_VIEWED:
return dispatch(handleChannelViewedEvent(msg));
case WebsocketEvents.CHANNEL_MEMBER_UPDATED:
return dispatch(handleChannelMemberUpdatedEvent(msg));
case WebsocketEvents.CHANNEL_SCHEME_UPDATED:
return dispatch(handleChannelSchemeUpdatedEvent(msg));
case WebsocketEvents.DIRECT_ADDED:
return dispatch(handleDirectAddedEvent(msg));
case WebsocketEvents.PREFERENCE_CHANGED:
return dispatch(handlePreferenceChangedEvent(msg));
case WebsocketEvents.PREFERENCES_CHANGED:
return dispatch(handlePreferencesChangedEvent(msg));
case WebsocketEvents.PREFERENCES_DELETED:
return dispatch(handlePreferencesDeletedEvent(msg));
case WebsocketEvents.STATUS_CHANGED:
return dispatch(handleStatusChangedEvent(msg));
case WebsocketEvents.TYPING:
return dispatch(handleUserTypingEvent(msg));
case WebsocketEvents.HELLO:
handleHelloEvent(msg);
break;
case WebsocketEvents.REACTION_ADDED:
return dispatch(handleReactionAddedEvent(msg));
case WebsocketEvents.REACTION_REMOVED:
return dispatch(handleReactionRemovedEvent(msg));
case WebsocketEvents.EMOJI_ADDED:
return dispatch(handleAddEmoji(msg));
case WebsocketEvents.LICENSE_CHANGED:
return dispatch(handleLicenseChangedEvent(msg));
case WebsocketEvents.CONFIG_CHANGED:
return dispatch(handleConfigChangedEvent(msg));
case WebsocketEvents.OPEN_DIALOG:
return dispatch(handleOpenDialogEvent(msg));
case WebsocketEvents.RECEIVED_GROUP:
return dispatch(handleGroupUpdatedEvent(msg));
case WebsocketEvents.THREAD_UPDATED:
return dispatch(handleThreadUpdated(msg));
case WebsocketEvents.THREAD_READ_CHANGED:
return dispatch(handleThreadReadChanged(msg));
case WebsocketEvents.THREAD_FOLLOW_CHANGED:
return dispatch(handleThreadFollowChanged(msg));
case WebsocketEvents.APPS_FRAMEWORK_REFRESH_BINDINGS:
return dispatch(handleRefreshAppsBindings());
case WebsocketEvents.SIDEBAR_CATEGORY_CREATED:
return dispatch(handleSidebarCategoryCreated(msg));
case WebsocketEvents.SIDEBAR_CATEGORY_UPDATED:
return dispatch(handleSidebarCategoryUpdated(msg));
case WebsocketEvents.SIDEBAR_CATEGORY_DELETED:
return dispatch(handleSidebarCategoryDeleted(msg));
case WebsocketEvents.SIDEBAR_CATEGORY_ORDER_UPDATED:
return dispatch(handleSidebarCategoryOrderUpdated(msg));
}
return {data: true};
};
}
function handleHelloEvent(msg: WebSocketMessage) {
const serverVersion = msg.data.server_version;
if (serverVersion && Client4.serverVersion !== serverVersion) {
Client4.serverVersion = serverVersion;
EventEmitter.emit(General.SERVER_VERSION_CHANGED, serverVersion);
}
}
// Helpers
let lastTimeTypingSent = 0;
export function userTyping(state: GlobalState, channelId: string, parentPostId: string): void {
const config = getConfig(state);
const t = Date.now();
const stats = getCurrentChannelStats(state);
const membersInChannel = stats ? stats.member_count : 0;
if (((t - lastTimeTypingSent) > parseInt(config.TimeBetweenUserTypingUpdatesMilliseconds!, 10)) &&
(membersInChannel < parseInt(config.MaxNotificationsPerChannel!, 10)) && (config.EnableUserTypingMessages === 'true')) {
websocketClient.userTyping(channelId, parentPostId);
lastTimeTypingSent = t;
}
} | the_stack |
import { QueryClientContract } from '@ioc:Adonis/Lucid/Database'
import { LucidRow, LucidModel, ModelAdapterOptions, ModelObject } from '@ioc:Adonis/Lucid/Orm'
import {
FactoryModelContract,
FactoryContextContract,
FactoryBuilderContract,
FactoryRelationContract,
} from '@ioc:Adonis/Lucid/Factory'
import { FactoryModel } from './FactoryModel'
import { FactoryContext } from './FactoryContext'
/**
* Factory builder exposes the API to create/persist factory model instances.
*/
export class FactoryBuilder implements FactoryBuilderContract<FactoryModelContract<LucidModel>> {
/**
* Relationships to setup. Do note: It is possible to load one relationship
* twice. A practical use case is to apply different states. For example:
*
* Make user with "3 active posts" and "2 draft posts"
*/
private withRelations: {
name: string
count?: number
callback?: (factory: any) => void
}[] = []
/**
* An array of callbacks to execute before persisting the model instance
*/
private tapCallbacks: ((row: LucidRow, state: FactoryContextContract, builder: this) => void)[] =
[]
/**
* Belongs to relationships are treated different, since they are
* persisted before the parent model
*/
private withBelongsToRelations: {
name: string
count?: number
callback?: (factory: any) => void
}[] = []
/**
* The current index. Updated by `makeMany` and `createMany`
*/
private currentIndex = 0
/**
* Custom attributes to pass to model merge method
*/
private attributes: any = {}
/**
* Custom attributes to pass to relationship merge methods
*/
private recursiveAttributes: any = {}
/**
* States to apply. One state can be applied only once and hence
* a set is used.
*/
private appliedStates: Set<string> = new Set()
/**
* Custom context passed using `useCtx` method. It not defined, we will
* create one inline inside `create` and `make` methods
*/
private ctx?: FactoryContextContract
/**
* Pivot attributes for a many to many relationship
*/
private attributesForPivotTable?: ModelObject | ModelObject[]
/**
* Instead of relying on the `FactoryModelContract`, we rely on the
* `FactoryModel`, since it exposes certain API's required for
* the runtime operations and those API's are not exposed
* on the interface to keep the API clean
*/
constructor(
public factory: FactoryModel<LucidModel>,
private options?: ModelAdapterOptions,
/**
* The relationship via which this factory builder was
* created
*/ private viaRelation?: FactoryRelationContract
) {}
/**
* Access the parent relationship for which the model instance
* is created
*/
public get parent() {
return this.viaRelation ? this.viaRelation.parent : undefined
}
/**
* Returns factory state
*/
private async getCtx(isStubbed: boolean, withTransaction: boolean) {
if (withTransaction === false) {
return new FactoryContext(isStubbed, undefined)
}
const client = this.factory.model.$adapter.modelConstructorClient(
this.factory.model,
this.options
)
const trx = await client.transaction()
return new FactoryContext(isStubbed, trx)
}
/**
* Returns attributes to merge for a given index
*/
private getMergeAttributes(index: number) {
const attributes = Array.isArray(this.attributes) ? this.attributes[index] : this.attributes
const recursiveAttributes = Array.isArray(this.recursiveAttributes)
? this.recursiveAttributes[index]
: this.recursiveAttributes
return {
...recursiveAttributes,
...attributes,
}
}
/**
* Returns a new model instance with filled attributes
*/
private async getModelInstance(ctx: FactoryContextContract): Promise<LucidRow> {
const modelAttributes = await this.factory.define(ctx)
const modelInstance = this.factory.newUpModelInstance(
modelAttributes,
ctx,
this.factory.model,
this
)
this.factory.mergeAttributes(
modelInstance,
this.getMergeAttributes(this.currentIndex),
ctx,
this
)
return modelInstance
}
/**
* Apply states by invoking state callback
*/
private async applyStates(modelInstance: LucidRow, ctx: FactoryContextContract) {
for (let state of this.appliedStates) {
await this.factory.getState(state)(modelInstance, ctx, this)
}
}
/**
* Invoke tap callbacks
*/
private invokeTapCallback(modelInstance: LucidRow, ctx: FactoryContextContract) {
this.tapCallbacks.forEach((callback) => callback(modelInstance, ctx, this))
}
/**
* Compile factory by instantiating model instance, applying merge
* attributes, apply state
*/
private async compile(ctx: FactoryContext) {
try {
/**
* Newup the model instance
*/
const modelInstance = await this.getModelInstance(ctx)
/**
* Apply state
*/
await this.applyStates(modelInstance, ctx)
/**
* Invoke tap callbacks as the last step
*/
this.invokeTapCallback(modelInstance, ctx)
/**
* Pass pivot attributes to the relationship instance
*/
if (this.viaRelation && this.viaRelation.pivotAttributes) {
this.viaRelation.pivotAttributes(this.attributesForPivotTable || {})
}
return modelInstance
} catch (error) {
if (!this.ctx && ctx.$trx) {
await ctx.$trx.rollback()
}
throw error
}
}
/**
* Makes relationship instances. Call [[createRelation]] to
* also persist them.
*/
private async makeRelations(modelInstance: LucidRow, ctx: FactoryContextContract) {
for (let { name, count, callback } of this.withBelongsToRelations) {
const relation = this.factory.getRelation(name)
await relation
.useCtx(ctx)
.merge(this.recursiveAttributes)
.make(modelInstance, callback, count)
}
for (let { name, count, callback } of this.withRelations) {
const relation = this.factory.getRelation(name)
await relation
.useCtx(ctx)
.merge(this.recursiveAttributes)
.make(modelInstance, callback, count)
}
}
/**
* Makes and persists relationship instances
*/
private async createRelations(
modelInstance: LucidRow,
ctx: FactoryContextContract,
cycle: 'before' | 'after'
) {
const relationships = cycle === 'before' ? this.withBelongsToRelations : this.withRelations
for (let { name, count, callback } of relationships) {
const relation = this.factory.getRelation(name)
await relation
.useCtx(ctx)
.merge(this.recursiveAttributes)
.create(modelInstance, callback, count)
}
}
/**
* Persist the model instance along with its relationships
*/
private async persistModelInstance(modelInstance: LucidRow, ctx: FactoryContextContract) {
/**
* Fire the after "make" hook. There is no before make hook
*/
await this.factory.hooks.exec('after', 'make', this, modelInstance, ctx)
/**
* Fire the before "create" hook
*/
await this.factory.hooks.exec('before', 'create', this, modelInstance, ctx)
/**
* Sharing transaction with the model
*/
modelInstance.$trx = ctx.$trx
/**
* Create belongs to relationships before calling the save method. Even though
* we can update the foriegn key after the initial insert call, we avoid it
* for cases, where FK is a not nullable.
*/
await this.createRelations(modelInstance, ctx, 'before')
/**
* Persist model instance
*/
await modelInstance.save()
/**
* Create relationships that are meant to be created after the parent
* row. Basically all types of relationships except belongsTo
*/
await this.createRelations(modelInstance, ctx, 'after')
/**
* Fire after hook before the transaction is committed, so that
* hook can run db operations using the same transaction
*/
await this.factory.hooks.exec('after', 'create', this, modelInstance, ctx)
}
/**
* Define custom database connection
*/
public connection(connection: string): this {
this.options = this.options || {}
this.options.connection = connection
return this
}
/**
* Define custom query client
*/
public client(client: QueryClientContract): this {
this.options = this.options || {}
this.options.client = client
return this
}
/**
* Define custom context. Usually called by the relationships
* to share the parent context with relationship factory
*/
public useCtx(ctx: FactoryContextContract): this {
this.ctx = ctx
return this
}
/**
* Load relationship
*/
public with(name: string, count?: number, callback?: (factory: never) => void): this {
const relation = this.factory.getRelation(name)
if (relation.relation.type === 'belongsTo') {
this.withBelongsToRelations.push({ name, count, callback })
return this
}
this.withRelations.push({ name, count, callback })
return this
}
/**
* Apply one or more states. Multiple calls to apply a single
* state will be ignored
*/
public apply(...states: string[]): this {
states.forEach((state) => this.appliedStates.add(state))
return this
}
/**
* Fill custom set of attributes. They are passed down to the newUp
* method of the factory
*/
public merge(attributes: any) {
this.attributes = attributes
return this
}
/**
* Merge custom set of attributes with the correct factory builder
* model and all of its relationships as well
*/
public mergeRecursive(attributes: any): this {
this.recursiveAttributes = attributes
return this
}
/**
* Define pivot attributes when persisting a many to many
* relationship. Results in a noop, when not called
* for a many to many relationship
*/
public pivotAttributes(attributes: ModelObject | ModelObject[]): this {
this.attributesForPivotTable = attributes
return this
}
/**
* Tap into the persistence layer of factory builder. Allows one
* to modify the model instance just before it is persisted
* to the database
*/
public tap(
callback: (row: LucidRow, state: FactoryContextContract, builder: this) => void
): this {
this.tapCallbacks.push(callback)
return this
}
/**
* Make model instance. Relationships are not processed with the make function.
*/
public async make() {
const ctx = this.ctx || (await this.getCtx(false, false))
const modelInstance = await this.compile(ctx)
await this.factory.hooks.exec('after', 'make', this, modelInstance, ctx)
return modelInstance
}
/**
* Create many of the factory model instances
*/
public async makeMany(count: number) {
let modelInstances: LucidRow[] = []
const counter = new Array(count).fill(0).map((_, i) => i)
for (let index of counter) {
this.currentIndex = index
modelInstances.push(await this.make())
}
return modelInstances
}
/**
* Returns a model instance without persisting it to the database.
* Relationships are still loaded and states are also applied.
*/
public async makeStubbed() {
const ctx = this.ctx || (await this.getCtx(true, false))
const modelInstance = await this.compile(ctx)
await this.factory.hooks.exec('after', 'make', this, modelInstance, ctx)
await this.factory.hooks.exec('before', 'makeStubbed', this, modelInstance, ctx)
const id = modelInstance.$primaryKeyValue || this.factory.manager.getNextId(modelInstance)
modelInstance[this.factory.model.primaryKey] = id
/**
* Make relationships. The relationships will be not persisted
*/
await this.makeRelations(modelInstance, ctx)
/**
* Fire the after hook
*/
await this.factory.hooks.exec('after', 'makeStubbed', this, modelInstance, ctx)
return modelInstance
}
/**
* Create many of model factory instances
*/
public async makeStubbedMany(count: number) {
let modelInstances: LucidRow[] = []
const counter = new Array(count).fill(0).map((_, i) => i)
for (let index of counter) {
this.currentIndex = index
modelInstances.push(await this.makeStubbed())
}
return modelInstances
}
/**
* Similar to make, but also persists the model instance to the
* database.
*/
public async create() {
/**
* Use pre-defined ctx or create a new one
*/
const ctx = this.ctx || (await this.getCtx(false, true))
/**
* Compile a model instance
*/
const modelInstance = await this.compile(ctx)
try {
await this.persistModelInstance(modelInstance, ctx)
if (!this.ctx && ctx.$trx) {
await ctx.$trx.commit()
}
return modelInstance
} catch (error) {
if (!this.ctx && ctx.$trx) {
await ctx.$trx.rollback()
}
throw error
}
}
/**
* Create and persist many of factory model instances
*/
public async createMany(count: number) {
let modelInstances: LucidRow[] = []
/**
* Use pre-defined ctx or create a new one
*/
const ctx = this.ctx || (await this.getCtx(false, true))
const counter = new Array(count).fill(0).map((_, i) => i)
try {
for (let index of counter) {
this.currentIndex = index
/**
* Compile a model instance
*/
const modelInstance = await this.compile(ctx)
await this.persistModelInstance(modelInstance, ctx)
modelInstances.push(modelInstance)
}
if (!this.ctx && ctx.$trx) {
await ctx.$trx.commit()
}
return modelInstances
} catch (error) {
if (!this.ctx && ctx.$trx) {
await ctx.$trx.rollback()
}
throw error
}
}
} | the_stack |
"use strict";
import { Disposable, FileSystemWatcher, StatusBarAlignment, StatusBarItem, version, window, workspace } from "vscode";
import { Settings } from "./helpers/settings";
import { CommandNames, Constants, TelemetryEvents, TfvcTelemetryEvents } from "./helpers/constants";
import { CredentialManager } from "./helpers/credentialmanager";
import { Logger } from "./helpers/logger";
import { Strings } from "./helpers/strings";
import { UserAgentProvider } from "./helpers/useragentprovider";
import { Utils } from "./helpers/utils";
import { VsCodeUtils } from "./helpers/vscodeutils";
import { IButtonMessageItem } from "./helpers/vscodeutils.interfaces";
import { RepositoryContextFactory } from "./contexts/repocontextfactory";
import { IRepositoryContext, RepositoryType } from "./contexts/repositorycontext";
import { TeamServerContext } from "./contexts/servercontext";
import { TfvcContext } from "./contexts/tfvccontext";
import { Telemetry } from "./services/telemetry";
import { TeamServicesApi } from "./clients/teamservicesclient";
import { FeedbackClient } from "./clients/feedbackclient";
import { RepositoryInfoClient } from "./clients/repositoryinfoclient";
import { UserInfo } from "./info/userinfo";
import { CredentialInfo } from "./info/credentialinfo";
import { TeamExtension } from "./team-extension";
import { TfCommandLineRunner } from "./tfvc/tfcommandlinerunner";
import { TfvcExtension } from "./tfvc/tfvc-extension";
import { TfvcErrorCodes } from "./tfvc/tfvcerror";
import { TfvcSCMProvider } from "./tfvc/tfvcscmprovider";
import { TfvcRepository } from "./tfvc/tfvcrepository";
import * as path from "path";
import * as util from "util";
export class ExtensionManager implements Disposable {
private _teamServicesStatusBarItem: StatusBarItem;
private _feedbackStatusBarItem: StatusBarItem;
private _errorMessage: string;
private _feedbackClient: FeedbackClient;
private _serverContext: TeamServerContext;
private _repoContext: IRepositoryContext;
private _settings: Settings;
private _credentialManager : CredentialManager;
private _teamExtension: TeamExtension;
private _tfvcExtension: TfvcExtension;
private _scmProvider: TfvcSCMProvider;
public async Initialize(): Promise<void> {
await this.setupFileSystemWatcherOnConfig();
await this.initializeExtension(false /*reinitializing*/);
// Add the event listener for settings changes, then re-initialized the extension
if (workspace) {
workspace.onDidChangeConfiguration(() => {
Logger.LogDebug("Reinitializing due to onDidChangeConfiguration");
//FUTURE: Check to see if we really need to do the re-initialization
this.Reinitialize();
});
}
}
public get RepoContext(): IRepositoryContext {
return this._repoContext;
}
public get ServerContext(): TeamServerContext {
return this._serverContext;
}
public get CredentialManager(): CredentialManager {
return this._credentialManager;
}
public get FeedbackClient(): FeedbackClient {
return this._feedbackClient;
}
public get Settings(): Settings {
return this._settings;
}
public get Team(): TeamExtension {
return this._teamExtension;
}
public get Tfvc(): TfvcExtension {
return this._tfvcExtension;
}
//Meant to reinitialize the extension when coming back online
public Reinitialize(): void {
this.cleanup(true);
this.initializeExtension(true /*reinitializing*/);
}
public SendFeedback(): void {
//SendFeedback doesn't need to ensure the extension is initialized
FeedbackClient.SendFeedback();
}
//Ensure we have a TFS or Team Services-based repository. Otherwise, return false.
private ensureMinimalInitialization(): boolean {
if (!this._repoContext
|| !this._serverContext
|| !this._serverContext.RepoInfo.IsTeamFoundation) {
//If the user previously signed out (in this session of VS Code), show a message to that effect
if (this._teamExtension.IsSignedOut) {
this.setErrorStatus(Strings.UserMustSignIn, CommandNames.Signin);
} else {
this.setErrorStatus(Strings.NoRepoInformation);
}
return false;
}
return true;
}
//Checks to ensure we're good to go for running TFVC commands
public EnsureInitializedForTFVC(): boolean {
return this.ensureMinimalInitialization();
}
//Checks to ensure that Team Services functionality is ready to go.
public EnsureInitialized(expectedType: RepositoryType): boolean {
//Ensure we have a TFS or Team Services-based repository. Otherwise, return false.
if (!this.ensureMinimalInitialization()) {
return false;
}
//If we aren't the expected type and we also aren't ANY, determine which error to show.
//If we aren't ANY, then this If will handle Git and TFVC. So if we get past the first
//if, we're returning false either for Git or for TFVC (there's no other option)
if (expectedType !== this._repoContext.Type && expectedType !== RepositoryType.ANY) {
//If we already have an error message set, we're in an error state and use that message
if (this._errorMessage) {
return false;
}
//Display the message straightaway in this case (instead of using status bar)
if (expectedType === RepositoryType.GIT) {
VsCodeUtils.ShowErrorMessage(Strings.NotAGitRepository);
return false;
}
if (expectedType === RepositoryType.TFVC) {
VsCodeUtils.ShowErrorMessage(Strings.NotATfvcRepository);
return false;
}
}
//For TFVC, without a TeamProjectName, we can't initialize the Team Services functionality
if ((expectedType === RepositoryType.TFVC || expectedType === RepositoryType.ANY)
&& this._repoContext.Type === RepositoryType.TFVC
&& !this._repoContext.TeamProjectName) {
this.setErrorStatus(Strings.NoTeamProjectFound);
return false;
}
//Finally, if we set a global error message, there's an issue so we can't initialize.
if (this._errorMessage !== undefined) {
return false;
}
return true;
}
//Return value indicates whether a message was displayed
public DisplayErrorMessage(message?: string): boolean {
const msg: string = message ? message : this._errorMessage;
if (msg) {
VsCodeUtils.ShowErrorMessage(msg);
return true;
}
return false;
}
public DisplayWarningMessage(message: string): void {
VsCodeUtils.ShowWarningMessage(message);
}
//Logs an error to the logger and sends an exception to telemetry service
public ReportError(err: Error, message: string, showToUser: boolean = false): void {
const fullMessage = err ? message + " " + err : message;
// Log the message
Logger.LogError(fullMessage);
if (err && err.message) {
// Log additional information for debugging purposes
Logger.LogDebug(err.message);
}
// Show just the message to the user if needed
if (showToUser) {
this.DisplayErrorMessage(message);
}
// Send it to telemetry
if (err !== undefined && (Utils.IsUnauthorized(err) || Utils.IsOffline(err) || Utils.IsProxyIssue(err))) {
//Don't log exceptions for Unauthorized, Offline or Proxy scenarios
return;
}
Telemetry.SendException(err);
}
//Ensures a folder is open before attempting to run any command already shown in
//the Command Palette (and defined in package.json).
public RunCommand(funcToTry: (args) => void, ...args: string[]): void {
if (!workspace || !workspace.rootPath) {
this.DisplayErrorMessage(Strings.FolderNotOpened);
return;
}
funcToTry(args);
}
private displayNoCredentialsMessage(): void {
let error: string = Strings.NoTeamServerCredentialsRunSignin;
let displayError: string = Strings.NoTeamServerCredentialsRunSignin;
const messageItems: IButtonMessageItem[] = [];
if (this._serverContext.RepoInfo.IsTeamServices === true) {
messageItems.push({ title : Strings.LearnMore,
url : Constants.TokenLearnMoreUrl,
telemetryId: TelemetryEvents.TokenLearnMoreClick });
messageItems.push({ title : Strings.ShowMe,
url : Constants.TokenShowMeUrl,
telemetryId: TelemetryEvents.TokenShowMeClick });
//Need different messages for popup message and status bar
//Add the account name to the message to help the user
error = util.format(Strings.NoAccessTokenRunSignin, this._serverContext.RepoInfo.Account);
displayError = util.format(Strings.NoAccessTokenLearnMoreRunSignin, this._serverContext.RepoInfo.Account);
}
Logger.LogError(error);
this.setErrorStatus(error, CommandNames.Signin);
VsCodeUtils.ShowErrorMessage(displayError, ...messageItems);
}
private formatErrorLogMessage(err): string {
let logMsg: string = err.message;
if (err.stderr) { //Add stderr to logged message if we have it
logMsg = Utils.FormatMessage(`${logMsg} ${err.stderr}`);
}
return logMsg;
}
private async initializeExtension(reinitializing: boolean): Promise<void> {
//Set version of VSCode on the UserAgentProvider
UserAgentProvider.VSCodeVersion = version;
//Users could install without having a folder (workspace) open
this._settings = new Settings(); //We need settings before showing the Welcome message
Telemetry.Initialize(this._settings); //Need to initialize telemetry for showing welcome message
if (!reinitializing) {
await this.showFarewellMessage();
await this.showWelcomeMessage(); //Ensure we show the message before hooking workspace.onDidChangeConfiguration
}
//Don't initialize if we don't have a workspace
if (!workspace || !workspace.rootPath) {
return;
}
// Create the extensions
this._teamExtension = new TeamExtension(this);
this._tfvcExtension = new TfvcExtension(this);
//If Logging is enabled, the user must have used the extension before so we can enable
//it here. This will allow us to log errors when we begin processing TFVC commands.
Telemetry.SendEvent(TelemetryEvents.Installed); //Send event that the extension is installed (even if not used)
this.logStart(this._settings.LoggingLevel, workspace.rootPath);
this._teamServicesStatusBarItem = window.createStatusBarItem(StatusBarAlignment.Left, 100);
this._feedbackStatusBarItem = window.createStatusBarItem(StatusBarAlignment.Left, 96);
try {
//RepositoryContext has some initial information about the repository (what we can get without authenticating with server)
this._repoContext = await RepositoryContextFactory.CreateRepositoryContext(workspace.rootPath, this._settings);
if (this._repoContext) {
this.showFeedbackItem();
this.setupFileSystemWatcherOnHead();
this._serverContext = new TeamServerContext(this._repoContext.RemoteUrl);
//Now that we have a server context, we can update it on the repository context
RepositoryContextFactory.UpdateRepositoryContext(this._repoContext, this._serverContext);
this._feedbackClient = new FeedbackClient();
this._credentialManager = new CredentialManager();
this._credentialManager.GetCredentials(this._serverContext).then(async (creds: CredentialInfo) => {
if (!creds || !creds.CredentialHandler) {
this.displayNoCredentialsMessage();
return;
} else {
this._serverContext.CredentialInfo = creds;
Telemetry.Initialize(this._settings, this._serverContext); //Re-initialize the telemetry with the server context information
Logger.LogDebug("Started ApplicationInsights telemetry");
//Set up the client we need to talk to the server for more repository information
const repositoryInfoClient: RepositoryInfoClient = new RepositoryInfoClient(this._repoContext, CredentialManager.GetCredentialHandler());
Logger.LogInfo("Getting repository information with repositoryInfoClient");
Logger.LogDebug("RemoteUrl = " + this._repoContext.RemoteUrl);
try {
//At this point, we have either successfully called git.exe or tf.cmd (we just need to verify the remote urls)
//For Git repositories, we call vsts/info and get collection ids, etc.
//For TFVC, we have to (potentially) make multiple other calls to get collection ids, etc.
this._serverContext.RepoInfo = await repositoryInfoClient.GetRepositoryInfo();
//Now we need to go and get the authorized user information
const connectionUrl: string = (this._serverContext.RepoInfo.IsTeamServices === true ? this._serverContext.RepoInfo.AccountUrl : this._serverContext.RepoInfo.CollectionUrl);
const accountClient: TeamServicesApi = new TeamServicesApi(connectionUrl, [CredentialManager.GetCredentialHandler()]);
Logger.LogInfo("Getting connectionData with accountClient");
Logger.LogDebug("connectionUrl = " + connectionUrl);
try {
const settings: any = await accountClient.connect();
Logger.LogInfo("Retrieved connectionData with accountClient");
this.resetErrorStatus();
this._serverContext.UserInfo = new UserInfo(settings.authenticatedUser.id,
settings.authenticatedUser.providerDisplayName,
settings.authenticatedUser.customDisplayName);
this.initializeStatusBars();
await this.initializeClients(this._repoContext.Type);
this.sendStartupTelemetry();
Logger.LogInfo(`Sent extension start up telemetry`);
Logger.LogObject(settings);
this.logDebugInformation();
} catch (err) {
this.setErrorStatus(Utils.GetMessageForStatusCode(err, err.message), (err.statusCode === 401 ? CommandNames.Signin : undefined));
//Wrap err here to get a useful call stack
this.ReportError(new Error(err), Utils.GetMessageForStatusCode(err, err.message, "Failed to get results with accountClient: "));
}
} catch (err) {
//TODO: With TFVC, creating a RepositoryInfo can throw (can't get project collection, can't get team project, etc.)
// We get a 404 on-prem if we aren't TFS 2015 Update 2 or later and 'core id' error with TFS 2013 RTM (and likely later)
if (this._serverContext.RepoInfo.IsTeamFoundationServer === true &&
(err.statusCode === 404 || (err.message && err.message.indexOf("Failed to find api location for area: core id:") === 0))) {
this.setErrorStatus(Strings.UnsupportedServerVersion);
Logger.LogError(Strings.UnsupportedServerVersion);
Telemetry.SendEvent(TelemetryEvents.UnsupportedServerVersion);
} else {
this.setErrorStatus(Utils.GetMessageForStatusCode(err, err.message), (err.statusCode === 401 ? CommandNames.Signin : undefined));
//Wrap err here to get a useful call stack
this.ReportError(new Error(err), Utils.GetMessageForStatusCode(err, err.message, "Failed call with repositoryClient: "));
}
}
}
// Now that everything else is ready, create the SCM provider
try {
if (this._repoContext.Type === RepositoryType.TFVC) {
const tfvcContext: TfvcContext = <TfvcContext>this._repoContext;
this.sendTfvcConfiguredTelemetry(tfvcContext.TfvcRepository);
Logger.LogInfo(`Sent TFVC tooling telemetry`);
if (!this._scmProvider) {
Logger.LogDebug(`Initializing the TfvcSCMProvider`);
this._scmProvider = new TfvcSCMProvider(this);
await this._scmProvider.Initialize();
Logger.LogDebug(`Initialized the TfvcSCMProvider`);
} else {
Logger.LogDebug(`Re-initializing the TfvcSCMProvider`);
await this._scmProvider.Reinitialize();
Logger.LogDebug(`Re-initialized the TfvcSCMProvider`);
}
this.sendTfvcConnectedTelemetry(tfvcContext.TfvcRepository);
}
} catch (err) {
Logger.LogError(`Caught an exception during Tfvc SCM Provider initialization`);
const logMsg: string = this.formatErrorLogMessage(err);
Logger.LogError(logMsg);
if (err.tfvcErrorCode) {
this.setErrorStatus(err.message);
//Dispose of the Build and WIT status bar items so they don't show up (they should be re-created once a new folder is opened)
this._teamExtension.cleanup();
if (this.shouldDisplayTfvcError(err.tfvcErrorCode)) {
VsCodeUtils.ShowErrorMessage(err.message, ...err.messageOptions);
}
}
}
}).fail((err) => {
this.setErrorStatus(Utils.GetMessageForStatusCode(err, err.message), (err.statusCode === 401 ? CommandNames.Signin : undefined));
//If we can't get a requestHandler, report the error via the feedbackclient
const message: string = Utils.GetMessageForStatusCode(err, err.message, "Failed to get a credential handler");
Logger.LogError(message);
Telemetry.SendException(err);
});
}
} catch (err) {
const logMsg: string = this.formatErrorLogMessage(err);
Logger.LogError(logMsg);
//For now, don't report these errors via the FeedbackClient (TFVC errors could result from TfvcContext creation failing)
if (!err.tfvcErrorCode || this.shouldDisplayTfvcError(err.tfvcErrorCode)) {
this.setErrorStatus(err.message);
VsCodeUtils.ShowErrorMessage(err.message, ...err.messageOptions);
}
}
}
//Sends the "StartUp" event based on repository type
private sendStartupTelemetry(): void {
let event: string = TelemetryEvents.StartUp;
if (this._repoContext.Type === RepositoryType.TFVC) {
event = TfvcTelemetryEvents.StartUp;
} else if (this._repoContext.Type === RepositoryType.EXTERNAL) {
event = TelemetryEvents.ExternalRepository;
}
Telemetry.SendEvent(event);
}
//Sends telemetry based on values of the TfvcRepository (which TF tooling (Exe or CLC) is configured)
private sendTfvcConfiguredTelemetry(repository: TfvcRepository): void {
let event: string = TfvcTelemetryEvents.ExeConfigured;
if (!repository.IsExe) {
event = TfvcTelemetryEvents.ClcConfigured;
}
Telemetry.SendEvent(event);
//For now, this is simply an indication that users have configured that feature
if (repository.RestrictWorkspace) {
Telemetry.SendEvent(TfvcTelemetryEvents.RestrictWorkspace);
}
}
//Sends telemetry based on values of the TfvcRepository (which TF tooling (Exe or CLC) was connected)
private sendTfvcConnectedTelemetry(repository: TfvcRepository): void {
let event: string = TfvcTelemetryEvents.ExeConnected;
if (!repository.IsExe) {
event = TfvcTelemetryEvents.ClcConnected;
}
Telemetry.SendEvent(event);
}
//Determines which Tfvc errors to display in the status bar ui
private shouldDisplayTfvcError(errorCode: string): boolean {
if (TfvcErrorCodes.MinVersionWarning === errorCode ||
TfvcErrorCodes.NotFound === errorCode ||
TfvcErrorCodes.NotAuthorizedToAccess === errorCode ||
TfvcErrorCodes.NotAnEnuTfCommandLine === errorCode ||
TfvcErrorCodes.WorkspaceNotKnownToClc === errorCode) {
return true;
}
return false;
}
//Ensure this is async (and is awaited on) so that the extension doesn't continue until user deals with message
private async showWelcomeMessage(): Promise<void> {
if (this._settings.ShowWelcomeMessage) {
const welcomeMessage: string = `This is version ${Constants.ExtensionVersion} of the Azure Repos extension.`;
const messageItems: IButtonMessageItem[] = [];
messageItems.push({ title : Strings.LearnMore,
url : Constants.ReadmeLearnMoreUrl,
telemetryId : TelemetryEvents.WelcomeLearnMoreClick });
messageItems.push({ title : Strings.SetupTfvcSupport,
url : Constants.TfvcLearnMoreUrl,
telemetryId : TfvcTelemetryEvents.SetupTfvcSupportClick });
messageItems.push({ title : Strings.DontShowAgain });
const chosenItem: IButtonMessageItem = await VsCodeUtils.ShowInfoMessage(welcomeMessage, ...messageItems);
if (chosenItem && chosenItem.title === Strings.DontShowAgain) {
this._settings.ShowWelcomeMessage = false;
}
}
}
private async showFarewellMessage(): Promise<void> {
if (this._settings.ShowFarewellMessage) {
const farewellMessage: string = `The Azure Repos extension has been sunsetted.`;
const messageItems: IButtonMessageItem[] = [];
messageItems.push({ title : Strings.LearnMore,
url : Constants.FarewellLearnMoreUrl,
telemetryId : TelemetryEvents.FarewellLearnMoreClick });
messageItems.push({ title : Strings.DontShowAgain });
const chosenItem: IButtonMessageItem = await VsCodeUtils.ShowInfoMessage(farewellMessage, ...messageItems);
if (chosenItem && chosenItem.title === Strings.DontShowAgain) {
this._settings.ShowFarewellMessage = false;
}
}
}
//Set up the initial status bars
private initializeStatusBars(): void {
if (this.ensureMinimalInitialization()) {
this._teamServicesStatusBarItem.command = CommandNames.OpenTeamSite;
this._teamServicesStatusBarItem.text = this._serverContext.RepoInfo.TeamProject ? this._serverContext.RepoInfo.TeamProject : "<none>";
this._teamServicesStatusBarItem.tooltip = Strings.NavigateToTeamServicesWebSite;
this._teamServicesStatusBarItem.show();
if (this.EnsureInitialized(RepositoryType.ANY)) {
// Update the extensions
this._teamExtension.InitializeStatusBars();
//this._tfvcExtension.InitializeStatusBars();
}
}
}
//Set up the initial status bars
private async initializeClients(repoType: RepositoryType): Promise<void> {
await this._teamExtension.InitializeClients(repoType);
await this._tfvcExtension.InitializeClients(repoType);
}
private logDebugInformation(): void {
Logger.LogDebug("Account: " + this._serverContext.RepoInfo.Account + " "
+ "Team Project: " + this._serverContext.RepoInfo.TeamProject + " "
+ "Collection: " + this._serverContext.RepoInfo.CollectionName + " "
+ "Repository: " + this._serverContext.RepoInfo.RepositoryName + " "
+ "UserCustomDisplayName: " + this._serverContext.UserInfo.CustomDisplayName + " "
+ "UserProviderDisplayName: " + this._serverContext.UserInfo.ProviderDisplayName + " "
+ "UserId: " + this._serverContext.UserInfo.Id + " ");
Logger.LogDebug("repositoryFolder: " + this._repoContext.RepoFolder);
Logger.LogDebug("repositoryRemoteUrl: " + this._repoContext.RemoteUrl);
if (this._repoContext.Type === RepositoryType.GIT) {
Logger.LogDebug("gitRepositoryParentFolder: " + this._repoContext.RepositoryParentFolder);
Logger.LogDebug("gitCurrentBranch: " + this._repoContext.CurrentBranch);
Logger.LogDebug("gitCurrentRef: " + this._repoContext.CurrentRef);
}
Logger.LogDebug("IsSsh: " + this._repoContext.IsSsh);
Logger.LogDebug("proxy: " + (Utils.IsProxyEnabled() ? "enabled" : "not enabled")
+ ", azure devops services: " + this._serverContext.RepoInfo.IsTeamServices.toString());
}
private logStart(loggingLevel: string, rootPath: string): void {
if (loggingLevel === undefined) {
return;
}
Logger.SetLoggingLevel(loggingLevel);
if (rootPath !== undefined) {
Logger.LogPath = rootPath;
Logger.LogInfo(`*** FOLDER: ${rootPath} ***`);
Logger.LogInfo(`${UserAgentProvider.UserAgent}`);
} else {
Logger.LogInfo(`*** Folder not opened ***`);
}
}
private resetErrorStatus(): void {
this._errorMessage = undefined;
}
private setErrorStatus(message: string, commandOnClick?: string): void {
this._errorMessage = message;
if (this._teamServicesStatusBarItem !== undefined) {
//TODO: Should the default command be to display the message?
this._teamServicesStatusBarItem.command = commandOnClick; // undefined clears the command
this._teamServicesStatusBarItem.text = `Team $(stop)`;
this._teamServicesStatusBarItem.tooltip = message;
this._teamServicesStatusBarItem.show();
}
}
//Sets up a file system watcher on HEAD so we can know when the current branch has changed
private async setupFileSystemWatcherOnHead(): Promise<void> {
if (this._repoContext && this._repoContext.Type === RepositoryType.GIT) {
const pattern: string = this._repoContext.RepoFolder + "/HEAD";
const fsw:FileSystemWatcher = workspace.createFileSystemWatcher(pattern, true, false, true);
fsw.onDidChange(async (/*uri*/) => {
Logger.LogInfo("HEAD has changed, re-parsing RepoContext object");
this._repoContext = await RepositoryContextFactory.CreateRepositoryContext(workspace.rootPath, this._settings);
Logger.LogInfo("CurrentBranch is: " + this._repoContext.CurrentBranch);
this.notifyBranchChanged(/*this._repoContext.CurrentBranch*/);
});
}
}
private notifyBranchChanged(/*TODO: currentBranch: string*/): void {
this._teamExtension.NotifyBranchChanged();
//this._tfvcExtension.NotifyBranchChanged(currentBranch);
}
//Sets up a file system watcher on config so we can know when the remote origin has changed
private async setupFileSystemWatcherOnConfig(): Promise<void> {
//If we don't have a workspace, don't set up the file watcher
if (!workspace || !workspace.rootPath) {
return;
}
if (this._repoContext && this._repoContext.Type === RepositoryType.GIT) {
const pattern: string = path.join(workspace.rootPath, ".git", "config");
//We want to listen to file creation, change and delete events
const fsw:FileSystemWatcher = workspace.createFileSystemWatcher(pattern, false, false, false);
fsw.onDidCreate((/*uri*/) => {
//When a new local repo is initialized (e.g., git init), re-initialize the extension
Logger.LogInfo("config has been created, re-initializing the extension");
this.Reinitialize();
});
fsw.onDidChange(async (uri) => {
Logger.LogInfo("config has changed, checking if 'remote origin' changed");
const context: IRepositoryContext = await RepositoryContextFactory.CreateRepositoryContext(uri.fsPath, this._settings);
const remote: string = context.RemoteUrl;
if (remote === undefined) {
//There is either no remote defined yet or it isn't a Team Services repo
if (this._repoContext.RemoteUrl !== undefined) {
//We previously had a Team Services repo and now we don't, reinitialize
Logger.LogInfo("remote was removed, previously had an Azure Repos remote, re-initializing the extension");
this.Reinitialize();
return;
}
//There was no previous remote, so do nothing
Logger.LogInfo("remote does not exist, no previous Azure Repos remote, nothing to do");
} else if (this._repoContext !== undefined) {
//We have a valid gitContext already, check to see what changed
if (this._repoContext.RemoteUrl !== undefined) {
//The config has changed, and we had a Team Services remote already
if (remote.toLowerCase() !== this._repoContext.RemoteUrl.toLowerCase()) {
//And they're different, reinitialize
Logger.LogInfo("remote changed to a different Azure Repos remote, re-initializing the extension");
this.Reinitialize();
}
} else {
//The remote was initialized to a Team Services remote, reinitialize
Logger.LogInfo("remote initialized to an Azure Repos remote, re-initializing the extension");
this.Reinitialize();
}
}
});
fsw.onDidDelete((/*uri*/) => {
Logger.LogInfo("config has been deleted, re-initializing the extension");
this.Reinitialize();
});
}
}
private showFeedbackItem(): void {
this._feedbackStatusBarItem.command = CommandNames.SendFeedback;
this._feedbackStatusBarItem.text = `$(megaphone)`;
this._feedbackStatusBarItem.tooltip = Strings.SendFeedback;
this._feedbackStatusBarItem.show();
}
private cleanup(preserveTeamExtension: boolean = false): void {
if (this._teamServicesStatusBarItem) {
this._teamServicesStatusBarItem.dispose();
this._teamServicesStatusBarItem = undefined;
}
if (this._feedbackStatusBarItem !== undefined) {
this._feedbackStatusBarItem.dispose();
this._feedbackStatusBarItem = undefined;
}
//No matter if we're signing out or re-initializing, we need the team extension's
//status bars and timers to be disposed but not the entire object
this._teamExtension.cleanup();
//If we are signing out, we need to keep some of the objects around
if (!preserveTeamExtension && this._teamExtension) {
this._teamExtension.dispose();
this._teamExtension = undefined;
this._serverContext = undefined;
this._credentialManager = undefined;
if (this._tfvcExtension) {
this._tfvcExtension.dispose();
this._tfvcExtension = undefined;
}
if (this._scmProvider) {
this._scmProvider.dispose();
this._scmProvider = undefined;
}
//Make sure we clean up any running instances of TF
TfCommandLineRunner.DisposeStatics();
}
//The following will be reset during a re-initialization
this._repoContext = undefined;
this._settings = undefined;
this._errorMessage = undefined;
}
public dispose() {
this.cleanup();
}
//If we're signing out, we don't want to dispose of everything.
public SignOut(): void {
this.cleanup(true);
}
} | the_stack |
import * as coreClient from "@azure/core-client";
export interface ErrorModel {
status?: number;
message?: string;
}
/** Defines values for UriColor. */
export type UriColor = "red color" | "green color" | "blue color";
/** Optional parameters. */
export interface PathsGetBooleanTrueOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsGetBooleanFalseOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsGetIntOneMillionOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsGetIntNegativeOneMillionOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsGetTenBillionOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsGetNegativeTenBillionOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsFloatScientificPositiveOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsFloatScientificNegativeOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsDoubleDecimalPositiveOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsDoubleDecimalNegativeOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsStringUnicodeOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsStringUrlEncodedOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsStringUrlNonEncodedOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsStringEmptyOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsStringNullOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsEnumValidOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsEnumNullOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsByteMultiByteOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsByteEmptyOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsByteNullOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsDateValidOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsDateNullOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsDateTimeValidOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsDateTimeNullOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsBase64UrlOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsArrayCsvInPathOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PathsUnixTimeUrlOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesGetBooleanTrueOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesGetBooleanFalseOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesGetBooleanNullOptionalParams
extends coreClient.OperationOptions {
/** null boolean value */
boolQuery?: boolean;
}
/** Optional parameters. */
export interface QueriesGetIntOneMillionOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesGetIntNegativeOneMillionOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesGetIntNullOptionalParams
extends coreClient.OperationOptions {
/** null integer value */
intQuery?: number;
}
/** Optional parameters. */
export interface QueriesGetTenBillionOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesGetNegativeTenBillionOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesGetLongNullOptionalParams
extends coreClient.OperationOptions {
/** null 64 bit integer value */
longQuery?: number;
}
/** Optional parameters. */
export interface QueriesFloatScientificPositiveOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesFloatScientificNegativeOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesFloatNullOptionalParams
extends coreClient.OperationOptions {
/** null numeric value */
floatQuery?: number;
}
/** Optional parameters. */
export interface QueriesDoubleDecimalPositiveOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesDoubleDecimalNegativeOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesDoubleNullOptionalParams
extends coreClient.OperationOptions {
/** null numeric value */
doubleQuery?: number;
}
/** Optional parameters. */
export interface QueriesStringUnicodeOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesStringUrlEncodedOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesStringEmptyOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesStringNullOptionalParams
extends coreClient.OperationOptions {
/** null string value */
stringQuery?: string;
}
/** Optional parameters. */
export interface QueriesEnumValidOptionalParams
extends coreClient.OperationOptions {
/** 'green color' enum value */
enumQuery?: UriColor;
}
/** Optional parameters. */
export interface QueriesEnumNullOptionalParams
extends coreClient.OperationOptions {
/** null string value */
enumQuery?: UriColor;
}
/** Optional parameters. */
export interface QueriesByteMultiByteOptionalParams
extends coreClient.OperationOptions {
/** '啊齄丂狛狜隣郎隣兀﨩' multibyte value as utf-8 encoded byte array */
byteQuery?: Uint8Array;
}
/** Optional parameters. */
export interface QueriesByteEmptyOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesByteNullOptionalParams
extends coreClient.OperationOptions {
/** null as byte array (no query parameters in uri) */
byteQuery?: Uint8Array;
}
/** Optional parameters. */
export interface QueriesDateValidOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesDateNullOptionalParams
extends coreClient.OperationOptions {
/** null as date (no query parameters in uri) */
dateQuery?: Date;
}
/** Optional parameters. */
export interface QueriesDateTimeValidOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface QueriesDateTimeNullOptionalParams
extends coreClient.OperationOptions {
/** null as date-time (no query parameters) */
dateTimeQuery?: Date;
}
/** Optional parameters. */
export interface QueriesArrayStringCsvValidOptionalParams
extends coreClient.OperationOptions {
/** an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format */
arrayQuery?: string[];
}
/** Optional parameters. */
export interface QueriesArrayStringCsvNullOptionalParams
extends coreClient.OperationOptions {
/** a null array of string using the csv-array format */
arrayQuery?: string[];
}
/** Optional parameters. */
export interface QueriesArrayStringCsvEmptyOptionalParams
extends coreClient.OperationOptions {
/** an empty array [] of string using the csv-array format */
arrayQuery?: string[];
}
/** Optional parameters. */
export interface QueriesArrayStringNoCollectionFormatEmptyOptionalParams
extends coreClient.OperationOptions {
/** Array-typed query parameter. Pass in ['hello', 'nihao', 'bonjour']. */
arrayQuery?: string[];
}
/** Optional parameters. */
export interface QueriesArrayStringSsvValidOptionalParams
extends coreClient.OperationOptions {
/** an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the ssv-array format */
arrayQuery?: string[];
}
/** Optional parameters. */
export interface QueriesArrayStringTsvValidOptionalParams
extends coreClient.OperationOptions {
/** an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the tsv-array format */
arrayQuery?: string[];
}
/** Optional parameters. */
export interface QueriesArrayStringPipesValidOptionalParams
extends coreClient.OperationOptions {
/** an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the pipes-array format */
arrayQuery?: string[];
}
/** Optional parameters. */
export interface PathItemsGetAllWithValuesOptionalParams
extends coreClient.OperationOptions {
/** A string value 'pathItemStringQuery' that appears as a query parameter */
pathItemStringQuery?: string;
/** should contain value 'localStringQuery' */
localStringQuery?: string;
}
/** Optional parameters. */
export interface PathItemsGetGlobalQueryNullOptionalParams
extends coreClient.OperationOptions {
/** A string value 'pathItemStringQuery' that appears as a query parameter */
pathItemStringQuery?: string;
/** should contain value 'localStringQuery' */
localStringQuery?: string;
}
/** Optional parameters. */
export interface PathItemsGetGlobalAndLocalQueryNullOptionalParams
extends coreClient.OperationOptions {
/** A string value 'pathItemStringQuery' that appears as a query parameter */
pathItemStringQuery?: string;
/** should contain null value */
localStringQuery?: string;
}
/** Optional parameters. */
export interface PathItemsGetLocalPathItemQueryNullOptionalParams
extends coreClient.OperationOptions {
/** should contain value null */
pathItemStringQuery?: string;
/** should contain value null */
localStringQuery?: string;
}
/** Optional parameters. */
export interface UrlClientOptionalParams
extends coreClient.ServiceClientOptions {
/** server parameter */
$host?: string;
/** should contain value null */
globalStringQuery?: string;
/** Overrides client endpoint. */
endpoint?: string;
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.